]> git.sesse.net Git - vlc/blob - modules/demux/mpeg/es.c
Created the ES inside the Open() function of the ES demuxer.
[vlc] / modules / demux / mpeg / es.c
1 /*****************************************************************************
2  * es.c : Generic audio ES input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2008 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 #ifdef HAVE_CONFIG_H
30 # include "config.h"
31 #endif
32
33 #include <vlc_common.h>
34 #include <vlc_plugin.h>
35 #include <vlc_demux.h>
36 #include <vlc_codec.h>
37 #include <vlc_codecs.h>
38 #include <vlc_input.h>
39
40 #include "../../codec/a52.h"
41
42 /*****************************************************************************
43  * Module descriptor
44  *****************************************************************************/
45 static int  OpenAudio( vlc_object_t * );
46 static int  OpenVideo( vlc_object_t * );
47 static void Close    ( vlc_object_t * );
48
49 #define FPS_TEXT N_("Frames per Second")
50 #define FPS_LONGTEXT N_("This is the frame rate used as a fallback when " \
51     "playing MPEG video elementary streams.")
52
53 vlc_module_begin ()
54     set_category( CAT_INPUT )
55     set_subcategory( SUBCAT_INPUT_DEMUX )
56     set_description( N_("MPEG-I/II/4 / A52 / DTS / MLP audio" ) )
57     set_capability( "demux", 155 )
58     set_callbacks( OpenAudio, Close )
59
60     add_shortcut( "mpga", "mp3",
61                   "m4a", "mp4a", "aac",
62                   "ac3", "a52",
63                   "eac3",
64                   "dts",
65                   "mlp", "thd" )
66
67     add_submodule()
68     set_description( N_("MPEG-4 video" ) )
69     set_capability( "demux", 0 )
70     set_callbacks( OpenVideo, Close )
71     add_float( "es-fps", 25, FPS_TEXT, FPS_LONGTEXT, false )
72
73     add_shortcut( "m4v" )
74     add_shortcut( "mp4v" )
75 vlc_module_end ()
76
77 /*****************************************************************************
78  * Local prototypes
79  *****************************************************************************/
80 static int Demux  ( demux_t * );
81 static int Control( demux_t *, int, va_list );
82
83 typedef struct
84 {
85     vlc_fourcc_t i_codec;
86     bool       b_use_word;
87     const char *psz_name;
88     int  (*pf_probe)( demux_t *p_demux, int64_t *pi_offset );
89     int  (*pf_init)( demux_t *p_demux );
90 } codec_t;
91
92 struct demux_sys_t
93 {
94     codec_t codec;
95
96     es_out_id_t *p_es;
97
98     bool  b_start;
99     decoder_t   *p_packetizer;
100     block_t     *p_packetized_data;
101
102     mtime_t     i_pts;
103     mtime_t     i_time_offset;
104     int64_t     i_bytes;
105
106     bool        b_big_endian;
107     bool        b_estimate_bitrate;
108     int         i_bitrate_avg;  /* extracted from Xing header */
109
110     bool b_initial_sync_failed;
111
112     int i_packet_size;
113
114     int64_t i_stream_offset;
115
116     float   f_fps;
117
118     /* Mpga specific */
119     struct
120     {
121         int i_frames;
122         int i_bytes;
123         int i_bitrate_avg;
124         int i_frame_samples;
125     } xing;
126 };
127
128 static int MpgaProbe( demux_t *p_demux, int64_t *pi_offset );
129 static int MpgaInit( demux_t *p_demux );
130
131 static int AacProbe( demux_t *p_demux, int64_t *pi_offset );
132 static int AacInit( demux_t *p_demux );
133
134 static int EA52Probe( demux_t *p_demux, int64_t *pi_offset );
135 static int A52Probe( demux_t *p_demux, int64_t *pi_offset );
136 static int A52Init( demux_t *p_demux );
137
138 static int DtsProbe( demux_t *p_demux, int64_t *pi_offset );
139 static int DtsInit( demux_t *p_demux );
140
141 static int MlpProbe( demux_t *p_demux, int64_t *pi_offset );
142 static int MlpInit( demux_t *p_demux );
143
144 static int Parse( demux_t *p_demux, block_t **pp_output );
145
146 static const codec_t p_codecs[] = {
147     { VLC_CODEC_MP4A, false, "mp4 audio",  AacProbe,  AacInit },
148     { VLC_CODEC_MPGA, false, "mpeg audio", MpgaProbe, MpgaInit },
149     { VLC_CODEC_A52, true,  "a52 audio",  A52Probe,  A52Init },
150     { VLC_CODEC_EAC3, true,  "eac3 audio", EA52Probe, A52Init },
151     { VLC_CODEC_DTS, false, "dts audio",  DtsProbe,  DtsInit },
152     { VLC_CODEC_TRUEHD, false, "mlp audio",  MlpProbe,  MlpInit },
153
154     { 0, false, NULL, NULL, NULL }
155 };
156
157 static int VideoInit( demux_t *p_demux );
158
159 static const codec_t codec_m4v = {
160     VLC_CODEC_MP4V, false, "mp4 video", NULL,  VideoInit
161 };
162
163 /*****************************************************************************
164  * OpenCommon: initializes demux structures
165  *****************************************************************************/
166 static int OpenCommon( demux_t *p_demux,
167                        int i_cat, const codec_t *p_codec, int64_t i_bs_offset )
168 {
169     demux_sys_t *p_sys;
170
171     es_format_t fmt;
172
173     DEMUX_INIT_COMMON(); p_sys = p_demux->p_sys;
174     memset( p_sys, 0, sizeof( demux_sys_t ) );
175     p_sys->codec = *p_codec;
176     p_sys->p_es = NULL;
177     p_sys->b_start = true;
178     p_sys->i_stream_offset = i_bs_offset;
179     p_sys->b_estimate_bitrate = true;
180     p_sys->i_bitrate_avg = 0;
181     p_sys->b_big_endian = false;
182     p_sys->f_fps = var_InheritFloat( p_demux, "es-fps" );
183     p_sys->p_packetized_data = NULL;
184
185     if( stream_Seek( p_demux->s, p_sys->i_stream_offset ) )
186     {
187         free( p_sys );
188         return VLC_EGENERIC;
189     }
190
191     if( p_sys->codec.pf_init( p_demux ) )
192     {
193         free( p_sys );
194         return VLC_EGENERIC;
195     }
196
197     msg_Dbg( p_demux, "detected format %4.4s", (const char*)&p_sys->codec.i_codec );
198
199     /* Load the audio packetizer */
200     es_format_Init( &fmt, i_cat, p_sys->codec.i_codec );
201     p_sys->p_packetizer = demux_PacketizerNew( p_demux, &fmt, p_sys->codec.psz_name );
202     if( !p_sys->p_packetizer )
203     {
204         free( p_sys );
205         return VLC_EGENERIC;
206     }
207
208     while( vlc_object_alive( p_demux ) )
209     {
210         if( Parse( p_demux, &p_sys->p_packetized_data ) )
211             break;
212         if( p_sys->p_packetized_data )
213             break;
214     }
215     return VLC_SUCCESS;
216 }
217 static int OpenAudio( vlc_object_t *p_this )
218 {
219     demux_t *p_demux = (demux_t*)p_this;
220     for( int i = 0; p_codecs[i].i_codec != 0; i++ )
221     {
222         int64_t i_offset;
223         if( !p_codecs[i].pf_probe( p_demux, &i_offset ) )
224             return OpenCommon( p_demux, AUDIO_ES, &p_codecs[i], i_offset );
225     }
226     return VLC_EGENERIC;
227 }
228 static int OpenVideo( vlc_object_t *p_this )
229 {
230     demux_t *p_demux = (demux_t*)p_this;
231
232     /* Only m4v is supported for the moment */
233     bool b_m4v_ext    = demux_IsPathExtension( p_demux, ".m4v" );
234     bool b_m4v_forced = demux_IsForced( p_demux, "m4v" ) ||
235                         demux_IsForced( p_demux, "mp4v" );
236     if( !b_m4v_ext && !b_m4v_forced )
237         return VLC_EGENERIC;
238
239     const uint8_t *p_peek;
240     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
241         return VLC_EGENERIC;
242     if( p_peek[0] != 0x00 || p_peek[1] != 0x00 || p_peek[2] != 0x01 )
243     {
244         if( !b_m4v_forced)
245             return VLC_EGENERIC;
246         msg_Warn( p_demux,
247                   "this doesn't look like an MPEG ES stream, continuing anyway" );
248     }
249     return OpenCommon( p_demux, VIDEO_ES, &codec_m4v, 0 );
250 }
251 /*****************************************************************************
252  * Demux: reads and demuxes data packets
253  *****************************************************************************
254  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
255  *****************************************************************************/
256 static int Demux( demux_t *p_demux )
257 {
258     demux_sys_t *p_sys = p_demux->p_sys;
259
260     block_t *p_block_out = p_sys->p_packetized_data;
261     if( p_block_out )
262         p_sys->p_packetized_data = NULL;
263     else if( Parse( p_demux, &p_block_out ) )
264         return 0;
265
266     while( p_block_out )
267     {
268         block_t *p_next = p_block_out->p_next;
269
270         /* Correct timestamp */
271         if( p_sys->p_packetizer->fmt_out.i_cat == VIDEO_ES )
272         {
273             if( p_block_out->i_pts <= VLC_TS_INVALID &&
274                 p_block_out->i_dts <= VLC_TS_INVALID )
275                 p_block_out->i_dts = VLC_TS_0 + p_sys->i_pts + 1000000 / p_sys->f_fps;
276             if( p_block_out->i_dts > VLC_TS_INVALID )
277                 p_sys->i_pts = p_block_out->i_dts - VLC_TS_0;
278         }
279         else
280         {
281             p_sys->i_pts = p_block_out->i_pts - VLC_TS_0;
282         }
283
284         if( p_block_out->i_pts > VLC_TS_INVALID )
285         {
286             p_block_out->i_pts += p_sys->i_time_offset;
287         }
288         if( p_block_out->i_dts > VLC_TS_INVALID )
289         {
290             p_block_out->i_dts += p_sys->i_time_offset;
291             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block_out->i_dts );
292         }
293         /* Re-estimate bitrate */
294         if( p_sys->b_estimate_bitrate && p_sys->i_pts > INT64_C(500000) )
295             p_sys->i_bitrate_avg = 8*INT64_C(1000000)*p_sys->i_bytes/(p_sys->i_pts-1);
296         p_sys->i_bytes += p_block_out->i_buffer;
297
298
299         p_block_out->p_next = NULL;
300         es_out_Send( p_demux->out, p_sys->p_es, p_block_out );
301
302         p_block_out = p_next;
303     }
304     return 1;
305 }
306
307 /*****************************************************************************
308  * Close: frees unused data
309  *****************************************************************************/
310 static void Close( vlc_object_t * p_this )
311 {
312     demux_t     *p_demux = (demux_t*)p_this;
313     demux_sys_t *p_sys = p_demux->p_sys;
314
315     if( p_sys->p_packetized_data )
316         block_ChainRelease( p_sys->p_packetized_data );
317     demux_PacketizerDestroy( p_sys->p_packetizer );
318     free( p_sys );
319 }
320
321 /*****************************************************************************
322  * Control:
323  *****************************************************************************/
324 static int Control( demux_t *p_demux, int i_query, va_list args )
325 {
326     demux_sys_t *p_sys  = p_demux->p_sys;
327     int64_t *pi64;
328     bool *pb_bool;
329     int i_ret;
330     va_list args_save;
331
332     va_copy ( args_save, args );
333
334     switch( i_query )
335     {
336         case DEMUX_HAS_UNSUPPORTED_META:
337             pb_bool = (bool*)va_arg( args, bool* );
338             *pb_bool = true;
339             return VLC_SUCCESS;
340
341         case DEMUX_GET_TIME:
342             pi64 = (int64_t*)va_arg( args, int64_t * );
343             *pi64 = p_sys->i_pts + p_sys->i_time_offset;
344             return VLC_SUCCESS;
345
346         case DEMUX_GET_LENGTH:
347             i_ret = demux_vaControlHelper( p_demux->s, p_sys->i_stream_offset, -1,
348                                             p_sys->i_bitrate_avg, 1, i_query,
349                                             args );
350             /* No bitrate, we can't have it precisely, but we can compute
351              * a raw approximation with time/position */
352             if( i_ret && !p_sys->i_bitrate_avg )
353             {
354                 float f_pos = (double)(uint64_t)( stream_Tell( p_demux->s ) ) /
355                               (double)(uint64_t)( stream_Size( p_demux->s ) );
356                 /* The first few seconds are guaranteed to be very whacky,
357                  * don't bother trying ... Too bad */
358                 if( f_pos < 0.01 ||
359                     (p_sys->i_pts + p_sys->i_time_offset) < 8000000 )
360                     return VLC_EGENERIC;
361
362                 pi64 = (int64_t *)va_arg( args_save, int64_t * );
363                 *pi64 = (p_sys->i_pts + p_sys->i_time_offset) / f_pos;
364                 return VLC_SUCCESS;
365             }
366             va_end( args_save );
367             return i_ret;
368
369         case DEMUX_SET_TIME:
370             /* FIXME TODO: implement a high precision seek (with mp3 parsing)
371              * needed for multi-input */
372         default:
373             i_ret = demux_vaControlHelper( p_demux->s, p_sys->i_stream_offset, -1,
374                                             p_sys->i_bitrate_avg, 1, i_query,
375                                             args );
376             if( !i_ret && p_sys->i_bitrate_avg > 0 &&
377                 (i_query == DEMUX_SET_POSITION || i_query == DEMUX_SET_TIME) )
378             {
379                 int64_t i_time = INT64_C(8000000) * ( stream_Tell(p_demux->s) - p_sys->i_stream_offset ) /
380                     p_sys->i_bitrate_avg;
381
382                 /* Fix time_offset */
383                 if( i_time >= 0 )
384                     p_sys->i_time_offset = i_time - p_sys->i_pts;
385                 /* And reset buffered data */
386                 if( p_sys->p_packetized_data )
387                     block_ChainRelease( p_sys->p_packetized_data );
388                 p_sys->p_packetized_data = NULL;
389             }
390             return i_ret;
391     }
392 }
393
394 /*****************************************************************************
395  * Returned a link list of buffer of parsed data
396  *****************************************************************************/
397 static int Parse( demux_t *p_demux, block_t **pp_output )
398 {
399     demux_sys_t *p_sys = p_demux->p_sys;
400     block_t *p_block_in, *p_block_out;
401
402     *pp_output = NULL;
403
404     if( p_sys->codec.b_use_word )
405     {
406         /* Make sure we are word aligned */
407         int64_t i_pos = stream_Tell( p_demux->s );
408         if( i_pos % 2 )
409             stream_Read( p_demux->s, NULL, 1 );
410     }
411
412     if( ( p_block_in = stream_Block( p_demux->s, p_sys->i_packet_size ) ) == NULL )
413         return VLC_EGENERIC;
414
415     if( p_sys->codec.b_use_word && !p_sys->b_big_endian && p_block_in->i_buffer > 0 )
416     {
417         /* Convert to big endian */
418         swab( p_block_in->p_buffer, p_block_in->p_buffer, p_block_in->i_buffer );
419     }
420
421     p_block_in->i_pts = p_block_in->i_dts = p_sys->b_start || p_sys->b_initial_sync_failed ? VLC_TS_0 : VLC_TS_INVALID;
422     p_sys->b_initial_sync_failed = p_sys->b_start; /* Only try to resync once */
423
424     while( ( p_block_out = p_sys->p_packetizer->pf_packetize( p_sys->p_packetizer, &p_block_in ) ) )
425     {
426         p_sys->b_initial_sync_failed = false;
427         while( p_block_out )
428         {
429             if( !p_sys->p_es )
430             {
431                 p_sys->p_packetizer->fmt_out.b_packetized = true;
432                 p_sys->p_es = es_out_Add( p_demux->out,
433                                           &p_sys->p_packetizer->fmt_out);
434
435
436                 /* Try the xing header */
437                 if( p_sys->xing.i_bytes && p_sys->xing.i_frames &&
438                     p_sys->xing.i_frame_samples )
439                 {
440                     p_sys->i_bitrate_avg = p_sys->xing.i_bytes * INT64_C(8) *
441                         p_sys->p_packetizer->fmt_out.audio.i_rate /
442                         p_sys->xing.i_frames / p_sys->xing.i_frame_samples;
443
444                     if( p_sys->i_bitrate_avg > 0 )
445                         p_sys->b_estimate_bitrate = false;
446                 }
447                 /* Use the bitrate as initual value */
448                 if( p_sys->b_estimate_bitrate )
449                     p_sys->i_bitrate_avg = p_sys->p_packetizer->fmt_out.i_bitrate;
450             }
451
452             block_t *p_next = p_block_out->p_next;
453             p_block_out->p_next = NULL;
454
455             block_ChainLastAppend( &pp_output, p_block_out );
456
457             p_block_out = p_next;
458         }
459     }
460
461     if( p_sys->b_initial_sync_failed )
462         msg_Dbg( p_demux, "did not sync on first block" );
463     p_sys->b_start = false;
464     return VLC_SUCCESS;
465 }
466
467 /*****************************************************************************
468  * Wav header skipper
469  *****************************************************************************/
470 #define WAV_PROBE_SIZE (512*1024)
471 static int WavSkipHeader( demux_t *p_demux, int *pi_skip, const int pi_format[] )
472 {
473     const uint8_t *p_peek;
474     int         i_peek = 0;
475
476     /* */
477     *pi_skip = 0;
478
479     /* Check if we are dealing with a WAV file */
480     if( stream_Peek( p_demux->s, &p_peek, 12+8 ) != 12 + 8 )
481         return VLC_SUCCESS;
482
483     if( memcmp( p_peek, "RIFF", 4 ) || memcmp( &p_peek[8], "WAVE", 4 ) )
484         return VLC_SUCCESS;
485
486     /* Find the wave format header */
487     i_peek = 12 + 8;
488     while( memcmp( p_peek + i_peek - 8, "fmt ", 4 ) )
489     {
490         uint32_t i_len = GetDWLE( p_peek + i_peek - 4 );
491         if( i_len > WAV_PROBE_SIZE || i_peek + i_len > WAV_PROBE_SIZE )
492             return VLC_EGENERIC;
493
494         i_peek += i_len + 8;
495         if( stream_Peek( p_demux->s, &p_peek, i_peek ) != i_peek )
496             return VLC_EGENERIC;
497     }
498
499     /* Sanity check the wave format header */
500     uint32_t i_len = GetDWLE( p_peek + i_peek - 4 );
501     if( i_len > WAV_PROBE_SIZE )
502         return VLC_EGENERIC;
503
504     i_peek += i_len + 8;
505     if( stream_Peek( p_demux->s, &p_peek, i_peek ) != i_peek )
506         return VLC_EGENERIC;
507     const int i_format = GetWLE( p_peek + i_peek - i_len - 8 /* wFormatTag */ );
508     int i_format_idx;
509     for( i_format_idx = 0; pi_format[i_format_idx] != WAVE_FORMAT_UNKNOWN; i_format_idx++ )
510     {
511         if( i_format == pi_format[i_format_idx] )
512             break;
513     }
514     if( pi_format[i_format_idx] == WAVE_FORMAT_UNKNOWN )
515         return VLC_EGENERIC;
516
517     if( i_format == WAVE_FORMAT_PCM )
518     {
519         if( GetWLE( p_peek + i_peek - i_len - 6 /* nChannels */ ) != 2 )
520             return VLC_EGENERIC;
521         if( GetDWLE( p_peek + i_peek - i_len - 4 /* nSamplesPerSec */ ) !=
522             44100 )
523             return VLC_EGENERIC;
524     }
525
526     /* Skip the wave header */
527     while( memcmp( p_peek + i_peek - 8, "data", 4 ) )
528     {
529         uint32_t i_len = GetDWLE( p_peek + i_peek - 4 );
530         if( i_len > WAV_PROBE_SIZE || i_peek + i_len > WAV_PROBE_SIZE )
531             return VLC_EGENERIC;
532
533         i_peek += i_len + 8;
534         if( stream_Peek( p_demux->s, &p_peek, i_peek ) != i_peek )
535             return VLC_EGENERIC;
536     }
537     *pi_skip = i_peek;
538     return VLC_SUCCESS;
539 }
540
541 static int GenericProbe( demux_t *p_demux, int64_t *pi_offset,
542                          const char * ppsz_name[],
543                          int (*pf_check)( const uint8_t *, int * ), int i_check_size,
544                          const int pi_wav_format[] )
545 {
546     bool   b_forced_demux;
547
548     int64_t i_offset;
549     const uint8_t *p_peek;
550     int i_skip;
551
552     b_forced_demux = false;
553     for( int i = 0; ppsz_name[i] != NULL; i++ )
554     {
555         b_forced_demux |= demux_IsForced( p_demux, ppsz_name[i] );
556     }
557
558     i_offset = stream_Tell( p_demux->s );
559
560     if( WavSkipHeader( p_demux, &i_skip, pi_wav_format ) )
561     {
562         if( !b_forced_demux )
563             return VLC_EGENERIC;
564     }
565     const bool b_wav = i_skip > 0;
566
567     /* peek the begining
568      * It is common that wav files have some sort of garbage at the begining
569      * We will accept probing 0.5s of data in this case.
570      */
571     const int i_probe = i_skip + i_check_size + 8000 + ( b_wav ? (44000/2*2*2) : 0);
572     const int i_peek = stream_Peek( p_demux->s, &p_peek, i_probe );
573     if( i_peek < i_skip + i_check_size )
574     {
575         msg_Err( p_demux, "cannot peek" );
576         return VLC_EGENERIC;
577     }
578     for( ;; )
579     {
580         if( i_skip + i_check_size > i_peek )
581         {
582             if( !b_forced_demux )
583                 return VLC_EGENERIC;
584             break;
585         }
586         int i_samples = 0;
587         int i_size = pf_check( &p_peek[i_skip], &i_samples );
588         if( i_size >= 0 )
589         {
590             if( i_size == 0 )
591                 break;
592
593             /* If we have the frame size, check the next frame for
594              * extra robustness
595              * The second test is because some .wav have paddings
596              */
597             bool b_ok = false;
598             for( int t = 0; t < 1 + !!b_wav; t++ )
599             {
600                 if( t == 1 )
601                     i_size = i_samples * 2 * 2;
602                 if( i_skip + i_check_size + i_size <= i_peek )
603                 {
604                     b_ok = pf_check( &p_peek[i_skip+i_size], NULL ) >= 0;
605                     if( b_ok )
606                         break;
607                 }
608             }
609             if( b_ok )
610                 break;
611         }
612         i_skip++;
613         if( !b_wav && !b_forced_demux )
614             return VLC_EGENERIC;
615     }
616
617     *pi_offset = i_offset + i_skip;
618     return VLC_SUCCESS;
619 }
620
621 /*****************************************************************************
622  * Mpeg I/II Audio
623  *****************************************************************************/
624 static int MpgaCheckSync( const uint8_t *p_peek )
625 {
626     uint32_t h = GetDWBE( p_peek );
627
628     if( ((( h >> 21 )&0x07FF) != 0x07FF )   /* header sync */
629         || (((h >> 17)&0x03) == 0 )         /* valid layer ?*/
630         || (((h >> 12)&0x0F) == 0x0F )
631         || (((h >> 12)&0x0F) == 0x00 )      /* valid bitrate ? */
632         || (((h >> 10) & 0x03) == 0x03 )    /* valide sampling freq ? */
633         || ((h & 0x03) == 0x02 ))           /* valid emphasis ? */
634     {
635         return false;
636     }
637     return true;
638 }
639
640 #define MPGA_VERSION( h )   ( 1 - (((h)>>19)&0x01) )
641 #define MPGA_MODE(h)        (((h)>> 6)&0x03)
642
643 static int MpgaGetFrameSamples( uint32_t h )
644 {
645     const int i_layer = 3 - (((h)>>17)&0x03);
646     switch( i_layer )
647     {
648     case 0:
649         return 384;
650     case 1:
651         return 1152;
652     case 2:
653         return MPGA_VERSION(h) ? 576 : 1152;
654     default:
655         return 0;
656     }
657 }
658
659 static int MpgaProbe( demux_t *p_demux, int64_t *pi_offset )
660 {
661     const int pi_wav[] = { WAVE_FORMAT_MPEG, WAVE_FORMAT_MPEGLAYER3, WAVE_FORMAT_UNKNOWN };
662     bool   b_forced;
663     bool   b_forced_demux;
664     int64_t i_offset;
665
666     const uint8_t *p_peek;
667     int i_skip;
668
669     b_forced = demux_IsPathExtension( p_demux, ".mp3" );
670     b_forced_demux = demux_IsForced( p_demux, "mp3" ) ||
671                      demux_IsForced( p_demux, "mpga" );
672
673     i_offset = stream_Tell( p_demux->s );
674
675     if( WavSkipHeader( p_demux, &i_skip, pi_wav ) )
676     {
677         if( !b_forced_demux )
678             return VLC_EGENERIC;
679
680         return VLC_EGENERIC;
681     }
682
683     if( stream_Peek( p_demux->s, &p_peek, i_skip + 4 ) < i_skip + 4 )
684         return VLC_EGENERIC;
685
686     if( !MpgaCheckSync( &p_peek[i_skip] ) )
687     {
688         bool b_ok = false;
689         int i_peek;
690
691         if( !b_forced_demux && !b_forced )
692             return VLC_EGENERIC;
693
694         i_peek = stream_Peek( p_demux->s, &p_peek, i_skip + 8096 );
695         while( i_skip + 4 < i_peek )
696         {
697             if( MpgaCheckSync( &p_peek[i_skip] ) )
698             {
699                 b_ok = true;
700                 break;
701             }
702             i_skip++;
703         }
704         if( !b_ok && !b_forced_demux )
705             return VLC_EGENERIC;
706     }
707     *pi_offset = i_offset + i_skip;
708     return VLC_SUCCESS;
709 }
710
711 static void MpgaXingSkip( const uint8_t **pp_xing, int *pi_xing, int i_count )
712 {
713     if(i_count > *pi_xing )
714         i_count = *pi_xing;
715
716     (*pp_xing) += i_count;
717     (*pi_xing) -= i_count;
718 }
719
720 static uint32_t MpgaXingGetDWBE( const uint8_t **pp_xing, int *pi_xing, uint32_t i_default )
721 {
722     if( *pi_xing < 4 )
723         return i_default;
724
725     uint32_t v = GetDWBE( *pp_xing );
726
727     MpgaXingSkip( pp_xing, pi_xing, 4 );
728
729     return v;
730 }
731
732 static int MpgaInit( demux_t *p_demux )
733 {
734     demux_sys_t *p_sys = p_demux->p_sys;
735
736     const uint8_t *p_peek;
737     int i_peek;
738
739     /* */
740     p_sys->i_packet_size = 1024;
741
742     /* Load a potential xing header */
743     i_peek = stream_Peek( p_demux->s, &p_peek, 4 + 1024 );
744     if( i_peek < 4 + 21 )
745         return VLC_SUCCESS;
746
747     const uint32_t header = GetDWBE( p_peek );
748     if( !MpgaCheckSync( p_peek ) )
749         return VLC_SUCCESS;
750
751     /* Xing header */
752     const uint8_t *p_xing = p_peek;
753     int i_xing = i_peek;
754     int i_skip;
755
756     if( MPGA_VERSION( header ) == 0 )
757         i_skip = MPGA_MODE( header ) != 3 ? 36 : 21;
758     else
759         i_skip = MPGA_MODE( header ) != 3 ? 21 : 13;
760
761     if( i_skip + 8 >= i_xing || memcmp( &p_xing[i_skip], "Xing", 4 ) )
762         return VLC_SUCCESS;
763
764     const uint32_t i_flags = GetDWBE( &p_xing[i_skip+4] );
765
766     MpgaXingSkip( &p_xing, &i_xing, i_skip + 8 );
767
768     if( i_flags&0x01 )
769         p_sys->xing.i_frames = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
770     if( i_flags&0x02 )
771         p_sys->xing.i_bytes = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
772     if( i_flags&0x04 ) /* TODO Support XING TOC to improve seeking accuracy */
773         MpgaXingSkip( &p_xing, &i_xing, 100 );
774     if( i_flags&0x08 )
775     {
776         /* FIXME: doesn't return the right bitrage average, at least
777            with some MP3's */
778         p_sys->xing.i_bitrate_avg = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
779         msg_Dbg( p_demux, "xing vbr value present (%d)",
780                  p_sys->xing.i_bitrate_avg );
781     }
782
783     if( p_sys->xing.i_frames > 0 && p_sys->xing.i_bytes > 0 )
784     {
785         p_sys->xing.i_frame_samples = MpgaGetFrameSamples( header );
786         msg_Dbg( p_demux, "xing frames&bytes value present "
787                  "(%d bytes, %d frames, %d samples/frame)",
788                  p_sys->xing.i_bytes, p_sys->xing.i_frames,
789                  p_sys->xing.i_frame_samples );
790     }
791     return VLC_SUCCESS;
792 }
793
794 /*****************************************************************************
795  * AAC
796  *****************************************************************************/
797 static int AacProbe( demux_t *p_demux, int64_t *pi_offset )
798 {
799     bool   b_forced;
800     bool   b_forced_demux;
801
802     int64_t i_offset;
803     const uint8_t *p_peek;
804
805     b_forced = demux_IsPathExtension( p_demux, ".aac" ) ||
806                demux_IsPathExtension( p_demux, ".aacp" );
807     b_forced_demux = demux_IsForced( p_demux, "m4a" ) ||
808                      demux_IsForced( p_demux, "aac" ) ||
809                      demux_IsForced( p_demux, "mp4a" );
810
811     if( !b_forced_demux && !b_forced )
812         return VLC_EGENERIC;
813
814     i_offset = stream_Tell( p_demux->s );
815
816     /* peek the begining (10 is for adts header) */
817     if( stream_Peek( p_demux->s, &p_peek, 10 ) < 10 )
818     {
819         msg_Err( p_demux, "cannot peek" );
820         return VLC_EGENERIC;
821     }
822     if( !strncmp( (char *)p_peek, "ADIF", 4 ) )
823     {
824         msg_Err( p_demux, "ADIF file. Not yet supported. (Please report)" );
825         return VLC_EGENERIC;
826     }
827
828     *pi_offset = i_offset;
829     return VLC_SUCCESS;
830 }
831 static int AacInit( demux_t *p_demux )
832 {
833     demux_sys_t *p_sys = p_demux->p_sys;
834
835     p_sys->i_packet_size = 4096;
836
837     return VLC_SUCCESS;
838 }
839
840
841 /*****************************************************************************
842  * A52
843  *****************************************************************************/
844 static int A52CheckSync( const uint8_t *p_peek, bool *p_big_endian, int *pi_samples, bool b_eac3 )
845 {
846     vlc_a52_header_t header;
847     uint8_t p_tmp[VLC_A52_HEADER_SIZE];
848
849     *p_big_endian =  p_peek[0] == 0x0b && p_peek[1] == 0x77;
850     if( !*p_big_endian )
851     {
852         swab( p_peek, p_tmp, VLC_A52_HEADER_SIZE );
853         p_peek = p_tmp;
854     }
855
856     if( vlc_a52_header_Parse( &header, p_peek, VLC_A52_HEADER_SIZE ) )
857         return VLC_EGENERIC;
858
859     if( !header.b_eac3 != !b_eac3 )
860         return VLC_EGENERIC;
861     if( pi_samples )
862         *pi_samples = header.i_samples;
863     return header.i_size;
864 }
865 static int EA52CheckSyncProbe( const uint8_t *p_peek, int *pi_samples )
866 {
867     bool b_dummy;
868     return A52CheckSync( p_peek, &b_dummy, pi_samples, true );
869 }
870
871 static int EA52Probe( demux_t *p_demux, int64_t *pi_offset )
872 {
873     const char *ppsz_name[] = { "eac3", NULL };
874     const int pi_wav[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_A52, WAVE_FORMAT_UNKNOWN };
875
876     return GenericProbe( p_demux, pi_offset, ppsz_name, EA52CheckSyncProbe, VLC_A52_HEADER_SIZE, pi_wav );
877 }
878
879 static int A52CheckSyncProbe( const uint8_t *p_peek, int *pi_samples )
880 {
881     bool b_dummy;
882     return A52CheckSync( p_peek, &b_dummy, pi_samples, false );
883 }
884
885 static int A52Probe( demux_t *p_demux, int64_t *pi_offset )
886 {
887     const char *ppsz_name[] = { "a52", "ac3", NULL };
888     const int pi_wav[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_A52, WAVE_FORMAT_UNKNOWN };
889
890     return GenericProbe( p_demux, pi_offset, ppsz_name, A52CheckSyncProbe, VLC_A52_HEADER_SIZE, pi_wav );
891 }
892
893 static int A52Init( demux_t *p_demux )
894 {
895     demux_sys_t *p_sys = p_demux->p_sys;
896
897     p_sys->b_big_endian = false;
898     p_sys->i_packet_size = 1024;
899
900     const uint8_t *p_peek;
901
902     /* peek the begining */
903     if( stream_Peek( p_demux->s, &p_peek, VLC_A52_HEADER_SIZE ) >= VLC_A52_HEADER_SIZE )
904     {
905         A52CheckSync( p_peek, &p_sys->b_big_endian, NULL, true );
906     }
907     return VLC_SUCCESS;
908 }
909
910 /*****************************************************************************
911  * DTS
912  *****************************************************************************/
913 static int DtsCheckSync( const uint8_t *p_peek, int *pi_samples )
914 {
915     /* TODO return frame size for robustness */
916
917     /* 14 bits, little endian version of the bitstream */
918     if( p_peek[0] == 0xff && p_peek[1] == 0x1f &&
919         p_peek[2] == 0x00 && p_peek[3] == 0xe8 &&
920         (p_peek[4] & 0xf0) == 0xf0 && p_peek[5] == 0x07 )
921     {
922         return 0;
923     }
924     /* 14 bits, big endian version of the bitstream */
925     else if( p_peek[0] == 0x1f && p_peek[1] == 0xff &&
926              p_peek[2] == 0xe8 && p_peek[3] == 0x00 &&
927              p_peek[4] == 0x07 && (p_peek[5] & 0xf0) == 0xf0)
928     {
929         return 0;
930     }
931     /* 16 bits, big endian version of the bitstream */
932     else if( p_peek[0] == 0x7f && p_peek[1] == 0xfe &&
933              p_peek[2] == 0x80 && p_peek[3] == 0x01 )
934     {
935         return 0;
936     }
937     /* 16 bits, little endian version of the bitstream */
938     else if( p_peek[0] == 0xfe && p_peek[1] == 0x7f &&
939              p_peek[2] == 0x01 && p_peek[3] == 0x80 )
940     {
941         return 0;
942     }
943
944     VLC_UNUSED(pi_samples);
945     return VLC_EGENERIC;
946 }
947
948 static int DtsProbe( demux_t *p_demux, int64_t *pi_offset )
949 {
950     const char *ppsz_name[] = { "dts", NULL };
951     const int pi_wav[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_DTS, WAVE_FORMAT_UNKNOWN };
952
953     return GenericProbe( p_demux, pi_offset, ppsz_name, DtsCheckSync, 11, pi_wav );
954 }
955 static int DtsInit( demux_t *p_demux )
956 {
957     demux_sys_t *p_sys = p_demux->p_sys;
958
959     p_sys->i_packet_size = 16384;
960
961     return VLC_SUCCESS;
962 }
963
964 /*****************************************************************************
965  * MLP
966  *****************************************************************************/
967 static int MlpCheckSync( const uint8_t *p_peek, int *pi_samples )
968 {
969     if( p_peek[4+0] != 0xf8 || p_peek[4+1] != 0x72 || p_peek[4+2] != 0x6f )
970         return -1;
971
972     if( p_peek[4+3] != 0xba && p_peek[4+3] != 0xbb )
973         return -1;
974
975     /* TODO checksum and real size for robustness */
976     VLC_UNUSED(pi_samples);
977     return 0;
978 }
979 static int MlpProbe( demux_t *p_demux, int64_t *pi_offset )
980 {
981     const char *ppsz_name[] = { "mlp", "thd", NULL };
982     const int pi_wav[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_UNKNOWN };
983
984     return GenericProbe( p_demux, pi_offset, ppsz_name, MlpCheckSync, 4+28+16*4, pi_wav );
985 }
986 static int MlpInit( demux_t *p_demux )
987
988 {
989     demux_sys_t *p_sys = p_demux->p_sys;
990
991     p_sys->i_packet_size = 4096;
992
993     return VLC_SUCCESS;
994 }
995
996 /*****************************************************************************
997  * Video
998  *****************************************************************************/
999 static int VideoInit( demux_t *p_demux )
1000 {
1001     demux_sys_t *p_sys = p_demux->p_sys;
1002
1003     p_sys->i_packet_size = 4096;
1004
1005     return VLC_SUCCESS;
1006 }