a8491f3f0d78fc17a855bd840908d4898391f5de
[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  *
6  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
7  *          Gildas Bazin <gbazin@videolan.org>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31
32 #include <vlc_common.h>
33 #include <vlc_plugin.h>
34 #include <vlc_demux.h>
35 #include <vlc_codec.h>
36 #include <vlc_codecs.h>
37 #include <vlc_input.h>
38
39 #include "../../packetizer/a52.h"
40 #include "../../packetizer/dts_header.h"
41 #include "../../meta_engine/ID3Tag.h"
42 #include "../../meta_engine/ID3Text.h"
43 #include "../../meta_engine/ID3Meta.h"
44
45 /*****************************************************************************
46  * Module descriptor
47  *****************************************************************************/
48 static int  OpenAudio( vlc_object_t * );
49 static int  OpenVideo( vlc_object_t * );
50 static void Close    ( vlc_object_t * );
51
52 #define FPS_TEXT N_("Frames per Second")
53 #define FPS_LONGTEXT N_("This is the frame rate used as a fallback when " \
54     "playing MPEG video elementary streams.")
55
56 vlc_module_begin ()
57     set_category( CAT_INPUT )
58     set_subcategory( SUBCAT_INPUT_DEMUX )
59     set_description( N_("MPEG-I/II/4 / A52 / DTS / MLP audio" ) )
60     set_shortname( N_("Audio ES") )
61     set_capability( "demux", 155 )
62     set_callbacks( OpenAudio, Close )
63
64     add_shortcut( "mpga", "mp3",
65                   "m4a", "mp4a", "aac",
66                   "ac3", "a52",
67                   "eac3",
68                   "dts",
69                   "mlp", "thd" )
70
71     add_submodule()
72     set_description( N_("MPEG-4 video" ) )
73     set_capability( "demux", 5 )
74     set_callbacks( OpenVideo, Close )
75     add_float( "es-fps", 25, FPS_TEXT, FPS_LONGTEXT, false )
76
77     add_shortcut( "m4v" )
78     add_shortcut( "mp4v" )
79 vlc_module_end ()
80
81 /*****************************************************************************
82  * Local prototypes
83  *****************************************************************************/
84 static int Demux  ( demux_t * );
85 static int Control( demux_t *, int, va_list );
86
87 #define WAV_PROBE_SIZE (512*1024)
88 #define BASE_PROBE_SIZE (8000)
89 #define WAV_EXTRA_PROBE_SIZE (44000/2*2*2)
90
91 typedef struct
92 {
93     vlc_fourcc_t i_codec;
94     bool       b_use_word;
95     const char *psz_name;
96     int  (*pf_probe)( demux_t *p_demux, uint64_t *pi_offset );
97     int  (*pf_init)( demux_t *p_demux );
98 } codec_t;
99
100 typedef struct
101 {
102     char  psz_version[10];
103     int   i_lowpass;
104 } lame_extra_t;
105
106 typedef struct
107 {
108     vlc_tick_t i_time;
109     uint64_t i_pos;
110     bs_t br;
111 } sync_table_ctx_t;
112
113 typedef struct
114 {
115     uint16_t i_frames_btw_refs;
116     uint32_t i_bytes_btw_refs;
117     uint32_t i_ms_btw_refs;
118     uint8_t i_bits_per_bytes_dev;
119     uint8_t i_bits_per_ms_dev;
120     uint8_t *p_bits;
121     size_t i_bits;
122     sync_table_ctx_t current;
123 } sync_table_t;
124
125 typedef struct
126 {
127     uint32_t i_offset;
128     seekpoint_t *p_seekpoint;
129 } chap_entry_t;
130
131 typedef struct
132 {
133     codec_t codec;
134     vlc_fourcc_t i_original;
135
136     es_out_id_t *p_es;
137
138     bool  b_start;
139     decoder_t   *p_packetizer;
140     block_t     *p_packetized_data;
141
142     vlc_tick_t  i_pts;
143     vlc_tick_t  i_time_offset;
144     int64_t     i_bytes;
145
146     bool        b_big_endian;
147     bool        b_estimate_bitrate;
148     int         i_bitrate_avg;  /* extracted from Xing header */
149
150     bool b_initial_sync_failed;
151
152     int i_packet_size;
153
154     uint64_t i_stream_offset;
155     unsigned i_demux_flags;
156
157     float   f_fps;
158
159     /* Mpga specific */
160     struct
161     {
162         int i_frames;
163         int i_bytes;
164         int i_bitrate_avg;
165         int i_frame_samples;
166         lame_extra_t lame;
167         bool b_lame;
168     } xing;
169
170     float rgf_replay_gain[AUDIO_REPLAY_GAIN_MAX];
171     float rgf_replay_peak[AUDIO_REPLAY_GAIN_MAX];
172
173     sync_table_t mllt;
174     struct
175     {
176         size_t i_count;
177         size_t i_current;
178         chap_entry_t *p_entry;
179     } chapters;
180 } demux_sys_t;
181
182 static int MpgaProbe( demux_t *p_demux, uint64_t *pi_offset );
183 static int MpgaInit( demux_t *p_demux );
184
185 static int AacProbe( demux_t *p_demux, uint64_t *pi_offset );
186 static int AacInit( demux_t *p_demux );
187
188 static int EA52Probe( demux_t *p_demux, uint64_t *pi_offset );
189 static int A52Probe( demux_t *p_demux, uint64_t *pi_offset );
190 static int A52Init( demux_t *p_demux );
191
192 static int DtsProbe( demux_t *p_demux, uint64_t *pi_offset );
193 static int DtsInit( demux_t *p_demux );
194
195 static int MlpProbe( demux_t *p_demux, uint64_t *pi_offset );
196 static int ThdProbe( demux_t *p_demux, uint64_t *pi_offset );
197 static int MlpInit( demux_t *p_demux );
198
199 static bool Parse( demux_t *p_demux, block_t **pp_output );
200 static uint64_t SeekByMlltTable( demux_t *p_demux, vlc_tick_t *pi_time );
201
202 static const codec_t p_codecs[] = {
203     { VLC_CODEC_MP4A, false, "mp4 audio",  AacProbe,  AacInit },
204     { VLC_CODEC_MPGA, false, "mpeg audio", MpgaProbe, MpgaInit },
205     { VLC_CODEC_A52, true,  "a52 audio",  A52Probe,  A52Init },
206     { VLC_CODEC_EAC3, true,  "eac3 audio", EA52Probe, A52Init },
207     { VLC_CODEC_DTS, false, "dts audio",  DtsProbe,  DtsInit },
208     { VLC_CODEC_MLP, false, "mlp audio",  MlpProbe,  MlpInit },
209     { VLC_CODEC_TRUEHD, false, "TrueHD audio",  ThdProbe,  MlpInit },
210
211     { 0, false, NULL, NULL, NULL }
212 };
213
214 static int VideoInit( demux_t *p_demux );
215
216 static const codec_t codec_m4v = {
217     VLC_CODEC_MP4V, false, "mp4 video", NULL,  VideoInit
218 };
219
220 /*****************************************************************************
221  * OpenCommon: initializes demux structures
222  *****************************************************************************/
223 static int OpenCommon( demux_t *p_demux,
224                        int i_cat, const codec_t *p_codec, uint64_t i_bs_offset )
225 {
226     demux_sys_t *p_sys;
227
228     es_format_t fmt;
229
230     DEMUX_INIT_COMMON(); p_sys = p_demux->p_sys;
231     memset( p_sys, 0, sizeof( demux_sys_t ) );
232     p_sys->codec = *p_codec;
233     p_sys->p_es = NULL;
234     p_sys->b_start = true;
235     p_sys->i_stream_offset = i_bs_offset;
236     p_sys->b_estimate_bitrate = true;
237     p_sys->i_bitrate_avg = 0;
238     p_sys->b_big_endian = false;
239     p_sys->f_fps = var_InheritFloat( p_demux, "es-fps" );
240     p_sys->p_packetized_data = NULL;
241     p_sys->chapters.i_current = 0;
242     TAB_INIT(p_sys->chapters.i_count, p_sys->chapters.p_entry);
243
244     if( vlc_stream_Seek( p_demux->s, p_sys->i_stream_offset ) )
245     {
246         free( p_sys );
247         return VLC_EGENERIC;
248     }
249
250     if( p_sys->codec.pf_init( p_demux ) )
251     {
252         free( p_sys );
253         return VLC_EGENERIC;
254     }
255
256     msg_Dbg( p_demux, "detected format %4.4s", (const char*)&p_sys->codec.i_codec );
257
258     /* Load the audio packetizer */
259     es_format_Init( &fmt, i_cat, p_sys->codec.i_codec );
260     fmt.i_original_fourcc = p_sys->i_original;
261     p_sys->p_packetizer = demux_PacketizerNew( p_demux, &fmt, p_sys->codec.psz_name );
262     if( !p_sys->p_packetizer )
263     {
264         free( p_sys );
265         return VLC_EGENERIC;
266     }
267
268     es_format_t *p_fmt = &p_sys->p_packetizer->fmt_out;
269     for( int i = 0; i < AUDIO_REPLAY_GAIN_MAX; i++ )
270     {
271         if ( p_sys->rgf_replay_gain[i] != 0.0 )
272         {
273             p_fmt->audio_replay_gain.pb_gain[i] = true;
274             p_fmt->audio_replay_gain.pf_gain[i] = p_sys->rgf_replay_gain[i];
275         }
276         if ( p_sys->rgf_replay_peak[i] != 0.0 )
277         {
278             p_fmt->audio_replay_gain.pb_peak[i] = true;
279             p_fmt->audio_replay_gain.pf_peak[i] = p_sys->rgf_replay_peak[i];
280         }
281     }
282
283     for( ;; )
284     {
285         if( Parse( p_demux, &p_sys->p_packetized_data ) )
286             break;
287         if( p_sys->p_packetized_data )
288             break;
289     }
290
291     return VLC_SUCCESS;
292 }
293 static int OpenAudio( vlc_object_t *p_this )
294 {
295     demux_t *p_demux = (demux_t*)p_this;
296     for( int i = 0; p_codecs[i].i_codec != 0; i++ )
297     {
298         uint64_t i_offset;
299         if( !p_codecs[i].pf_probe( p_demux, &i_offset ) )
300             return OpenCommon( p_demux, AUDIO_ES, &p_codecs[i], i_offset );
301     }
302     return VLC_EGENERIC;
303 }
304 static int OpenVideo( vlc_object_t *p_this )
305 {
306     demux_t *p_demux = (demux_t*)p_this;
307
308     /* Only m4v is supported for the moment */
309     bool b_m4v_ext    = demux_IsPathExtension( p_demux, ".m4v" );
310     bool b_re4_ext    = !b_m4v_ext && demux_IsPathExtension( p_demux, ".re4" );
311     bool b_m4v_forced = demux_IsForced( p_demux, "m4v" ) ||
312                         demux_IsForced( p_demux, "mp4v" );
313
314     if( !b_m4v_ext && !b_m4v_forced && !b_re4_ext )
315         return VLC_EGENERIC;
316
317     ssize_t i_off = b_re4_ext ? 220 : 0;
318     const uint8_t *p_peek;
319     if( vlc_stream_Peek( p_demux->s, &p_peek, i_off + 4 ) < i_off + 4 )
320         return VLC_EGENERIC;
321     if( p_peek[i_off + 0] != 0x00 || p_peek[i_off + 1] != 0x00 || p_peek[i_off + 2] != 0x01 )
322     {
323         if( !b_m4v_forced)
324             return VLC_EGENERIC;
325         msg_Warn( p_demux,
326                   "this doesn't look like an MPEG ES stream, continuing anyway" );
327     }
328     return OpenCommon( p_demux, VIDEO_ES, &codec_m4v, i_off );
329 }
330
331 static void IncreaseChapter( demux_t *p_demux, vlc_tick_t i_time )
332 {
333     demux_sys_t *p_sys = p_demux->p_sys;
334     while( p_sys->chapters.i_current + 1 < p_sys->chapters.i_count )
335     {
336         const chap_entry_t *p = &p_sys->chapters.p_entry[p_sys->chapters.i_current + 1];
337         if( (p->i_offset != UINT32_MAX && vlc_stream_Tell( p_demux->s ) < p->i_offset) ||
338             (i_time == VLC_TICK_INVALID || p->p_seekpoint->i_time_offset + VLC_TICK_0 > i_time) )
339             break;
340         ++p_sys->chapters.i_current;
341         p_sys->i_demux_flags |= INPUT_UPDATE_SEEKPOINT;
342     }
343 }
344
345 /*****************************************************************************
346  * Demux: reads and demuxes data packets
347  *****************************************************************************
348  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
349  *****************************************************************************/
350 static int Demux( demux_t *p_demux )
351 {
352     int ret = 1;
353     demux_sys_t *p_sys = p_demux->p_sys;
354
355     block_t *p_block_out = p_sys->p_packetized_data;
356     if( p_block_out )
357         p_sys->p_packetized_data = NULL;
358     else
359         ret = Parse( p_demux, &p_block_out ) ? 0 : 1;
360
361     /* Update chapter if any */
362     IncreaseChapter( p_demux,
363                      p_block_out ? p_sys->i_time_offset + p_block_out->i_dts
364                                  : VLC_TICK_INVALID );
365
366     while( p_block_out )
367     {
368         block_t *p_next = p_block_out->p_next;
369
370         /* Correct timestamp */
371         if( p_sys->p_packetizer->fmt_out.i_cat == VIDEO_ES )
372         {
373             if( p_block_out->i_pts == VLC_TICK_INVALID &&
374                 p_block_out->i_dts == VLC_TICK_INVALID )
375                 p_block_out->i_dts = VLC_TICK_0 + p_sys->i_pts + VLC_TICK_FROM_SEC(1) / p_sys->f_fps;
376             if( p_block_out->i_dts != VLC_TICK_INVALID )
377                 p_sys->i_pts = p_block_out->i_dts - VLC_TICK_0;
378         }
379         else
380         {
381             p_sys->i_pts = p_block_out->i_pts - VLC_TICK_0;
382         }
383
384         if( p_block_out->i_pts != VLC_TICK_INVALID )
385         {
386             p_block_out->i_pts += p_sys->i_time_offset;
387         }
388         if( p_block_out->i_dts != VLC_TICK_INVALID )
389         {
390             p_block_out->i_dts += p_sys->i_time_offset;
391             es_out_SetPCR( p_demux->out, p_block_out->i_dts );
392         }
393         /* Re-estimate bitrate */
394         if( p_sys->b_estimate_bitrate && p_sys->i_pts > VLC_TICK_FROM_MS(500) )
395             p_sys->i_bitrate_avg = 8 * CLOCK_FREQ * p_sys->i_bytes
396                                    / (p_sys->i_pts - 1);
397         p_sys->i_bytes += p_block_out->i_buffer;
398
399
400         p_block_out->p_next = NULL;
401         es_out_Send( p_demux->out, p_sys->p_es, p_block_out );
402
403         p_block_out = p_next;
404     }
405     return ret;
406 }
407
408 /*****************************************************************************
409  * Close: frees unused data
410  *****************************************************************************/
411 static void Close( vlc_object_t * p_this )
412 {
413     demux_t     *p_demux = (demux_t*)p_this;
414     demux_sys_t *p_sys = p_demux->p_sys;
415
416     if( p_sys->p_packetized_data )
417         block_ChainRelease( p_sys->p_packetized_data );
418     for( size_t i=0; i< p_sys->chapters.i_count; i++ )
419         vlc_seekpoint_Delete( p_sys->chapters.p_entry[i].p_seekpoint );
420     TAB_CLEAN( p_sys->chapters.i_count, p_sys->chapters.p_entry );
421     if( p_sys->mllt.p_bits )
422         free( p_sys->mllt.p_bits );
423     demux_PacketizerDestroy( p_sys->p_packetizer );
424     free( p_sys );
425 }
426
427 /*****************************************************************************
428  * Time seek:
429  *****************************************************************************/
430 static int MovetoTimePos( demux_t *p_demux, vlc_tick_t i_time, uint64_t i_pos )
431 {
432     demux_sys_t *p_sys  = p_demux->p_sys;
433     int i_ret = vlc_stream_Seek( p_demux->s, p_sys->i_stream_offset + i_pos );
434     if( i_ret != VLC_SUCCESS )
435         return i_ret;
436     p_sys->i_time_offset = i_time - p_sys->i_pts;
437     /* And reset buffered data */
438     if( p_sys->p_packetized_data )
439         block_ChainRelease( p_sys->p_packetized_data );
440     p_sys->p_packetized_data = NULL;
441     p_sys->chapters.i_current = 0;
442     p_sys->i_demux_flags |= INPUT_UPDATE_SEEKPOINT;
443     return VLC_SUCCESS;
444 }
445
446 /*****************************************************************************
447  * Control:
448  *****************************************************************************/
449 static int Control( demux_t *p_demux, int i_query, va_list args )
450 {
451     demux_sys_t *p_sys  = p_demux->p_sys;
452     bool *pb_bool;
453
454     switch( i_query )
455     {
456         case DEMUX_HAS_UNSUPPORTED_META:
457             pb_bool = va_arg( args, bool * );
458             *pb_bool = true;
459             return VLC_SUCCESS;
460
461         case DEMUX_GET_TIME:
462             *va_arg( args, vlc_tick_t * ) = p_sys->i_pts + p_sys->i_time_offset;
463             return VLC_SUCCESS;
464
465         case DEMUX_GET_LENGTH:
466         {
467             va_list ap;
468             int i_ret;
469
470             va_copy ( ap, args );
471             i_ret = demux_vaControlHelper( p_demux->s, p_sys->i_stream_offset,
472                                     -1, p_sys->i_bitrate_avg, 1, i_query, ap );
473             va_end( ap );
474
475             /* No bitrate, we can't have it precisely, but we can compute
476              * a raw approximation with time/position */
477             if( i_ret && !p_sys->i_bitrate_avg )
478             {
479                 float f_pos = (double)(uint64_t)( vlc_stream_Tell( p_demux->s ) ) /
480                               (double)(uint64_t)( stream_Size( p_demux->s ) );
481                 /* The first few seconds are guaranteed to be very whacky,
482                  * don't bother trying ... Too bad */
483                 if( f_pos < 0.01f ||
484                     (p_sys->i_pts + p_sys->i_time_offset) < VLC_TICK_FROM_SEC(8) )
485                 {
486                     return VLC_EGENERIC;
487                 }
488
489                 *va_arg( args, vlc_tick_t * ) =
490                     (p_sys->i_pts + p_sys->i_time_offset) / f_pos;
491                 return VLC_SUCCESS;
492             }
493             return i_ret;
494         }
495
496         case DEMUX_SET_TIME:
497             if( p_sys->mllt.p_bits )
498             {
499                 vlc_tick_t i_time = va_arg(args, vlc_tick_t);
500                 uint64_t i_pos = SeekByMlltTable( p_demux, &i_time );
501                 return MovetoTimePos( p_demux, i_time, i_pos );
502             }
503             /* FIXME TODO: implement a high precision seek (with mp3 parsing)
504              * needed for multi-input */
505             break;
506
507         case DEMUX_GET_TITLE_INFO:
508         {
509             if( p_sys->chapters.i_count == 0 )
510                 return VLC_EGENERIC;
511             input_title_t **pp_title = malloc( sizeof(*pp_title) );
512             if( !pp_title )
513                 return VLC_EGENERIC;
514             *pp_title = vlc_input_title_New();
515             if( !*pp_title )
516             {
517                 free( pp_title );
518                 return VLC_EGENERIC;
519             }
520             (*pp_title)->seekpoint = vlc_alloc( p_sys->chapters.i_count, sizeof(seekpoint_t) );
521             if( !(*pp_title)->seekpoint )
522             {
523                 free( *pp_title );
524                 free( pp_title );
525                 return VLC_EGENERIC;
526             }
527             for( size_t i=0; i<p_sys->chapters.i_count; i++ )
528             {
529                 seekpoint_t *s = vlc_seekpoint_Duplicate( p_sys->chapters.p_entry[i].p_seekpoint );
530                 if( s )
531                     (*pp_title)->seekpoint[(*pp_title)->i_seekpoint++] = s;
532             }
533             *(va_arg( args, input_title_t *** )) = pp_title;
534             *(va_arg( args, int* )) = 1;
535             *(va_arg( args, int* )) = 0;
536             *(va_arg( args, int* )) = 0;
537             return VLC_SUCCESS;
538         }
539         break;
540
541         case DEMUX_GET_TITLE:
542             if( p_sys->chapters.i_count == 0 )
543                 return VLC_EGENERIC;
544             *(va_arg( args, int* )) = 0;
545             return VLC_SUCCESS;
546
547         case DEMUX_GET_SEEKPOINT:
548             if( p_sys->chapters.i_count == 0 )
549                 return VLC_EGENERIC;
550             *(va_arg( args, int* )) = p_sys->chapters.i_current;
551             return VLC_SUCCESS;
552
553         case DEMUX_SET_TITLE:
554             return va_arg( args, int) == 0 ? VLC_SUCCESS : VLC_EGENERIC;
555
556         case DEMUX_SET_SEEKPOINT:
557         {
558             int i = va_arg( args, int );
559             if( (size_t)i>=p_sys->chapters.i_count )
560                 return VLC_EGENERIC;
561             const chap_entry_t *p = &p_sys->chapters.p_entry[i];
562             if( p_sys->chapters.p_entry[i].i_offset == UINT32_MAX )
563                 return demux_Control( p_demux, DEMUX_SET_TIME, p->p_seekpoint->i_time_offset );
564             int i_ret= MovetoTimePos( p_demux, p->p_seekpoint->i_time_offset, p->i_offset );
565             if( i_ret == VLC_SUCCESS )
566                 p_sys->chapters.i_current = i;
567             return i_ret;
568         }
569
570         case DEMUX_TEST_AND_CLEAR_FLAGS:
571         {
572             unsigned *restrict flags = va_arg( args, unsigned * );
573             *flags &= p_sys->i_demux_flags;
574             p_sys->i_demux_flags &= ~*flags;
575             return VLC_SUCCESS;
576         }
577     }
578
579     int ret = demux_vaControlHelper( p_demux->s, p_sys->i_stream_offset, -1,
580                                        p_sys->i_bitrate_avg, 1, i_query, args );
581     if( ret != VLC_SUCCESS )
582         return ret;
583
584     if( i_query == DEMUX_SET_POSITION || i_query == DEMUX_SET_TIME )
585     {
586         if( p_sys->i_bitrate_avg > 0 )
587         {
588             vlc_tick_t i_time = vlc_tick_from_samples(
589                 ( vlc_stream_Tell(p_demux->s) - p_sys->i_stream_offset ) * 8
590                 , p_sys->i_bitrate_avg );
591
592             /* Fix time_offset */
593             if( i_time >= 0 )
594                 p_sys->i_time_offset = i_time - p_sys->i_pts;
595             /* And reset buffered data */
596             if( p_sys->p_packetized_data )
597                 block_ChainRelease( p_sys->p_packetized_data );
598             p_sys->p_packetized_data = NULL;
599         }
600
601         /* Reset chapter if any */
602         p_sys->chapters.i_current = 0;
603         p_sys->i_demux_flags |= INPUT_UPDATE_SEEKPOINT;
604     }
605
606     return VLC_SUCCESS;
607 }
608
609 /*****************************************************************************
610  * Makes a link list of buffer of parsed data
611  * Returns true if EOF
612  *****************************************************************************/
613 static bool Parse( demux_t *p_demux, block_t **pp_output )
614 {
615     demux_sys_t *p_sys = p_demux->p_sys;
616     block_t *p_block_in, *p_block_out;
617
618     *pp_output = NULL;
619
620     if( p_sys->codec.b_use_word )
621     {
622         /* Make sure we are word aligned */
623         int64_t i_pos = vlc_stream_Tell( p_demux->s );
624         if( (i_pos & 1) && vlc_stream_Read( p_demux->s, NULL, 1 ) != 1 )
625             return true;
626     }
627
628     p_block_in = vlc_stream_Block( p_demux->s, p_sys->i_packet_size );
629     bool b_eof = p_block_in == NULL;
630
631     if( p_block_in )
632     {
633         if( p_sys->codec.b_use_word && !p_sys->b_big_endian && p_block_in->i_buffer > 0 )
634         {
635             /* Convert to big endian */
636             block_t *old = p_block_in;
637             p_block_in = block_Alloc( p_block_in->i_buffer );
638             if( p_block_in )
639             {
640                 block_CopyProperties( p_block_in, old );
641                 swab( old->p_buffer, p_block_in->p_buffer, old->i_buffer );
642             }
643             block_Release( old );
644         }
645
646         if( p_block_in )
647         {
648             p_block_in->i_pts =
649             p_block_in->i_dts = (p_sys->b_start || p_sys->b_initial_sync_failed) ?
650                                  VLC_TICK_0 : VLC_TICK_INVALID;
651         }
652     }
653     p_sys->b_initial_sync_failed = p_sys->b_start; /* Only try to resync once */
654
655     while( ( p_block_out = p_sys->p_packetizer->pf_packetize( p_sys->p_packetizer, p_block_in ? &p_block_in : NULL ) ) )
656     {
657         p_sys->b_initial_sync_failed = false;
658         while( p_block_out )
659         {
660             if( !p_sys->p_es )
661             {
662                 p_sys->p_packetizer->fmt_out.b_packetized = true;
663                 p_sys->p_packetizer->fmt_out.i_id = 0;
664                 p_sys->p_es = es_out_Add( p_demux->out,
665                                           &p_sys->p_packetizer->fmt_out);
666
667
668                 /* Try the xing header */
669                 if( p_sys->xing.i_bytes && p_sys->xing.i_frames &&
670                     p_sys->xing.i_frame_samples )
671                 {
672                     p_sys->i_bitrate_avg = p_sys->xing.i_bytes * INT64_C(8) *
673                         p_sys->p_packetizer->fmt_out.audio.i_rate /
674                         p_sys->xing.i_frames / p_sys->xing.i_frame_samples;
675
676                     if( p_sys->i_bitrate_avg > 0 )
677                         p_sys->b_estimate_bitrate = false;
678                 }
679                 /* Use the bitrate as initual value */
680                 if( p_sys->b_estimate_bitrate )
681                     p_sys->i_bitrate_avg = p_sys->p_packetizer->fmt_out.i_bitrate;
682             }
683
684             block_t *p_next = p_block_out->p_next;
685             p_block_out->p_next = NULL;
686
687             block_ChainLastAppend( &pp_output, p_block_out );
688
689             p_block_out = p_next;
690         }
691     }
692
693     if( p_sys->b_initial_sync_failed )
694         msg_Dbg( p_demux, "did not sync on first block" );
695     p_sys->b_start = false;
696
697     return b_eof;
698 }
699
700 /* Check to apply to WAVE fmt header */
701 static int GenericFormatCheck( int i_format, const uint8_t *p_head )
702 {
703     if ( i_format == WAVE_FORMAT_PCM )
704     {
705         if( GetWLE( p_head /* nChannels */ ) != 2 )
706             return VLC_EGENERIC;
707         if( GetDWLE( p_head + 2 /* nSamplesPerSec */ ) != 44100 )
708             return VLC_EGENERIC;
709     }
710     return VLC_SUCCESS;
711 }
712
713 /*****************************************************************************
714  * Wav header skipper
715  *****************************************************************************/
716 static int WavSkipHeader( demux_t *p_demux, uint64_t *pi_skip,
717                           const uint16_t rgi_twocc[],
718                           int (*pf_format_check)( int, const uint8_t * ) )
719 {
720     const uint8_t *p_peek;
721     size_t i_peek = 0;
722     uint32_t i_len;
723
724     /* */
725     *pi_skip = 0;
726
727     /* Check if we are dealing with a WAV file */
728     if( vlc_stream_Peek( p_demux->s, &p_peek, 12+8 ) != 12 + 8 )
729         return VLC_SUCCESS;
730
731     if( memcmp( p_peek, "RIFF", 4 ) || memcmp( &p_peek[8], "WAVE", 4 ) )
732         return VLC_SUCCESS;
733
734     /* Find the wave format header */
735     i_peek = 12 + 8;
736     while( memcmp( p_peek + i_peek - 8, "fmt ", 4 ) )
737     {
738         i_len = GetDWLE( p_peek + i_peek - 4 );
739         if( i_len > WAV_PROBE_SIZE || i_peek + i_len > WAV_PROBE_SIZE )
740             return VLC_EGENERIC;
741
742         i_peek += i_len + 8;
743         if( vlc_stream_Peek( p_demux->s, &p_peek, i_peek ) != (ssize_t) i_peek )
744             return VLC_EGENERIC;
745     }
746
747     /* Sanity check the wave format header */
748     i_len = GetDWLE( p_peek + i_peek - 4 );
749     if( i_len > WAV_PROBE_SIZE )
750         return VLC_EGENERIC;
751
752     i_peek += i_len + 8;
753     if( vlc_stream_Peek( p_demux->s, &p_peek, i_peek ) != (ssize_t) i_peek )
754         return VLC_EGENERIC;
755     const uint16_t i_twocc = GetWLE( p_peek + i_peek - i_len - 8 /* wFormatTag */ );
756     int i_format_idx;
757     for( i_format_idx = 0; rgi_twocc[i_format_idx] != WAVE_FORMAT_UNKNOWN; i_format_idx++ )
758     {
759         if( i_twocc == rgi_twocc[i_format_idx] )
760             break;
761     }
762     if( rgi_twocc[i_format_idx] == WAVE_FORMAT_UNKNOWN )
763         return VLC_EGENERIC;
764
765     if( pf_format_check &&
766         pf_format_check( i_twocc, p_peek + i_peek - i_len - 6 ) != VLC_SUCCESS )
767             return VLC_EGENERIC;
768
769     /* Skip the wave header */
770     while( memcmp( p_peek + i_peek - 8, "data", 4 ) )
771     {
772         i_len = GetDWLE( p_peek + i_peek - 4 );
773         if( i_len > WAV_PROBE_SIZE || i_peek + i_len > WAV_PROBE_SIZE )
774             return VLC_EGENERIC;
775
776         i_peek += i_len + 8;
777         if( vlc_stream_Peek( p_demux->s, &p_peek, i_peek ) != (ssize_t) i_peek )
778             return VLC_EGENERIC;
779     }
780     *pi_skip = i_peek;
781     return VLC_SUCCESS;
782 }
783
784 static int GenericProbe( demux_t *p_demux, uint64_t *pi_offset,
785                          const char * ppsz_name[],
786                          int (*pf_check)( const uint8_t *, unsigned * ),
787                          unsigned i_check_size,
788                          unsigned i_base_probing,
789                          unsigned i_wav_extra_probing,
790                          bool b_use_word,
791                          const uint16_t pi_twocc[],
792                          int (*pf_format_check)( int, const uint8_t * ) )
793 {
794     bool   b_forced_demux;
795
796     uint64_t i_offset;
797     const uint8_t *p_peek;
798     uint64_t i_skip;
799
800     b_forced_demux = false;
801     for( size_t i = 0; ppsz_name[i] != NULL; i++ )
802     {
803         b_forced_demux |= demux_IsForced( p_demux, ppsz_name[i] );
804     }
805
806     i_offset = vlc_stream_Tell( p_demux->s );
807
808     if( WavSkipHeader( p_demux, &i_skip, pi_twocc, pf_format_check ) )
809     {
810         if( !b_forced_demux )
811             return VLC_EGENERIC;
812     }
813     const bool b_wav = i_skip > 0;
814
815     /* peek the begining
816      * It is common that wav files have some sort of garbage at the begining
817      * We will accept probing 0.5s of data in this case.
818      */
819     const size_t i_probe = i_skip + i_check_size + i_base_probing + ( b_wav ? i_wav_extra_probing : 0);
820     const ssize_t i_peek = vlc_stream_Peek( p_demux->s, &p_peek, i_probe );
821
822     if( i_peek < 0 || (size_t)i_peek < i_skip + i_check_size )
823         return VLC_EGENERIC;
824
825     for( ;; )
826     {
827         /* i_peek > 0 so we can cast into size_t. */
828         if( i_skip + i_check_size > (size_t)i_peek )
829         {
830             if( !b_forced_demux )
831                 return VLC_EGENERIC;
832             break;
833         }
834         unsigned i_samples = 0;
835         int i_size = pf_check( &p_peek[i_skip], &i_samples );
836         if( i_size >= 0 )
837         {
838             if( i_size == 0 || /* 0 sized frame ?? */
839                 i_skip == 0 /* exact match from start, we're not WAVE either, so skip multiple checks (would break if padding) */ )
840                 break;
841
842             /* If we have the frame size, check the next frame for
843              * extra robustness
844              * The second test is because some .wav have paddings
845              */
846             bool b_ok = false;
847             for( int t = 0; t < 1 + !!b_wav; t++ )
848             {
849                 if( t == 1 )
850                 {
851                     if(!i_samples)
852                         break;
853                     i_size = i_samples * 2 * 2;
854                 }
855
856                 if( i_skip + i_check_size + i_size <= (size_t)i_peek )
857                 {
858                     b_ok = pf_check( &p_peek[i_skip+i_size], NULL ) >= 0;
859                     if( b_ok )
860                         break;
861                 }
862             }
863             if( b_ok )
864                 break;
865         }
866         if( b_use_word )
867             i_skip += ((i_offset + i_skip) % 2 == 0) ? 2 : 1;
868         else
869             i_skip++;
870         if( !b_wav && !b_forced_demux )
871             return VLC_EGENERIC;
872     }
873
874     *pi_offset = i_offset + i_skip;
875     return VLC_SUCCESS;
876 }
877
878 /*****************************************************************************
879  * Mpeg I/II Audio
880  *****************************************************************************/
881 static int MpgaCheckSync( const uint8_t *p_peek )
882 {
883     uint32_t h = GetDWBE( p_peek );
884
885     if( ((( h >> 21 )&0x07FF) != 0x07FF )   /* header sync */
886         || (((h >> 19)&0x03) == 1 )         /* valid version ID ? */
887         || (((h >> 17)&0x03) == 0 )         /* valid layer ?*/
888         || (((h >> 12)&0x0F) == 0x0F )      /* valid bitrate ?*/
889         || (((h >> 10) & 0x03) == 0x03 )    /* valide sampling freq ? */
890         || ((h & 0x03) == 0x02 ))           /* valid emphasis ? */
891     {
892         return false;
893     }
894     return true;
895 }
896
897 #define MPGA_VERSION( h )   ( 1 - (((h)>>19)&0x01) )
898 #define MPGA_MODE(h)        (((h)>> 6)&0x03)
899
900 static int MpgaGetFrameSamples( uint32_t h )
901 {
902     const int i_layer = 3 - (((h)>>17)&0x03);
903     switch( i_layer )
904     {
905     case 0:
906         return 384;
907     case 1:
908         return 1152;
909     case 2:
910         return MPGA_VERSION(h) ? 576 : 1152;
911     default:
912         return 0;
913     }
914 }
915
916 static int MpgaProbe( demux_t *p_demux, uint64_t *pi_offset )
917 {
918     const uint16_t rgi_twocc[] = { WAVE_FORMAT_MPEG, WAVE_FORMAT_MPEGLAYER3, WAVE_FORMAT_UNKNOWN };
919     bool   b_forced;
920     bool   b_forced_demux;
921     uint64_t i_offset;
922
923     const uint8_t *p_peek;
924     uint64_t i_skip;
925     ssize_t i_peek;
926
927     b_forced = demux_IsPathExtension( p_demux, ".mp3" );
928     b_forced_demux = demux_IsForced( p_demux, "mp3" ) ||
929                      demux_IsForced( p_demux, "mpga" );
930
931     i_offset = vlc_stream_Tell( p_demux->s );
932
933     if( WavSkipHeader( p_demux, &i_skip, rgi_twocc, NULL ) )
934     {
935         if( !b_forced_demux )
936             return VLC_EGENERIC;
937
938         return VLC_EGENERIC;
939     }
940
941     i_peek = vlc_stream_Peek( p_demux->s, &p_peek, i_skip + 4 );
942     if( i_peek <= 0 || (uint64_t) i_peek < i_skip + 4 )
943         return VLC_EGENERIC;
944
945     if( !MpgaCheckSync( &p_peek[i_skip] ) )
946     {
947         bool b_ok = false;
948
949         if( !b_forced_demux && !b_forced )
950             return VLC_EGENERIC;
951
952         i_peek = vlc_stream_Peek( p_demux->s, &p_peek, i_skip + 8096 );
953         while( i_peek > 0 && i_skip + 4 < (uint64_t) i_peek )
954         {
955             if( MpgaCheckSync( &p_peek[i_skip] ) )
956             {
957                 b_ok = true;
958                 break;
959             }
960             i_skip++;
961         }
962         if( !b_ok && !b_forced_demux )
963             return VLC_EGENERIC;
964     }
965     *pi_offset = i_offset + i_skip;
966     return VLC_SUCCESS;
967 }
968
969 static void MpgaXingSkip( const uint8_t **pp_xing, int *pi_xing, int i_count )
970 {
971     if(i_count > *pi_xing )
972         i_count = *pi_xing;
973
974     (*pp_xing) += i_count;
975     (*pi_xing) -= i_count;
976 }
977
978 static uint32_t MpgaXingGetDWBE( const uint8_t **pp_xing, int *pi_xing, uint32_t i_default )
979 {
980     if( *pi_xing < 4 )
981         return i_default;
982
983     uint32_t v = GetDWBE( *pp_xing );
984
985     MpgaXingSkip( pp_xing, pi_xing, 4 );
986
987     return v;
988 }
989
990 static uint16_t MpgaXingGetWBE( const uint8_t **pp_xing, int *pi_xing, uint16_t i_default )
991 {
992     if( *pi_xing < 2 )
993         return i_default;
994
995     uint16_t v = GetWBE( *pp_xing );
996
997     MpgaXingSkip( pp_xing, pi_xing, 2 );
998
999     return v;
1000 }
1001
1002 static double MpgaXingLameConvertGain( uint16_t x )
1003 {
1004     double gain = (x & 0x1FF) / 10.0;
1005
1006     return x & 0x200 ? -gain : gain;
1007 }
1008
1009 static double MpgaXingLameConvertPeak( uint32_t x )
1010 {
1011     return x / 8388608.0; /* pow(2, 23) */
1012 }
1013
1014 static uint64_t SeekByMlltTable( demux_t *p_demux, vlc_tick_t *pi_time )
1015 {
1016     demux_sys_t *p_sys = p_demux->p_sys;
1017     sync_table_ctx_t *p_cur = &p_sys->mllt.current;
1018
1019     /* reset or init context */
1020     if( *pi_time < p_cur->i_time || !p_cur->br.p )
1021     {
1022         p_cur->i_time = 0;
1023         p_cur->i_pos = 0;
1024         bs_init(&p_cur->br, p_sys->mllt.p_bits, p_sys->mllt.i_bits);
1025     }
1026
1027     while(!bs_eof(&p_cur->br))
1028     {
1029         const uint32_t i_bytesdev = bs_read(&p_cur->br, p_sys->mllt.i_bits_per_bytes_dev);
1030         const uint32_t i_msdev = bs_read(&p_cur->br, p_sys->mllt.i_bits_per_ms_dev);
1031         if(bs_error(&p_cur->br))
1032             break;
1033         const vlc_tick_t i_deltatime = VLC_TICK_FROM_MS(p_sys->mllt.i_ms_btw_refs + i_msdev);
1034         if( p_cur->i_time + i_deltatime > *pi_time )
1035             break;
1036         p_cur->i_time += i_deltatime;
1037         p_cur->i_pos += p_sys->mllt.i_bytes_btw_refs + i_bytesdev;
1038     }
1039     *pi_time = p_cur->i_time;
1040     return p_cur->i_pos;
1041 }
1042
1043 static int ID3TAG_Parse_Handler( uint32_t i_tag, const uint8_t *p_payload, size_t i_payload, void *p_priv )
1044 {
1045     demux_t *p_demux = (demux_t *) p_priv;
1046     demux_sys_t *p_sys = p_demux->p_sys;
1047
1048     if( i_tag == VLC_FOURCC('M', 'L', 'L', 'T') )
1049     {
1050         if( i_payload > 20 )
1051         {
1052             p_sys->mllt.i_frames_btw_refs = GetWBE(p_payload);
1053             p_sys->mllt.i_bytes_btw_refs = GetDWBE(&p_payload[1]) & 0x00FFFFFF;
1054             p_sys->mllt.i_ms_btw_refs = GetDWBE(&p_payload[4]) & 0x00FFFFFF;
1055             if( !p_sys->mllt.i_frames_btw_refs || !p_sys->mllt.i_bytes_btw_refs ||
1056                     !p_sys->mllt.i_ms_btw_refs ||
1057                     p_payload[8] > 31 || p_payload[9] > 31 || /* bits length sanity check */
1058                     ((p_payload[8] + p_payload[9]) % 4) || p_payload[8] + p_payload[9] < 4 )
1059                 return VLC_EGENERIC;
1060             p_sys->mllt.i_bits_per_bytes_dev = p_payload[8];
1061             p_sys->mllt.i_bits_per_ms_dev = p_payload[9];
1062             p_sys->mllt.p_bits = malloc(i_payload - 10);
1063             if( likely(p_sys->mllt.p_bits) )
1064             {
1065                 p_sys->mllt.i_bits = i_payload - 10;
1066                 memcpy(p_sys->mllt.p_bits, &p_payload[10], p_sys->mllt.i_bits);
1067                 msg_Dbg(p_demux, "read MLLT sync table with %zu entries",
1068                         (p_sys->mllt.i_bits * 8) / (p_sys->mllt.i_bits_per_bytes_dev + p_sys->mllt.i_bits_per_ms_dev) );
1069             }
1070         }
1071         return VLC_EGENERIC;
1072     }
1073     else if( i_tag == VLC_FOURCC('T', 'X', 'X', 'X') )
1074     {
1075         vlc_meta_t *p_meta = vlc_meta_New();
1076         if( p_meta )
1077         {
1078             bool b_updated;
1079             if( ID3HandleTag( p_payload, i_payload, i_tag, p_meta, &b_updated ) )
1080             {
1081                 char ** ppsz_keys = vlc_meta_CopyExtraNames( p_meta );
1082                 if( ppsz_keys )
1083                 {
1084                     for( size_t i = 0; ppsz_keys[i]; ++i )
1085                     {
1086                         float *pf = NULL;
1087                         if(     !strcasecmp( ppsz_keys[i], "REPLAYGAIN_TRACK_GAIN" ) )
1088                             pf = &p_sys->rgf_replay_gain[AUDIO_REPLAY_GAIN_TRACK];
1089                         else if( !strcasecmp( ppsz_keys[i], "REPLAYGAIN_TRACK_PEAK" ) )
1090                             pf = &p_sys->rgf_replay_peak[AUDIO_REPLAY_GAIN_TRACK];
1091                         else if( !strcasecmp( ppsz_keys[i], "REPLAYGAIN_ALBUM_GAIN" ) )
1092                             pf = &p_sys->rgf_replay_gain[AUDIO_REPLAY_GAIN_ALBUM];
1093                         else if( !strcasecmp( ppsz_keys[i], "REPLAYGAIN_ALBUM_PEAK" ) )
1094                             pf = &p_sys->rgf_replay_peak[AUDIO_REPLAY_GAIN_ALBUM];
1095                         if( pf )
1096                         {
1097                             const char *psz_val = vlc_meta_GetExtra( p_meta, ppsz_keys[i] );
1098                             if( psz_val )
1099                                 *pf = us_atof( psz_val );
1100                         }
1101                         free( ppsz_keys[i] );
1102                     }
1103                     free( ppsz_keys );
1104                 }
1105             }
1106             vlc_meta_Delete( p_meta );
1107         }
1108     }
1109     else if ( i_tag == VLC_FOURCC('C', 'H', 'A', 'P') && i_payload >= 17 )
1110     {
1111         char *psz_title = strndup( (const char *)p_payload, i_payload - 16 );
1112         size_t i_offset = psz_title ? strlen( psz_title ) : 0;
1113         if( p_payload[i_offset] != 0 )
1114         {
1115             free( psz_title );
1116             return VLC_EGENERIC;
1117         }
1118         chap_entry_t e;
1119         e.p_seekpoint = vlc_seekpoint_New();
1120         if( e.p_seekpoint )
1121         {
1122             e.p_seekpoint->psz_name = psz_title;
1123             e.p_seekpoint->i_time_offset = VLC_TICK_FROM_MS(GetDWBE(&p_payload[1 + i_offset]));
1124             e.i_offset = GetDWBE(&p_payload[1 + i_offset + 8]);
1125             p_payload += i_offset + 1 + 16;
1126             i_payload -= i_offset + 1 + 16;
1127             if( 12 < i_payload && !memcmp("TIT2", p_payload, 4) )
1128             {
1129                 psz_title = NULL; /* optional alloc */
1130                 const char *psz = ID3TextConvert(&p_payload[10], i_payload-12, &psz_title);
1131                 if( psz ) /* replace with TIT2 */
1132                 {
1133                     free( e.p_seekpoint->psz_name );
1134                     e.p_seekpoint->psz_name = (psz_title) ? psz_title : strdup( psz );
1135                 }
1136             }
1137             TAB_APPEND(p_sys->chapters.i_count, p_sys->chapters.p_entry, e);
1138         } else free( psz_title );
1139     }
1140
1141     return VLC_SUCCESS;
1142 }
1143
1144 static int ID3Parse( demux_t *p_demux,
1145                      int (*pf_callback)(uint32_t, const uint8_t *, size_t, void *) )
1146 {
1147     const block_t *p_tags = NULL;
1148
1149     if( vlc_stream_Control( p_demux->s, STREAM_GET_TAGS, &p_tags ) != VLC_SUCCESS )
1150         return VLC_EGENERIC;
1151
1152     for( ; p_tags; p_tags = p_tags->p_next )
1153         ID3TAG_Parse( p_tags->p_buffer, p_tags->i_buffer, pf_callback, (void *) p_demux );
1154
1155     return VLC_SUCCESS;
1156 }
1157
1158 static int MpgaInit( demux_t *p_demux )
1159 {
1160     demux_sys_t *p_sys = p_demux->p_sys;
1161
1162     const uint8_t *p_peek;
1163     int i_peek;
1164
1165     /* */
1166     p_sys->i_packet_size = 1024;
1167
1168     ID3Parse( p_demux, ID3TAG_Parse_Handler );
1169
1170     /* Load a potential xing header */
1171     i_peek = vlc_stream_Peek( p_demux->s, &p_peek, 4 + 1024 );
1172     if( i_peek < 4 + 21 )
1173         return VLC_SUCCESS;
1174
1175     const uint32_t header = GetDWBE( p_peek );
1176     if( !MpgaCheckSync( p_peek ) )
1177         return VLC_SUCCESS;
1178
1179     /* Xing header */
1180     const uint8_t *p_xing = p_peek;
1181     int i_xing = i_peek;
1182     int i_skip;
1183
1184     if( MPGA_VERSION( header ) == 0 )
1185         i_skip = MPGA_MODE( header ) != 3 ? 36 : 21;
1186     else
1187         i_skip = MPGA_MODE( header ) != 3 ? 21 : 13;
1188
1189     if( i_skip + 8 >= i_xing || memcmp( &p_xing[i_skip], "Xing", 4 ) )
1190         return VLC_SUCCESS;
1191
1192     const uint32_t i_flags = GetDWBE( &p_xing[i_skip+4] );
1193
1194     MpgaXingSkip( &p_xing, &i_xing, i_skip + 8 );
1195
1196     if( i_flags&0x01 )
1197         p_sys->xing.i_frames = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
1198     if( i_flags&0x02 )
1199         p_sys->xing.i_bytes = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
1200     if( i_flags&0x04 ) /* TODO Support XING TOC to improve seeking accuracy */
1201         MpgaXingSkip( &p_xing, &i_xing, 100 );
1202     if( i_flags&0x08 )
1203     {
1204         /* FIXME: doesn't return the right bitrage average, at least
1205            with some MP3's */
1206         p_sys->xing.i_bitrate_avg = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
1207         msg_Dbg( p_demux, "xing vbr value present (%d)",
1208                  p_sys->xing.i_bitrate_avg );
1209     }
1210
1211     if( p_sys->xing.i_frames > 0 && p_sys->xing.i_bytes > 0 )
1212     {
1213         p_sys->xing.i_frame_samples = MpgaGetFrameSamples( header );
1214         msg_Dbg( p_demux, "xing frames&bytes value present "
1215                  "(%d bytes, %d frames, %d samples/frame)",
1216                  p_sys->xing.i_bytes, p_sys->xing.i_frames,
1217                  p_sys->xing.i_frame_samples );
1218     }
1219
1220     if( i_xing >= 20 && memcmp( p_xing, "LAME", 4 ) == 0)
1221     {
1222         p_sys->xing.b_lame = true;
1223         lame_extra_t *p_lame = &p_sys->xing.lame;
1224
1225         memcpy( p_lame->psz_version, p_xing, 9 );
1226         p_lame->psz_version[9] = '\0';
1227
1228         MpgaXingSkip( &p_xing, &i_xing, 9 );
1229         MpgaXingSkip( &p_xing, &i_xing, 1 ); /* rev_method */
1230
1231         p_lame->i_lowpass = (*p_xing) * 100;
1232         MpgaXingSkip( &p_xing, &i_xing, 1 );
1233
1234         uint32_t peak  = MpgaXingGetDWBE( &p_xing, &i_xing, 0 );
1235         uint16_t track = MpgaXingGetWBE( &p_xing, &i_xing, 0 );
1236         uint16_t album = MpgaXingGetWBE( &p_xing, &i_xing, 0 );
1237
1238         p_sys->rgf_replay_peak[AUDIO_REPLAY_GAIN_TRACK] = (float) MpgaXingLameConvertPeak( peak );
1239         p_sys->rgf_replay_gain[AUDIO_REPLAY_GAIN_TRACK] = (float) MpgaXingLameConvertGain( track );
1240         p_sys->rgf_replay_gain[AUDIO_REPLAY_GAIN_ALBUM] = (float) MpgaXingLameConvertGain( album );
1241
1242         MpgaXingSkip( &p_xing, &i_xing, 1 ); /* flags */
1243     }
1244
1245     return VLC_SUCCESS;
1246 }
1247
1248 /*****************************************************************************
1249  * AAC
1250  *****************************************************************************/
1251 static int AacProbe( demux_t *p_demux, uint64_t *pi_offset )
1252 {
1253     bool   b_forced;
1254     bool   b_forced_demux;
1255
1256     uint64_t i_offset;
1257     const uint8_t *p_peek;
1258
1259     b_forced = demux_IsPathExtension( p_demux, ".aac" ) ||
1260                demux_IsPathExtension( p_demux, ".aacp" );
1261     b_forced_demux = demux_IsForced( p_demux, "m4a" ) ||
1262                      demux_IsForced( p_demux, "aac" ) ||
1263                      demux_IsForced( p_demux, "mp4a" );
1264
1265     if( !b_forced_demux && !b_forced )
1266         return VLC_EGENERIC;
1267
1268     i_offset = vlc_stream_Tell( p_demux->s );
1269
1270     /* peek the begining (10 is for adts header) */
1271     if( vlc_stream_Peek( p_demux->s, &p_peek, 10 ) < 10 )
1272         return VLC_EGENERIC;
1273
1274     if( !strncmp( (char *)p_peek, "ADIF", 4 ) )
1275     {
1276         msg_Err( p_demux, "ADIF file. Not yet supported. (Please report)" );
1277         return VLC_EGENERIC;
1278     }
1279
1280     *pi_offset = i_offset;
1281     return VLC_SUCCESS;
1282 }
1283 static int AacInit( demux_t *p_demux )
1284 {
1285     demux_sys_t *p_sys = p_demux->p_sys;
1286
1287     p_sys->i_packet_size = 4096;
1288     p_sys->i_original = VLC_FOURCC('H','E','A','D');
1289
1290     return VLC_SUCCESS;
1291 }
1292
1293
1294 /*****************************************************************************
1295  * A52
1296  *****************************************************************************/
1297 static int A52CheckSync( const uint8_t *p_peek, bool *p_big_endian, unsigned *pi_samples, bool b_eac3 )
1298 {
1299     vlc_a52_header_t header;
1300     uint8_t p_tmp[VLC_A52_MIN_HEADER_SIZE];
1301
1302     *p_big_endian =  p_peek[0] == 0x0b && p_peek[1] == 0x77;
1303     if( !*p_big_endian )
1304     {
1305         swab( p_peek, p_tmp, VLC_A52_MIN_HEADER_SIZE );
1306         p_peek = p_tmp;
1307     }
1308
1309     if( vlc_a52_header_Parse( &header, p_peek, VLC_A52_MIN_HEADER_SIZE ) )
1310         return VLC_EGENERIC;
1311
1312     if( !header.b_eac3 != !b_eac3 )
1313         return VLC_EGENERIC;
1314     if( pi_samples )
1315         *pi_samples = header.i_samples;
1316     return header.i_size;
1317 }
1318 static int EA52CheckSyncProbe( const uint8_t *p_peek, unsigned *pi_samples )
1319 {
1320     bool b_dummy;
1321     return A52CheckSync( p_peek, &b_dummy, pi_samples, true );
1322 }
1323
1324 static int EA52Probe( demux_t *p_demux, uint64_t *pi_offset )
1325 {
1326     const char *ppsz_name[] = { "eac3", NULL };
1327     const uint16_t rgi_twocc[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_A52, WAVE_FORMAT_UNKNOWN };
1328
1329     return GenericProbe( p_demux, pi_offset, ppsz_name, EA52CheckSyncProbe,
1330                          VLC_A52_MIN_HEADER_SIZE,
1331                          1920 + VLC_A52_MIN_HEADER_SIZE + 1,
1332                          WAV_EXTRA_PROBE_SIZE,
1333                          true, rgi_twocc, GenericFormatCheck );
1334 }
1335
1336 static int A52CheckSyncProbe( const uint8_t *p_peek, unsigned *pi_samples )
1337 {
1338     bool b_dummy;
1339     return A52CheckSync( p_peek, &b_dummy, pi_samples, false );
1340 }
1341
1342 static int A52Probe( demux_t *p_demux, uint64_t *pi_offset )
1343 {
1344     const char *ppsz_name[] = { "a52", "ac3", NULL };
1345     const uint16_t rgi_twocc[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_A52, WAVE_FORMAT_UNKNOWN };
1346
1347     return GenericProbe( p_demux, pi_offset, ppsz_name, A52CheckSyncProbe,
1348                          VLC_A52_MIN_HEADER_SIZE,
1349                          1920 + VLC_A52_MIN_HEADER_SIZE + 1,
1350                          WAV_EXTRA_PROBE_SIZE,
1351                          true, rgi_twocc, GenericFormatCheck );
1352 }
1353
1354 static int A52Init( demux_t *p_demux )
1355 {
1356     demux_sys_t *p_sys = p_demux->p_sys;
1357
1358     p_sys->b_big_endian = false;
1359     p_sys->i_packet_size = 1024;
1360
1361     const uint8_t *p_peek;
1362
1363     /* peek the begining */
1364     if( vlc_stream_Peek( p_demux->s, &p_peek, VLC_A52_MIN_HEADER_SIZE ) >= VLC_A52_MIN_HEADER_SIZE )
1365     {
1366         A52CheckSync( p_peek, &p_sys->b_big_endian, NULL, true );
1367     }
1368     return VLC_SUCCESS;
1369 }
1370
1371 /*****************************************************************************
1372  * DTS
1373  *****************************************************************************/
1374 static int DtsCheckSync( const uint8_t *p_peek, unsigned *pi_samples )
1375 {
1376     VLC_UNUSED(pi_samples);
1377
1378     vlc_dts_header_t dts;
1379     if( vlc_dts_header_Parse( &dts, p_peek, VLC_DTS_HEADER_SIZE ) == VLC_SUCCESS
1380      && dts.i_frame_size > 0 && dts.i_frame_size <= 8192 )
1381     {
1382         if( pi_samples )
1383             *pi_samples = dts.i_frame_length;
1384         return dts.i_frame_size;
1385     }
1386     else
1387         return VLC_EGENERIC;
1388 }
1389
1390 static int DtsProbe( demux_t *p_demux, uint64_t *pi_offset )
1391 {
1392     const char *ppsz_name[] = { "dts", NULL };
1393     const uint16_t rgi_twocc[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_DTSINC_DTS, WAVE_FORMAT_UNKNOWN };
1394
1395     return GenericProbe( p_demux, pi_offset, ppsz_name, DtsCheckSync,
1396                          VLC_DTS_HEADER_SIZE,
1397                          16384 + VLC_DTS_HEADER_SIZE + 1,
1398                          WAV_EXTRA_PROBE_SIZE,
1399                          false, rgi_twocc, NULL );
1400 }
1401 static int DtsInit( demux_t *p_demux )
1402 {
1403     demux_sys_t *p_sys = p_demux->p_sys;
1404
1405     p_sys->i_packet_size = 16384;
1406
1407     return VLC_SUCCESS;
1408 }
1409
1410 /*****************************************************************************
1411  * MLP
1412  *****************************************************************************/
1413 static int MlpCheckSync( const uint8_t *p_peek, unsigned *pi_samples )
1414 {
1415     if( p_peek[4+0] != 0xf8 || p_peek[4+1] != 0x72 || p_peek[4+2] != 0x6f )
1416         return -1;
1417
1418     if( p_peek[4+3] != 0xbb )
1419         return -1;
1420
1421     /* TODO checksum and real size for robustness */
1422     VLC_UNUSED(pi_samples);
1423     return 0;
1424 }
1425 static int ThdCheckSync( const uint8_t *p_peek, unsigned *pi_samples )
1426 {
1427     if( p_peek[4+0] != 0xf8 || p_peek[4+1] != 0x72 || p_peek[4+2] != 0x6f )
1428         return -1;
1429
1430     if( p_peek[4+3] != 0xba )
1431         return -1;
1432
1433     /* TODO checksum and real size for robustness */
1434     VLC_UNUSED(pi_samples);
1435     return 0;
1436 }
1437 static int MlpProbe( demux_t *p_demux, uint64_t *pi_offset )
1438 {
1439     const char *ppsz_name[] = { "mlp", NULL };
1440     const uint16_t rgi_twocc[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_UNKNOWN };
1441
1442     return GenericProbe( p_demux, pi_offset, ppsz_name, MlpCheckSync,
1443                          4+28+16*4, BASE_PROBE_SIZE, WAV_EXTRA_PROBE_SIZE,
1444                          false, rgi_twocc, GenericFormatCheck );
1445 }
1446 static int ThdProbe( demux_t *p_demux, uint64_t *pi_offset )
1447 {
1448     const char *ppsz_name[] = { "thd", NULL };
1449     const uint16_t rgi_twocc[] = { WAVE_FORMAT_PCM, WAVE_FORMAT_UNKNOWN };
1450
1451     return GenericProbe( p_demux, pi_offset, ppsz_name, ThdCheckSync,
1452                          4+28+16*4, BASE_PROBE_SIZE, WAV_EXTRA_PROBE_SIZE,
1453                          false, rgi_twocc, GenericFormatCheck );
1454 }
1455 static int MlpInit( demux_t *p_demux )
1456
1457 {
1458     demux_sys_t *p_sys = p_demux->p_sys;
1459
1460     p_sys->i_packet_size = 4096;
1461
1462     return VLC_SUCCESS;
1463 }
1464
1465 /*****************************************************************************
1466  * Video
1467  *****************************************************************************/
1468 static int VideoInit( demux_t *p_demux )
1469 {
1470     demux_sys_t *p_sys = p_demux->p_sys;
1471
1472     p_sys->i_packet_size = 4096;
1473
1474     return VLC_SUCCESS;
1475 }