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