demux: fix a memory leak in flac & mpga when attachments are present
[vlc.git] / modules / demux / mpeg / mpga.c
1 /*****************************************************************************
2  * mpga.c : MPEG-I/II Audio input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2004 the VideoLAN team
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Gildas Bazin <gbazin@videolan.org>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28
29 #include <vlc/vlc.h>
30 #include <vlc_demux.h>
31 #include <vlc_codec.h>
32 #include <vlc_input.h>
33
34 #define MPGA_PACKET_SIZE 1024
35
36 /*****************************************************************************
37  * Module descriptor
38  *****************************************************************************/
39 static int  Open ( vlc_object_t * );
40 static void Close( vlc_object_t * );
41
42 vlc_module_begin();
43     set_category( CAT_INPUT );
44     set_subcategory( SUBCAT_INPUT_DEMUX );
45     set_description( _("MPEG audio / MP3 demuxer" ) );
46     set_capability( "demux2", 100 );
47     set_callbacks( Open, Close );
48     add_shortcut( "mpga" );
49     add_shortcut( "mp3" );
50 vlc_module_end();
51
52 /*****************************************************************************
53  * Local prototypes
54  *****************************************************************************/
55 static int Demux  ( demux_t * );
56 static int Control( demux_t *, int, va_list );
57
58 struct demux_sys_t
59 {
60     es_out_id_t *p_es;
61     vlc_meta_t  *meta;
62
63     vlc_bool_t  b_start;
64     decoder_t   *p_packetizer;
65
66     mtime_t     i_pts;
67     mtime_t     i_time_offset;
68     int         i_bitrate_avg;  /* extracted from Xing header */
69
70     vlc_bool_t b_initial_sync_failed;
71
72     int i_xing_frames;
73     int i_xing_bytes;
74     int i_xing_bitrate_avg;
75     int i_xing_frame_samples;
76     block_t *p_block_in, *p_block_out;
77
78     int                i_attachments;
79     input_attachment_t **attachments;
80 };
81
82 static int HeaderCheck( uint32_t h )
83 {
84     if( ((( h >> 21 )&0x07FF) != 0x07FF )   /* header sync */
85         || (((h >> 17)&0x03) == 0 )         /* valid layer ?*/
86         || (((h >> 12)&0x0F) == 0x0F )
87         || (((h >> 12)&0x0F) == 0x00 )      /* valid bitrate ? */
88         || (((h >> 10) & 0x03) == 0x03 )    /* valide sampling freq ? */
89         || ((h & 0x03) == 0x02 ))           /* valid emphasis ? */
90     {
91         return VLC_FALSE;
92     }
93     return VLC_TRUE;
94 }
95
96 #define MPGA_VERSION( h )   ( 1 - (((h)>>19)&0x01) )
97 #define MPGA_LAYER( h )     ( 3 - (((h)>>17)&0x03) )
98 #define MPGA_MODE(h)        (((h)>> 6)&0x03)
99
100 static int mpga_frame_samples( uint32_t h )
101 {
102     switch( MPGA_LAYER(h) )
103     {
104         case 0:
105             return 384;
106         case 1:
107             return 1152;
108         case 2:
109             return MPGA_VERSION(h) ? 576 : 1152;
110         default:
111             return 0;
112     }
113 }
114
115
116 /*****************************************************************************
117  * Open: initializes demux structures
118  *****************************************************************************/
119 static int Open( vlc_object_t * p_this )
120 {
121     demux_t     *p_demux = (demux_t*)p_this;
122     demux_sys_t *p_sys;
123     vlc_bool_t   b_forced = VLC_FALSE;
124
125     uint32_t     header;
126     const uint8_t     *p_peek;
127     module_t    *p_id3;
128     block_t     *p_block_in, *p_block_out;
129
130     if( demux2_IsPathExtension( p_demux, ".mp3" ) )
131         b_forced = VLC_TRUE;
132
133     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
134
135     if( !HeaderCheck( header = GetDWBE( p_peek ) ) )
136     {
137         vlc_bool_t b_ok = VLC_FALSE;
138         int i_peek;
139
140         if( !p_demux->b_force && !b_forced ) return VLC_EGENERIC;
141
142         i_peek = stream_Peek( p_demux->s, &p_peek, 8096 );
143         while( i_peek > 4 )
144         {
145             if( HeaderCheck( header = GetDWBE( p_peek ) ) )
146             {
147                 b_ok = VLC_TRUE;
148                 break;
149             }
150             p_peek += 1;
151             i_peek -= 1;
152         }
153         if( !b_ok && !p_demux->b_force ) return VLC_EGENERIC;
154     }
155
156     DEMUX_INIT_COMMON(); p_sys = p_demux->p_sys;
157     memset( p_sys, 0, sizeof( demux_sys_t ) );
158     p_sys->p_es = 0;
159     p_sys->b_start = VLC_TRUE;
160     p_sys->meta = 0;
161
162     /* Load the mpeg audio packetizer */
163     INIT_APACKETIZER( p_sys->p_packetizer, 'm', 'p', 'g', 'a' );
164     es_format_Init( &p_sys->p_packetizer->fmt_out, UNKNOWN_ES, 0 );
165     LOAD_PACKETIZER_OR_FAIL( p_sys->p_packetizer, "mpga" );
166
167     /* Xing header */
168     if( HeaderCheck( header ) )
169     {
170         int i_xing, i_skip;
171         const uint8_t *p_xing;
172
173         if( ( i_xing = stream_Peek( p_demux->s, &p_xing, 1024 ) ) < 21 )
174             return VLC_SUCCESS; /* No header */
175
176         if( MPGA_VERSION( header ) == 0 )
177         {
178             i_skip = MPGA_MODE( header ) != 3 ? 36 : 21;
179         }
180         else
181         {
182             i_skip = MPGA_MODE( header ) != 3 ? 21 : 13;
183         }
184
185         if( i_skip + 8 < i_xing && !strncmp( (char *)&p_xing[i_skip], "Xing", 4 ) )
186         {
187             unsigned int i_flags = GetDWBE( &p_xing[i_skip+4] );
188
189             p_xing += i_skip + 8;
190             i_xing -= i_skip + 8;
191
192             i_skip = 0;
193             if( i_flags&0x01 && i_skip + 4 <= i_xing )   /* XING_FRAMES */
194             {
195                 p_sys->i_xing_frames = GetDWBE( &p_xing[i_skip] );
196                 i_skip += 4;
197             }
198             if( i_flags&0x02 && i_skip + 4 <= i_xing )   /* XING_BYTES */
199             {
200                 p_sys->i_xing_bytes = GetDWBE( &p_xing[i_skip] );
201                 i_skip += 4;
202             }
203             if( i_flags&0x04 )   /* XING_TOC */
204             {
205                 i_skip += 100;
206             }
207
208             // FIXME: doesn't return the right bitrage average, at least
209             // with some MP3's
210             if( i_flags&0x08 && i_skip + 4 <= i_xing )   /* XING_VBR */
211             {
212                 p_sys->i_xing_bitrate_avg = GetDWBE( &p_xing[i_skip] );
213                 msg_Dbg( p_demux, "xing vbr value present (%d)",
214                          p_sys->i_xing_bitrate_avg );
215             }
216
217             if( p_sys->i_xing_frames > 0 && p_sys->i_xing_bytes > 0 )
218             {
219                 p_sys->i_xing_frame_samples = mpga_frame_samples( header );
220                 msg_Dbg( p_demux, "xing frames&bytes value present "
221                          "(%d bytes, %d frames, %d samples/frame)",
222                          p_sys->i_xing_bytes, p_sys->i_xing_frames,
223                          p_sys->i_xing_frame_samples );
224             }
225         }
226     }
227
228     if( ( p_block_in = stream_Block( p_demux->s, MPGA_PACKET_SIZE ) ) == NULL )
229     {
230         return VLC_EGENERIC;
231     }
232     p_block_in->i_pts = p_block_in->i_dts = 1;
233     p_block_out = p_sys->p_packetizer->pf_packetize(
234         p_sys->p_packetizer, &p_block_in );
235
236     if( p_block_out == NULL )
237     {
238         msg_Dbg( p_demux, "did not sync on first block" );
239         p_sys->b_initial_sync_failed = VLC_TRUE;
240     }
241     else
242         p_sys->b_initial_sync_failed = VLC_FALSE;
243
244     p_sys->i_bitrate_avg = p_sys->p_packetizer->fmt_out.i_bitrate;
245
246     if( p_sys->i_xing_bytes && p_sys->i_xing_frames &&
247         p_sys->i_xing_frame_samples )
248     {
249         p_sys->i_bitrate_avg = p_sys->i_xing_bytes * I64C(8) *
250             p_sys->p_packetizer->fmt_out.audio.i_rate /
251             p_sys->i_xing_frames / p_sys->i_xing_frame_samples;
252     }
253
254     p_sys->p_block_in = p_block_in;
255     p_sys->p_block_out = p_block_out;
256
257     /* Parse possible id3 header */
258     p_demux->p_private = malloc( sizeof( demux_meta_t ) );
259     if( !p_demux->p_private )
260         return VLC_ENOMEM;
261     if( ( p_id3 = module_Need( p_demux, "meta reader", NULL, 0 ) ) )
262     {
263         demux_meta_t *p_demux_meta = (demux_meta_t *)p_demux->p_private;
264         p_sys->meta = p_demux_meta->p_meta;
265         p_demux->p_private = NULL;
266         module_Unneed( p_demux, p_id3 );
267         p_sys->i_attachments = p_demux_meta->i_attachments;
268         p_sys->attachments = p_demux_meta->attachments;
269     }
270     free( p_demux->p_private );
271
272     /* */
273     p_sys->p_packetizer->fmt_out.b_packetized = VLC_TRUE;
274     vlc_audio_replay_gain_MergeFromMeta( &p_sys->p_packetizer->fmt_out.audio_replay_gain,
275                                          p_sys->meta );
276     p_sys->p_es = es_out_Add( p_demux->out,
277                               &p_sys->p_packetizer->fmt_out);
278     return VLC_SUCCESS;
279 }
280
281 /*****************************************************************************
282  * Demux: reads and demuxes data packets
283  *****************************************************************************
284  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
285  *****************************************************************************/
286 static int Demux( demux_t *p_demux )
287 {
288     demux_sys_t *p_sys = p_demux->p_sys;
289     block_t *p_block_in, *p_block_out;
290     if( p_sys->b_start )
291     {
292         p_sys->b_start = VLC_FALSE;
293         p_block_in = p_sys->p_block_in;
294         p_sys->p_block_in = NULL;
295         p_block_out = p_sys->p_block_out;
296         p_sys->p_block_out = NULL;
297     }
298     else
299     {
300         if( ( p_block_in = stream_Block( p_demux->s, MPGA_PACKET_SIZE ) )
301             == NULL )
302         {
303             return 0;
304         }
305         if( p_demux->p_sys->b_initial_sync_failed == VLC_TRUE )
306         {
307             p_block_in->i_pts = p_block_in->i_dts = 1;
308             /* Only try to resync once */
309             p_demux->p_sys->b_initial_sync_failed = 0;
310         }
311         else
312             p_block_in->i_pts = p_block_in->i_dts = 0;
313         p_block_out = p_sys->p_packetizer->pf_packetize(
314             p_sys->p_packetizer, &p_block_in );
315     }
316
317
318     while( p_block_out )
319     {
320         while( p_block_out )
321         {
322             block_t *p_next = p_block_out->p_next;
323
324             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block_out->i_dts );
325
326             p_block_out->p_next = NULL;
327             p_sys->i_pts = p_block_out->i_pts;
328             es_out_Send( p_demux->out, p_sys->p_es, p_block_out );
329
330             p_block_out = p_next;
331         }
332         p_block_out = p_sys->p_packetizer->pf_packetize(
333             p_sys->p_packetizer, &p_block_in );
334     }
335     return 1;
336 }
337
338 /*****************************************************************************
339  * Close: frees unused data
340  *****************************************************************************/
341 static void Close( vlc_object_t * p_this )
342 {
343     demux_t     *p_demux = (demux_t*)p_this;
344     demux_sys_t *p_sys = p_demux->p_sys;
345
346     DESTROY_PACKETIZER( p_sys->p_packetizer );
347     if( p_sys->meta ) vlc_meta_Delete( p_sys->meta );
348     if( p_sys->p_block_out ) block_Release( p_sys->p_block_out );
349
350     int i;
351     for( i = 0; i < p_sys->i_attachments; i++ )
352         free( p_sys->attachments[i] );
353     TAB_CLEAN( p_sys->i_attachments, p_sys->attachments);
354
355     free( p_sys );
356 }
357
358 /*****************************************************************************
359  * Control:
360  *****************************************************************************/
361 static int Control( demux_t *p_demux, int i_query, va_list args )
362 {
363     demux_sys_t *p_sys  = p_demux->p_sys;
364     int64_t *pi64;
365     vlc_meta_t *p_meta;
366     int i_ret;
367
368     input_attachment_t ***ppp_attach;
369     int *pi_int, i;
370
371     switch( i_query )
372     {
373         case DEMUX_GET_META:
374             p_meta = (vlc_meta_t *)va_arg( args, vlc_meta_t* );
375             vlc_meta_Merge( p_meta, p_sys->meta );
376             return VLC_SUCCESS;
377
378         case DEMUX_GET_ATTACHMENTS:
379             ppp_attach =
380                 (input_attachment_t***)va_arg( args, input_attachment_t*** );
381             pi_int = (int*)va_arg( args, int * );
382
383             if( p_sys->i_attachments <= 0 )
384                 return VLC_EGENERIC;
385
386             *pi_int = p_sys->i_attachments;
387             *ppp_attach = malloc( sizeof(input_attachment_t**) * p_sys->i_attachments );
388             for( i = 0; i < p_sys->i_attachments; i++ )
389                 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachments[i] );
390             return VLC_SUCCESS;
391
392         case DEMUX_GET_TIME:
393             pi64 = (int64_t*)va_arg( args, int64_t * );
394             *pi64 = p_sys->i_pts + p_sys->i_time_offset;
395             return VLC_SUCCESS;
396
397         case DEMUX_SET_TIME:
398             /* FIXME TODO: implement a high precision seek (with mp3 parsing)
399              * needed for multi-input */
400
401         default:
402             i_ret = demux2_vaControlHelper( p_demux->s, 0, -1,
403                                             p_sys->i_bitrate_avg, 1, i_query,
404                                             args );
405             /* No bitrate, we can't have it precisely, but we can compute
406              * a raw approximation with time/position */
407             if( i_ret && i_query == DEMUX_GET_LENGTH &&!p_sys->i_bitrate_avg )
408             {
409                 float f_pos = (double)( stream_Tell( p_demux->s ) ) /
410                               (double)( stream_Size( p_demux->s ) );
411                 /* The first few seconds are guaranteed to be very whacky,
412                  * don't bother trying ... Too bad */
413                 if( f_pos < 0.01 ||
414                     (p_sys->i_pts + p_sys->i_time_offset) < 8000000 )
415                     return VLC_EGENERIC;
416
417                 pi64 = (int64_t *)va_arg( args, int64_t * );
418                 *pi64 = (p_sys->i_pts + p_sys->i_time_offset) / f_pos;
419                 return VLC_SUCCESS;
420             }
421             if( !i_ret && p_sys->i_bitrate_avg > 0 &&
422                 (i_query == DEMUX_SET_POSITION || i_query == DEMUX_SET_TIME) )
423             {
424                 int64_t i_time = I64C(8000000) * stream_Tell(p_demux->s) /
425                     p_sys->i_bitrate_avg;
426
427                 /* Fix time_offset */
428                 if( i_time >= 0 ) p_sys->i_time_offset = i_time - p_sys->i_pts;
429             }
430             return i_ret;
431     }
432 }