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