]> git.sesse.net Git - vlc/blob - modules/demux/avi/avi.c
LGPL
[vlc] / modules / demux / avi / avi.c
1 /*****************************************************************************
2  * avi.c : AVI file Stream input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
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 #include <assert.h>
32 #include <ctype.h>
33
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_demux.h>
37 #include <vlc_input.h>
38
39 #include <vlc_dialog.h>
40
41 #include <vlc_meta.h>
42 #include <vlc_codecs.h>
43 #include <vlc_charset.h>
44 #include <vlc_memory.h>
45
46 #include "libavi.h"
47 #include "../rawdv.h"
48
49 /*****************************************************************************
50  * Module descriptor
51  *****************************************************************************/
52
53 #define INTERLEAVE_TEXT N_("Force interleaved method" )
54
55 #define INDEX_TEXT N_("Force index creation")
56 #define INDEX_LONGTEXT N_( \
57     "Recreate a index for the AVI file. Use this if your AVI file is damaged "\
58     "or incomplete (not seekable)." )
59
60 static int  Open ( vlc_object_t * );
61 static void Close( vlc_object_t * );
62
63 static const int pi_index[] = {0,1,2,3};
64
65 static const char *const ppsz_indexes[] = { N_("Ask for action"),
66                                             N_("Always fix"),
67                                             N_("Never fix"),
68                                             N_("Fix when necessary")};
69
70 vlc_module_begin ()
71     set_shortname( "AVI" )
72     set_description( N_("AVI demuxer") )
73     set_capability( "demux", 212 )
74     set_category( CAT_INPUT )
75     set_subcategory( SUBCAT_INPUT_DEMUX )
76
77     add_bool( "avi-interleaved", false,
78               INTERLEAVE_TEXT, INTERLEAVE_TEXT, true )
79     add_integer( "avi-index", 0,
80               INDEX_TEXT, INDEX_LONGTEXT, false )
81         change_integer_list( pi_index, ppsz_indexes )
82
83     set_callbacks( Open, Close )
84 vlc_module_end ()
85
86 /*****************************************************************************
87  * Local prototypes
88  *****************************************************************************/
89 static int Control         ( demux_t *, int, va_list );
90 static int Seek            ( demux_t *, mtime_t, int );
91 static int Demux_Seekable  ( demux_t * );
92 static int Demux_UnSeekable( demux_t * );
93
94 static char *FromACP( const char *str )
95 {
96     return FromCharset(vlc_pgettext("GetACP", "CP1252"), str, strlen(str));
97 }
98
99 #define IGNORE_ES NAV_ES
100
101 typedef struct
102 {
103     vlc_fourcc_t i_fourcc;
104     off_t        i_pos;
105     uint32_t     i_size;
106     vlc_fourcc_t i_type;     /* only for AVIFOURCC_LIST */
107
108     uint8_t      i_peek[8];  /* first 8 bytes */
109
110     unsigned int i_stream;
111     unsigned int i_cat;
112 } avi_packet_t;
113
114
115 typedef struct
116 {
117     vlc_fourcc_t i_id;
118     uint32_t     i_flags;
119     off_t        i_pos;
120     uint32_t     i_length;
121     int64_t      i_lengthtotal;
122
123 } avi_entry_t;
124
125 typedef struct
126 {
127     unsigned int    i_size;
128     unsigned int    i_max;
129     avi_entry_t     *p_entry;
130
131 } avi_index_t;
132 static void avi_index_Init( avi_index_t * );
133 static void avi_index_Clean( avi_index_t * );
134 static void avi_index_Append( avi_index_t *, off_t *, avi_entry_t * );
135
136 typedef struct
137 {
138     bool            b_activated;
139     bool            b_eof;
140
141     unsigned int    i_cat; /* AUDIO_ES, VIDEO_ES */
142     vlc_fourcc_t    i_codec;
143
144     int             i_rate;
145     int             i_scale;
146     unsigned int    i_samplesize;
147
148     es_out_id_t     *p_es;
149
150     int             i_dv_audio_rate;
151     es_out_id_t     *p_es_dv_audio;
152
153     /* Avi Index */
154     avi_index_t     idx;
155
156     unsigned int    i_idxposc;  /* numero of chunk */
157     unsigned int    i_idxposb;  /* byte in the current chunk */
158
159     /* For VBR audio only */
160     unsigned int    i_blockno;
161     unsigned int    i_blocksize;
162
163 } avi_track_t;
164
165 struct demux_sys_t
166 {
167     mtime_t i_time;
168     mtime_t i_length;
169
170     bool  b_seekable;
171     avi_chunk_t ck_root;
172
173     bool  b_odml;
174
175     off_t   i_movi_begin;
176     off_t   i_movi_lastchunk_pos;   /* XXX position of last valid chunk */
177
178     /* number of streams and information */
179     unsigned int i_track;
180     avi_track_t  **track;
181
182     /* meta */
183     vlc_meta_t  *meta;
184
185     unsigned int       i_attachment;
186     input_attachment_t **attachment;
187 };
188
189 static inline off_t __EVEN( off_t i )
190 {
191     return (i & 1) ? i + 1 : i;
192 }
193
194 static mtime_t AVI_PTSToChunk( avi_track_t *, mtime_t i_pts );
195 static mtime_t AVI_PTSToByte ( avi_track_t *, mtime_t i_pts );
196 static mtime_t AVI_GetDPTS   ( avi_track_t *, int64_t i_count );
197 static mtime_t AVI_GetPTS    ( avi_track_t * );
198
199
200 static int AVI_StreamChunkFind( demux_t *, unsigned int i_stream );
201 static int AVI_StreamChunkSet ( demux_t *,
202                                 unsigned int i_stream, unsigned int i_ck );
203 static int AVI_StreamBytesSet ( demux_t *,
204                                 unsigned int i_stream, off_t   i_byte );
205
206 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t );
207 static int   AVI_GetKeyFlag    ( vlc_fourcc_t , uint8_t * );
208
209 static int AVI_PacketGetHeader( demux_t *, avi_packet_t *p_pk );
210 static int AVI_PacketNext     ( demux_t * );
211 static int AVI_PacketRead     ( demux_t *, avi_packet_t *, block_t **);
212 static int AVI_PacketSearch   ( demux_t * );
213
214 static void AVI_IndexLoad    ( demux_t * );
215 static void AVI_IndexCreate  ( demux_t * );
216
217 static void AVI_ExtractSubtitle( demux_t *, unsigned int i_stream, avi_chunk_list_t *, avi_chunk_STRING_t * );
218
219 static void AVI_DvHandleAudio( demux_t *, avi_track_t *, block_t * );
220
221 static mtime_t  AVI_MovieGetLength( demux_t * );
222
223 static void AVI_MetaLoad( demux_t *, avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih );
224
225 /*****************************************************************************
226  * Stream management
227  *****************************************************************************/
228 static int        AVI_TrackSeek  ( demux_t *, int, mtime_t );
229 static int        AVI_TrackStopFinishedStreams( demux_t *);
230
231 /* Remarks:
232  - For VBR mp3 stream:
233     count blocks by rounded-up chunksizes instead of chunks
234     we need full emulation of dshow avi demuxer bugs :(
235     fixes silly nandub-style a-v delaying in avi with vbr mp3...
236     (from mplayer 2002/08/02)
237  - to complete....
238  */
239
240 /*****************************************************************************
241  * Open: check file and initializes AVI structures
242  *****************************************************************************/
243 static int Open( vlc_object_t * p_this )
244 {
245     demux_t  *p_demux = (demux_t *)p_this;
246     demux_sys_t     *p_sys;
247
248     bool       b_index = false, b_aborted = false;
249     int              i_do_index;
250
251     avi_chunk_list_t    *p_riff;
252     avi_chunk_list_t    *p_hdrl, *p_movi;
253     avi_chunk_avih_t    *p_avih;
254
255     unsigned int i_track;
256     unsigned int i, i_peeker;
257
258     const uint8_t *p_peek;
259
260     /* Is it an avi file ? */
261     if( stream_Peek( p_demux->s, &p_peek, 200 ) < 200 ) return VLC_EGENERIC;
262
263     for( i_peeker = 0; i_peeker < 188; i_peeker++ )
264     {
265         if( !strncmp( (char *)&p_peek[0], "RIFF", 4 ) && !strncmp( (char *)&p_peek[8], "AVI ", 4 ) )
266             break;
267         if( !strncmp( (char *)&p_peek[0], "ON2 ", 4 ) && !strncmp( (char *)&p_peek[8], "ON2f", 4 ) )
268             break;
269         p_peek++;
270     }
271     if( i_peeker == 188 )
272     {
273         return VLC_EGENERIC;
274     }
275
276     /* Initialize input structures. */
277     p_sys = p_demux->p_sys = calloc( 1, sizeof(demux_sys_t) );
278     p_sys->b_odml   = false;
279     p_sys->track    = NULL;
280     p_sys->meta     = NULL;
281     TAB_INIT(p_sys->i_attachment, p_sys->attachment);
282
283     stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_seekable );
284
285     p_demux->pf_control = Control;
286     p_demux->pf_demux = Demux_Seekable;
287
288     /* For unseekable stream, automatically use Demux_UnSeekable */
289     if( !p_sys->b_seekable
290      || var_InheritBool( p_demux, "avi-interleaved" ) )
291     {
292         p_demux->pf_demux = Demux_UnSeekable;
293     }
294
295     if( i_peeker > 0 )
296     {
297         stream_Read( p_demux->s, NULL, i_peeker );
298     }
299
300     if( AVI_ChunkReadRoot( p_demux->s, &p_sys->ck_root ) )
301     {
302         msg_Err( p_demux, "avi module discarded (invalid file)" );
303         free(p_sys);
304         return VLC_EGENERIC;
305     }
306
307     if( AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF ) > 1 )
308     {
309         unsigned int i_count =
310             AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF );
311
312         msg_Warn( p_demux, "multiple riff -> OpenDML ?" );
313         for( i = 1; i < i_count; i++ )
314         {
315             avi_chunk_list_t *p_sysx;
316
317             p_sysx = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, i );
318             if( p_sysx->i_type == AVIFOURCC_AVIX )
319             {
320                 msg_Warn( p_demux, "detected OpenDML file" );
321                 p_sys->b_odml = true;
322                 break;
323             }
324         }
325     }
326
327     p_riff  = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
328     p_hdrl  = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
329     p_movi  = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0 );
330     if( !p_movi )
331         p_movi  = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_movi, 0 );
332
333     if( !p_hdrl || !p_movi )
334     {
335         msg_Err( p_demux, "invalid file: cannot find hdrl or movi chunks" );
336         goto error;
337     }
338
339     if( !( p_avih = AVI_ChunkFind( p_hdrl, AVIFOURCC_avih, 0 ) ) )
340     {
341         msg_Err( p_demux, "invalid file: cannot find avih chunk" );
342         goto error;
343     }
344     i_track = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
345     if( p_avih->i_streams != i_track )
346     {
347         msg_Warn( p_demux,
348                   "found %d stream but %d are declared",
349                   i_track, p_avih->i_streams );
350     }
351     if( i_track == 0 )
352     {
353         msg_Err( p_demux, "no stream defined!" );
354         goto error;
355     }
356
357     /* print information on streams */
358     msg_Dbg( p_demux, "AVIH: %d stream, flags %s%s%s%s ",
359              i_track,
360              p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
361              p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
362              p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
363              p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
364
365     AVI_MetaLoad( p_demux, p_riff, p_avih );
366
367     /* now read info on each stream and create ES */
368     for( i = 0 ; i < i_track; i++ )
369     {
370         avi_track_t           *tk     = calloc( 1, sizeof( avi_track_t ) );
371         if( unlikely( !tk ) )
372             goto error;
373
374         avi_chunk_list_t      *p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
375         avi_chunk_strh_t      *p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
376         avi_chunk_STRING_t    *p_strn = AVI_ChunkFind( p_strl, AVIFOURCC_strn, 0 );
377         avi_chunk_strf_auds_t *p_auds = NULL;
378         avi_chunk_strf_vids_t *p_vids = NULL;
379         es_format_t fmt;
380
381         tk->b_eof = false;
382         tk->b_activated = true;
383
384         p_vids = (avi_chunk_strf_vids_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
385         p_auds = (avi_chunk_strf_auds_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
386
387         if( p_strl == NULL || p_strh == NULL || p_auds == NULL || p_vids == NULL )
388         {
389             msg_Warn( p_demux, "stream[%d] incomplete", i );
390             free( tk );
391             continue;
392         }
393
394         tk->i_rate  = p_strh->i_rate;
395         tk->i_scale = p_strh->i_scale;
396         tk->i_samplesize = p_strh->i_samplesize;
397         msg_Dbg( p_demux, "stream[%d] rate:%d scale:%d samplesize:%d",
398                  i, tk->i_rate, tk->i_scale, tk->i_samplesize );
399
400         switch( p_strh->i_type )
401         {
402             case( AVIFOURCC_auds ):
403                 tk->i_cat   = AUDIO_ES;
404                 if( p_auds->p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
405                     p_auds->p_wf->cbSize >= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) )
406                 {
407                     WAVEFORMATEXTENSIBLE *p_wfe = (WAVEFORMATEXTENSIBLE *)p_auds->p_wf;
408                     tk->i_codec = AVI_FourccGetCodec( AUDIO_ES,
409                                                       p_wfe->SubFormat.Data1 );
410                 }
411                 else
412                     tk->i_codec = AVI_FourccGetCodec( AUDIO_ES,
413                                                       p_auds->p_wf->wFormatTag );
414
415                 tk->i_blocksize = p_auds->p_wf->nBlockAlign;
416                 if( tk->i_blocksize == 0 )
417                 {
418                     if( p_auds->p_wf->wFormatTag == 1 )
419                         tk->i_blocksize = p_auds->p_wf->nChannels * (p_auds->p_wf->wBitsPerSample/8);
420                     else
421                         tk->i_blocksize = 1;
422                 }
423                 else if( tk->i_samplesize != 0 && tk->i_samplesize != tk->i_blocksize )
424                 {
425                     msg_Warn( p_demux, "track[%d] samplesize=%d and blocksize=%d are not equal."
426                                        "Using blocksize as a workaround.",
427                                        i, tk->i_samplesize, tk->i_blocksize );
428                     tk->i_samplesize = tk->i_blocksize;
429                 }
430
431                 if( tk->i_codec == VLC_CODEC_VORBIS )
432                 {
433                     tk->i_blocksize = 0; /* fix vorbis VBR decoding */
434                 }
435
436                 es_format_Init( &fmt, AUDIO_ES, tk->i_codec );
437
438                 fmt.audio.i_channels        = p_auds->p_wf->nChannels;
439                 fmt.audio.i_rate            = p_auds->p_wf->nSamplesPerSec;
440                 fmt.i_bitrate               = p_auds->p_wf->nAvgBytesPerSec*8;
441                 fmt.audio.i_blockalign      = p_auds->p_wf->nBlockAlign;
442                 fmt.audio.i_bitspersample   = p_auds->p_wf->wBitsPerSample;
443                 fmt.b_packetized            = !tk->i_blocksize;
444
445                 msg_Dbg( p_demux,
446                     "stream[%d] audio(0x%x - %s) %d channels %dHz %dbits",
447                     i, p_auds->p_wf->wFormatTag,vlc_fourcc_GetDescription(AUDIO_ES,tk->i_codec),
448                     p_auds->p_wf->nChannels,
449                     p_auds->p_wf->nSamplesPerSec,
450                     p_auds->p_wf->wBitsPerSample );
451
452                 fmt.i_extra = __MIN( p_auds->p_wf->cbSize,
453                     p_auds->i_chunk_size - sizeof(WAVEFORMATEX) );
454                 if( fmt.i_extra > 0 )
455                 {
456                     fmt.p_extra = malloc( fmt.i_extra );
457                     if( !fmt.p_extra ) goto error;
458                     memcpy( fmt.p_extra, &p_auds->p_wf[1], fmt.i_extra );
459                 }
460                 break;
461
462             case( AVIFOURCC_vids ):
463             {
464                 tk->i_cat   = VIDEO_ES;
465                 tk->i_codec = AVI_FourccGetCodec( VIDEO_ES,
466                                                   p_vids->p_bih->biCompression );
467                 if( p_vids->p_bih->biCompression == VLC_FOURCC( 'D', 'X', 'S', 'B' ) )
468                 {
469                    msg_Dbg( p_demux, "stream[%d] subtitles", i );
470                    es_format_Init( &fmt, SPU_ES, p_vids->p_bih->biCompression );
471                    tk->i_cat = SPU_ES;
472                    break;
473                 }
474                 else if( p_vids->p_bih->biCompression == 0x00 )
475                 {
476                     switch( p_vids->p_bih->biBitCount )
477                     {
478                         case 32:
479                             tk->i_codec = VLC_CODEC_RGB32;
480                             break;
481                         case 24:
482                             tk->i_codec = VLC_CODEC_RGB24;
483                             break;
484                         case 16: /* Yes it is RV15 */
485                         case 15:
486                             tk->i_codec = VLC_CODEC_RGB15;
487                             break;
488                         case 9: /* <- TODO check that */
489                             tk->i_codec = VLC_CODEC_I410;
490                             break;
491                         case 8: /* <- TODO check that */
492                             tk->i_codec = VLC_CODEC_GREY;
493                             break;
494                     }
495                     es_format_Init( &fmt, VIDEO_ES, tk->i_codec );
496
497                     switch( tk->i_codec )
498                     {
499                     case VLC_CODEC_RGB24:
500                     case VLC_CODEC_RGB32:
501                         fmt.video.i_rmask = 0x00ff0000;
502                         fmt.video.i_gmask = 0x0000ff00;
503                         fmt.video.i_bmask = 0x000000ff;
504                         break;
505                     case VLC_CODEC_RGB15:
506                         fmt.video.i_rmask = 0x7c00;
507                         fmt.video.i_gmask = 0x03e0;
508                         fmt.video.i_bmask = 0x001f;
509                         break;
510                     default:
511                         break;
512                     }
513                 }
514                 else
515                 {
516                     es_format_Init( &fmt, VIDEO_ES, p_vids->p_bih->biCompression );
517                     if( tk->i_codec == VLC_CODEC_MP4V &&
518                         !strncasecmp( (char*)&p_strh->i_handler, "XVID", 4 ) )
519                     {
520                         fmt.i_codec           =
521                         fmt.i_original_fourcc = VLC_FOURCC( 'X', 'V', 'I', 'D' );
522                     }
523                 }
524                 tk->i_samplesize = 0;
525                 fmt.video.i_width  = p_vids->p_bih->biWidth;
526                 fmt.video.i_height = p_vids->p_bih->biHeight;
527                 fmt.video.i_bits_per_pixel = p_vids->p_bih->biBitCount;
528                 fmt.video.i_frame_rate = tk->i_rate;
529                 fmt.video.i_frame_rate_base = tk->i_scale;
530                 avi_chunk_vprp_t *p_vprp = AVI_ChunkFind( p_strl, AVIFOURCC_vprp, 0 );
531                 if( p_vprp )
532                 {
533                     uint32_t i_frame_aspect_ratio = p_vprp->i_frame_aspect_ratio;
534                     if( p_vprp->i_video_format_token >= 1 &&
535                         p_vprp->i_video_format_token <= 4 )
536                         i_frame_aspect_ratio = 0x00040003;
537                     fmt.video.i_sar_num = ((i_frame_aspect_ratio >> 16) & 0xffff) * fmt.video.i_height;
538                     fmt.video.i_sar_den = ((i_frame_aspect_ratio >>  0) & 0xffff) * fmt.video.i_width;
539                 }
540
541                 msg_Dbg( p_demux, "stream[%d] video(%4.4s) %"PRIu32"x%"PRIu32" %dbpp %ffps",
542                          i, (char*)&p_vids->p_bih->biCompression,
543                          (uint32_t)p_vids->p_bih->biWidth,
544                          (uint32_t)p_vids->p_bih->biHeight,
545                          p_vids->p_bih->biBitCount,
546                          (float)tk->i_rate/(float)tk->i_scale );
547
548                 if( p_vids->p_bih->biCompression == 0x00 )
549                 {
550                     /* RGB DIB are coded from bottom to top */
551                     fmt.video.i_height =
552                         (unsigned int)(-(int)p_vids->p_bih->biHeight);
553                 }
554
555                 /* Extract palette from extradata if bpp <= 8
556                  * (assumes that extradata contains only palette but appears
557                  *  to be true for all palettized codecs we support) */
558                 if( fmt.video.i_bits_per_pixel > 0 && fmt.video.i_bits_per_pixel <= 8 )
559                 {
560                     /* The palette should not be included in biSize, but come
561                      * directly after BITMAPINFORHEADER in the BITMAPINFO structure */
562                     fmt.i_extra = p_vids->i_chunk_size - sizeof(VLC_BITMAPINFOHEADER);
563                     if( fmt.i_extra > 0 )
564                     {
565                         fmt.p_extra = malloc( fmt.i_extra );
566                         if( !fmt.p_extra ) goto error;
567                         memcpy( fmt.p_extra, &p_vids->p_bih[1], fmt.i_extra );
568
569                         const uint8_t *p_pal = fmt.p_extra;
570
571                         fmt.video.p_palette = calloc( 1, sizeof(video_palette_t) );
572                         fmt.video.p_palette->i_entries = __MIN(fmt.i_extra/4, 256);
573
574                         for( int k = 0; k < fmt.video.p_palette->i_entries; k++ )
575                         {
576                             for( int j = 0; j < 4; j++ )
577                                 fmt.video.p_palette->palette[k][j] = p_pal[4*k+j];
578                         }
579                     }
580                 }
581                 break;
582             }
583
584             case( AVIFOURCC_txts):
585                 msg_Dbg( p_demux, "stream[%d] subtitle attachment", i );
586                 AVI_ExtractSubtitle( p_demux, i, p_strl, p_strn );
587                 free( tk );
588                 continue;
589
590             case( AVIFOURCC_iavs):
591             case( AVIFOURCC_ivas):
592                 msg_Dbg( p_demux, "stream[%d] iavs with handler %4.4s", i, (char *)&p_strh->i_handler );
593                 tk->i_cat   = VIDEO_ES;
594                 tk->i_codec = AVI_FourccGetCodec( VIDEO_ES, p_strh->i_handler );
595                 tk->i_samplesize = 0;
596                 tk->i_dv_audio_rate = tk->i_codec == VLC_CODEC_DV ? -1 : 0;
597
598                 es_format_Init( &fmt, VIDEO_ES, p_strh->i_handler );
599                 fmt.video.i_width  = p_avih->i_width;
600                 fmt.video.i_height = p_avih->i_height;
601                 break;
602
603             case( AVIFOURCC_mids):
604                 msg_Dbg( p_demux, "stream[%d] midi is UNSUPPORTED", i );
605
606             default:
607                 msg_Warn( p_demux, "stream[%d] unknown type %4.4s", i, (char *)&p_strh->i_type );
608                 free( tk );
609                 continue;
610         }
611         if( p_strn )
612             fmt.psz_description = FromACP( p_strn->p_str );
613         tk->p_es = es_out_Add( p_demux->out, &fmt );
614         TAB_APPEND( p_sys->i_track, p_sys->track, tk );
615         es_format_Clean( &fmt );
616     }
617
618     if( p_sys->i_track <= 0 )
619     {
620         msg_Err( p_demux, "no valid track" );
621         goto error;
622     }
623
624     i_do_index = var_InheritInteger( p_demux, "avi-index" );
625     if( i_do_index == 1 ) /* Always fix */
626     {
627 aviindex:
628         if( p_sys->b_seekable )
629         {
630             AVI_IndexCreate( p_demux );
631         }
632         else
633         {
634             msg_Warn( p_demux, "cannot create index (unseekable stream)" );
635             AVI_IndexLoad( p_demux );
636         }
637     }
638     else
639     {
640         AVI_IndexLoad( p_demux );
641     }
642
643     /* *** movie length in sec *** */
644     p_sys->i_length = AVI_MovieGetLength( p_demux );
645
646     /* Check the index completeness */
647     unsigned int i_idx_totalframes = 0;
648     for( unsigned int i = 0; i < p_sys->i_track; i++ )
649     {
650         const avi_track_t *tk = p_sys->track[i];
651         if( tk->i_cat == VIDEO_ES && tk->idx.p_entry )
652             i_idx_totalframes = __MAX(i_idx_totalframes, tk->idx.i_size);
653             continue;
654     }
655     if( i_idx_totalframes != p_avih->i_totalframes &&
656         p_sys->i_length < (mtime_t)p_avih->i_totalframes *
657                           (mtime_t)p_avih->i_microsecperframe /
658                           (mtime_t)1000000 )
659     {
660         if( !vlc_object_alive( p_demux) )
661             goto error;
662
663         msg_Warn( p_demux, "broken or missing index, 'seek' will be "
664                            "approximative or will exhibit strange behavior" );
665         if( (i_do_index == 0 || i_do_index == 3) && !b_index )
666         {
667             if( !p_sys->b_seekable ) {
668                 b_index = true;
669                 goto aviindex;
670             }
671             if( i_do_index == 0 )
672             {
673                 switch( dialog_Question( p_demux, _("Broken or missing AVI Index") ,
674                    _( "Because this AVI file index is broken or missing, "
675                       "seeking will not work correctly.\n"
676                       "VLC won't repair your file but can temporary fix this "
677                       "problem by building an index in memory.\n"
678                       "This step might take a long time on a large file.\n"
679                       "What do you want to do?" ),
680                       _( "Build index then play" ), _( "Play as is" ), _( "Do not play") ) )
681                 {
682                     case 1:
683                         b_index = true;
684                         msg_Dbg( p_demux, "Fixing AVI index" );
685                         goto aviindex;
686                     case 3:
687                         b_aborted = true;
688                         goto error;
689                 }
690             }
691             else
692             {
693                 b_index = true;
694                 msg_Dbg( p_demux, "Fixing AVI index" );
695                 goto aviindex;
696             }
697         }
698     }
699
700     /* fix some BeOS MediaKit generated file */
701     for( i = 0 ; i < p_sys->i_track; i++ )
702     {
703         avi_track_t         *tk = p_sys->track[i];
704         avi_chunk_list_t    *p_strl;
705         avi_chunk_strf_auds_t    *p_auds;
706
707         if( tk->i_cat != AUDIO_ES )
708         {
709             continue;
710         }
711         if( tk->idx.i_size < 1 ||
712             tk->i_scale != 1 ||
713             tk->i_samplesize != 0 )
714         {
715             continue;
716         }
717         p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
718         p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
719
720         if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
721             (unsigned int)tk->i_rate == p_auds->p_wf->nSamplesPerSec )
722         {
723             int64_t i_track_length =
724                 tk->idx.p_entry[tk->idx.i_size-1].i_length +
725                 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal;
726             mtime_t i_length = (mtime_t)p_avih->i_totalframes *
727                                (mtime_t)p_avih->i_microsecperframe;
728
729             if( i_length == 0 )
730             {
731                 msg_Warn( p_demux, "track[%d] cannot be fixed (BeOS MediaKit generated)", i );
732                 continue;
733             }
734             tk->i_samplesize = 1;
735             tk->i_rate       = i_track_length  * (int64_t)1000000/ i_length;
736             msg_Warn( p_demux, "track[%d] fixed with rate=%d scale=%d (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
737         }
738     }
739
740     if( p_sys->b_seekable )
741     {
742         /* we have read all chunk so go back to movi */
743         stream_Seek( p_demux->s, p_movi->i_chunk_pos );
744     }
745     /* Skip movi header */
746     stream_Read( p_demux->s, NULL, 12 );
747
748     p_sys->i_movi_begin = p_movi->i_chunk_pos;
749     return VLC_SUCCESS;
750
751 error:
752     for( unsigned i = 0; i < p_sys->i_attachment; i++)
753         vlc_input_attachment_Delete(p_sys->attachment[i]);
754     free(p_sys->attachment);
755
756     if( p_sys->meta )
757         vlc_meta_Delete( p_sys->meta );
758
759     AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
760     free( p_sys );
761     return b_aborted ? VLC_ETIMEOUT : VLC_EGENERIC;
762 }
763
764 /*****************************************************************************
765  * Close: frees unused data
766  *****************************************************************************/
767 static void Close ( vlc_object_t * p_this )
768 {
769     demux_t *    p_demux = (demux_t *)p_this;
770     demux_sys_t *p_sys = p_demux->p_sys  ;
771
772     for( unsigned int i = 0; i < p_sys->i_track; i++ )
773     {
774         if( p_sys->track[i] )
775         {
776             avi_index_Clean( &p_sys->track[i]->idx );
777             free( p_sys->track[i] );
778         }
779     }
780     free( p_sys->track );
781
782     AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
783     vlc_meta_Delete( p_sys->meta );
784
785     for( unsigned i = 0; i < p_sys->i_attachment; i++)
786         vlc_input_attachment_Delete(p_sys->attachment[i]);
787     free(p_sys->attachment);
788
789     free( p_sys );
790 }
791
792 /*****************************************************************************
793  * Demux_Seekable: reads and demuxes data packets for stream seekable
794  *****************************************************************************
795  * AVIDemux: reads and demuxes data packets
796  *****************************************************************************
797  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
798  *****************************************************************************/
799 typedef struct
800 {
801     bool b_ok;
802
803     int i_toread;
804
805     off_t i_posf; /* where we will read :
806                    if i_idxposb == 0 : begining of chunk (+8 to acces data)
807                    else : point on data directly */
808 } avi_track_toread_t;
809
810 static int Demux_Seekable( demux_t *p_demux )
811 {
812     demux_sys_t *p_sys = p_demux->p_sys;
813
814     unsigned int i_track_count = 0;
815     unsigned int i_track;
816     /* cannot be more than 100 stream (dcXX or wbXX) */
817     avi_track_toread_t toread[100];
818
819
820     /* detect new selected/unselected streams */
821     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
822     {
823         avi_track_t *tk = p_sys->track[i_track];
824         bool  b;
825
826         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
827         if( tk->p_es_dv_audio )
828         {
829             bool b_extra;
830             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
831             b |= b_extra;
832         }
833         if( b && !tk->b_activated )
834         {
835             if( p_sys->b_seekable)
836             {
837                 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
838             }
839             tk->b_activated = true;
840         }
841         else if( !b && tk->b_activated )
842         {
843             tk->b_activated = false;
844         }
845         if( b )
846         {
847             i_track_count++;
848         }
849     }
850
851     if( i_track_count <= 0 )
852     {
853         int64_t i_length = p_sys->i_length * (mtime_t)1000000;
854
855         p_sys->i_time += 25*1000;  /* read 25ms */
856         if( i_length > 0 )
857         {
858             if( p_sys->i_time >= i_length )
859                 return 0;
860             return 1;
861         }
862         msg_Warn( p_demux, "no track selected, exiting..." );
863         return 0;
864     }
865
866     /* wait for the good time */
867     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
868     p_sys->i_time += 25*1000;  /* read 25ms */
869
870     /* init toread */
871     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
872     {
873         avi_track_t *tk = p_sys->track[i_track];
874         mtime_t i_dpts;
875
876         toread[i_track].b_ok = tk->b_activated && !tk->b_eof;
877         if( tk->i_idxposc < tk->idx.i_size )
878         {
879             toread[i_track].i_posf = tk->idx.p_entry[tk->i_idxposc].i_pos;
880            if( tk->i_idxposb > 0 )
881            {
882                 toread[i_track].i_posf += 8 + tk->i_idxposb;
883            }
884         }
885         else
886         {
887             toread[i_track].i_posf = -1;
888         }
889
890         i_dpts = p_sys->i_time - AVI_GetPTS( tk  );
891
892         if( tk->i_samplesize )
893         {
894             toread[i_track].i_toread = AVI_PTSToByte( tk, llabs( i_dpts ) );
895         }
896         else
897         {
898             toread[i_track].i_toread = AVI_PTSToChunk( tk, llabs( i_dpts ) );
899         }
900
901         if( i_dpts < 0 )
902         {
903             toread[i_track].i_toread *= -1;
904         }
905     }
906
907     for( ;; )
908     {
909         avi_track_t     *tk;
910         bool       b_done;
911         block_t         *p_frame;
912         off_t i_pos;
913         unsigned int i;
914         size_t i_size;
915
916         /* search for first chunk to be read */
917         for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
918         {
919             if( !toread[i].b_ok ||
920                 AVI_GetDPTS( p_sys->track[i],
921                              toread[i].i_toread ) <= -25 * 1000 )
922             {
923                 continue;
924             }
925
926             if( toread[i].i_toread > 0 )
927             {
928                 b_done = false; /* not yet finished */
929             }
930             if( toread[i].i_posf > 0 )
931             {
932                 if( i_pos == -1 || i_pos > toread[i].i_posf )
933                 {
934                     i_track = i;
935                     i_pos = toread[i].i_posf;
936                 }
937             }
938         }
939
940         if( b_done )
941         {
942             for( i = 0; i < p_sys->i_track; i++ )
943             {
944                 if( toread[i].b_ok )
945                     return 1;
946             }
947             msg_Warn( p_demux, "all tracks have failed, exiting..." );
948             return 0;
949         }
950
951         if( i_pos == -1 )
952         {
953             int i_loop_count = 0;
954
955             /* no valid index, we will parse directly the stream
956              * in case we fail we will disable all finished stream */
957             if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
958             {
959                 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
960                 if( AVI_PacketNext( p_demux ) )
961                 {
962                     return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
963                 }
964             }
965             else
966             {
967                 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
968             }
969
970             for( ;; )
971             {
972                 avi_packet_t avi_pk;
973
974                 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
975                 {
976                     msg_Warn( p_demux,
977                              "cannot get packet header, track disabled" );
978                     return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
979                 }
980                 if( avi_pk.i_stream >= p_sys->i_track ||
981                     ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
982                 {
983                     if( AVI_PacketNext( p_demux ) )
984                     {
985                         msg_Warn( p_demux,
986                                   "cannot skip packet, track disabled" );
987                         return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
988                     }
989
990                     /* Prevents from eating all the CPU with broken files.
991                      * This value should be low enough so that it doesn't
992                      * affect the reading speed too much. */
993                     if( !(++i_loop_count % 1024) )
994                     {
995                         if( !vlc_object_alive (p_demux) ) return -1;
996                         msleep( 10000 );
997
998                         if( !(i_loop_count % (1024 * 10)) )
999                             msg_Warn( p_demux,
1000                                       "don't seem to find any data..." );
1001                     }
1002                     continue;
1003                 }
1004                 else
1005                 {
1006                     i_track = avi_pk.i_stream;
1007                     tk = p_sys->track[i_track];
1008
1009                     /* add this chunk to the index */
1010                     avi_entry_t index;
1011                     index.i_id     = avi_pk.i_fourcc;
1012                     index.i_flags  = AVI_GetKeyFlag(tk->i_codec, avi_pk.i_peek);
1013                     index.i_pos    = avi_pk.i_pos;
1014                     index.i_length = avi_pk.i_size;
1015                     avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1016
1017                     /* do we will read this data ? */
1018                     if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -25*1000 )
1019                     {
1020                         break;
1021                     }
1022                     else
1023                     {
1024                         if( AVI_PacketNext( p_demux ) )
1025                         {
1026                             msg_Warn( p_demux,
1027                                       "cannot skip packet, track disabled" );
1028                             return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1029                         }
1030                     }
1031                 }
1032             }
1033
1034         }
1035         else
1036         {
1037             stream_Seek( p_demux->s, i_pos );
1038         }
1039
1040         /* Set the track to use */
1041         tk = p_sys->track[i_track];
1042
1043         /* read thoses data */
1044         if( tk->i_samplesize )
1045         {
1046             unsigned int i_toread;
1047
1048             if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1049             {
1050                 if( tk->i_samplesize > 1 )
1051                 {
1052                     i_toread = tk->i_samplesize;
1053                 }
1054                 else
1055                 {
1056                     i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1057                     i_toread = __MAX( i_toread, 100 );
1058                 }
1059             }
1060             i_size = __MIN( tk->idx.p_entry[tk->i_idxposc].i_length -
1061                                 tk->i_idxposb,
1062                             i_toread );
1063         }
1064         else
1065         {
1066             i_size = tk->idx.p_entry[tk->i_idxposc].i_length;
1067         }
1068
1069         if( tk->i_idxposb == 0 )
1070         {
1071             i_size += 8; /* need to read and skip header */
1072         }
1073
1074         if( ( p_frame = stream_Block( p_demux->s, __EVEN( i_size ) ) )==NULL )
1075         {
1076             msg_Warn( p_demux, "failed reading data" );
1077             tk->b_eof = false;
1078             toread[i_track].b_ok = false;
1079             continue;
1080         }
1081         if( i_size % 2 )    /* read was padded on word boundary */
1082         {
1083             p_frame->i_buffer--;
1084         }
1085         /* skip header */
1086         if( tk->i_idxposb == 0 )
1087         {
1088             p_frame->p_buffer += 8;
1089             p_frame->i_buffer -= 8;
1090         }
1091         p_frame->i_pts = AVI_GetPTS( tk ) + 1;
1092         if( tk->idx.p_entry[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1093         {
1094             p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1095         }
1096         else
1097         {
1098             p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1099         }
1100
1101         /* read data */
1102         if( tk->i_samplesize )
1103         {
1104             if( tk->i_idxposb == 0 )
1105             {
1106                 i_size -= 8;
1107             }
1108             toread[i_track].i_toread -= i_size;
1109             tk->i_idxposb += i_size;
1110             if( tk->i_idxposb >=
1111                     tk->idx.p_entry[tk->i_idxposc].i_length )
1112             {
1113                 tk->i_idxposb = 0;
1114                 tk->i_idxposc++;
1115             }
1116         }
1117         else
1118         {
1119             int i_length = tk->idx.p_entry[tk->i_idxposc].i_length;
1120
1121             tk->i_idxposc++;
1122             if( tk->i_cat == AUDIO_ES )
1123             {
1124                 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1125             }
1126             toread[i_track].i_toread--;
1127         }
1128
1129         if( tk->i_idxposc < tk->idx.i_size)
1130         {
1131             toread[i_track].i_posf =
1132                 tk->idx.p_entry[tk->i_idxposc].i_pos;
1133             if( tk->i_idxposb > 0 )
1134             {
1135                 toread[i_track].i_posf += 8 + tk->i_idxposb;
1136             }
1137
1138         }
1139         else
1140         {
1141             toread[i_track].i_posf = -1;
1142         }
1143
1144         if( tk->i_cat != VIDEO_ES )
1145             p_frame->i_dts = p_frame->i_pts;
1146         else
1147         {
1148             p_frame->i_dts = p_frame->i_pts;
1149             p_frame->i_pts = VLC_TS_INVALID;
1150         }
1151
1152         if( tk->i_dv_audio_rate )
1153             AVI_DvHandleAudio( p_demux, tk, p_frame );
1154         es_out_Send( p_demux->out, tk->p_es, p_frame );
1155     }
1156 }
1157
1158
1159 /*****************************************************************************
1160  * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1161  *****************************************************************************
1162  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1163  *****************************************************************************/
1164 static int Demux_UnSeekable( demux_t *p_demux )
1165 {
1166     demux_sys_t     *p_sys = p_demux->p_sys;
1167     avi_track_t *p_stream_master = NULL;
1168     unsigned int i_stream;
1169     unsigned int i_packet;
1170
1171     es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
1172
1173     /* *** find master stream for data packet skipping algo *** */
1174     /* *** -> first video, if any, or first audio ES *** */
1175     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1176     {
1177         avi_track_t *tk = p_sys->track[i_stream];
1178         bool  b;
1179
1180         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1181         if( tk->p_es_dv_audio )
1182         {
1183             bool b_extra;
1184             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1185             b |= b_extra;
1186         }
1187
1188         if( b && tk->i_cat == VIDEO_ES )
1189         {
1190             p_stream_master = tk;
1191         }
1192         else if( b )
1193         {
1194             p_stream_master = tk;
1195         }
1196     }
1197
1198     if( !p_stream_master )
1199     {
1200         msg_Warn( p_demux, "no more stream selected" );
1201         return( 0 );
1202     }
1203
1204     p_sys->i_time = AVI_GetPTS( p_stream_master );
1205
1206     for( i_packet = 0; i_packet < 10; i_packet++)
1207     {
1208 #define p_stream    p_sys->track[avi_pk.i_stream]
1209
1210         avi_packet_t    avi_pk;
1211
1212         if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1213         {
1214             return( 0 );
1215         }
1216
1217         if( avi_pk.i_stream >= p_sys->i_track ||
1218             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1219         {
1220             /* we haven't found an audio or video packet:
1221              *  - we have seek, found first next packet
1222              *  - others packets could be found, skip them
1223              */
1224             switch( avi_pk.i_fourcc )
1225             {
1226                 case AVIFOURCC_JUNK:
1227                 case AVIFOURCC_LIST:
1228                 case AVIFOURCC_RIFF:
1229                     return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1230                 case AVIFOURCC_idx1:
1231                     if( p_sys->b_odml )
1232                     {
1233                         return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1234                     }
1235                     return( 0 );    /* eof */
1236                 default:
1237                     msg_Warn( p_demux,
1238                               "seems to have lost position, resync" );
1239                     if( AVI_PacketSearch( p_demux ) )
1240                     {
1241                         msg_Err( p_demux, "resync failed" );
1242                         return( -1 );
1243                     }
1244             }
1245         }
1246         else
1247         {
1248             /* check for time */
1249             if( llabs( AVI_GetPTS( p_stream ) -
1250                         AVI_GetPTS( p_stream_master ) )< 600*1000 )
1251             {
1252                 /* load it and send to decoder */
1253                 block_t *p_frame;
1254                 if( AVI_PacketRead( p_demux, &avi_pk, &p_frame ) || p_frame == NULL )
1255                 {
1256                     return( -1 );
1257                 }
1258                 p_frame->i_pts = AVI_GetPTS( p_stream ) + 1;
1259
1260                 if( avi_pk.i_cat != VIDEO_ES )
1261                     p_frame->i_dts = p_frame->i_pts;
1262                 else
1263                 {
1264                     p_frame->i_dts = p_frame->i_pts;
1265                     p_frame->i_pts = VLC_TS_INVALID;
1266                 }
1267
1268                 if( p_stream->i_dv_audio_rate )
1269                     AVI_DvHandleAudio( p_demux, p_stream, p_frame );
1270                 es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1271             }
1272             else
1273             {
1274                 if( AVI_PacketNext( p_demux ) )
1275                 {
1276                     return( 0 );
1277                 }
1278             }
1279
1280             /* *** update stream time position *** */
1281             if( p_stream->i_samplesize )
1282             {
1283                 p_stream->i_idxposb += avi_pk.i_size;
1284             }
1285             else
1286             {
1287                 if( p_stream->i_cat == AUDIO_ES )
1288                 {
1289                     p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1290                 }
1291                 p_stream->i_idxposc++;
1292             }
1293
1294         }
1295 #undef p_stream
1296     }
1297
1298     return( 1 );
1299 }
1300
1301 /*****************************************************************************
1302  * Seek: goto to i_date or i_percent
1303  *****************************************************************************/
1304 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1305 {
1306     demux_sys_t *p_sys = p_demux->p_sys;
1307     msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1308              i_date / 1000000, i_percent );
1309
1310     if( p_sys->b_seekable )
1311     {
1312         if( !p_sys->i_length )
1313         {
1314             avi_track_t *p_stream = NULL;
1315             unsigned i_stream = 0;
1316             int64_t i_pos;
1317
1318             /* use i_percent to create a true i_date */
1319             msg_Warn( p_demux, "seeking without index at %d%%"
1320                       " only works for interleaved files", i_percent );
1321             if( i_percent >= 100 )
1322             {
1323                 msg_Warn( p_demux, "cannot seek so far !" );
1324                 return VLC_EGENERIC;
1325             }
1326             i_percent = __MAX( i_percent, 0 );
1327
1328             /* try to find chunk that is at i_percent or the file */
1329             i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1330                            p_sys->i_movi_begin );
1331             /* search first selected stream (and prefer non-EOF ones) */
1332             for( unsigned i = 0; i < p_sys->i_track; i++ )
1333             {
1334                 avi_track_t *p_track = p_sys->track[i];
1335                 if( !p_track->b_activated )
1336                     continue;
1337
1338                 p_stream = p_track;
1339                 i_stream = i;
1340                 if( !p_track->b_eof )
1341                     break;
1342             }
1343             if( p_stream == NULL )
1344             {
1345                 msg_Warn( p_demux, "cannot find any selected stream" );
1346                 return VLC_EGENERIC;
1347             }
1348
1349             /* be sure that the index exist */
1350             if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1351             {
1352                 msg_Warn( p_demux, "cannot seek" );
1353                 return VLC_EGENERIC;
1354             }
1355
1356             while( i_pos >= p_stream->idx.p_entry[p_stream->i_idxposc].i_pos +
1357                p_stream->idx.p_entry[p_stream->i_idxposc].i_length + 8 )
1358             {
1359                 /* search after i_idxposc */
1360                 if( AVI_StreamChunkSet( p_demux,
1361                                         i_stream, p_stream->i_idxposc + 1 ) )
1362                 {
1363                     msg_Warn( p_demux, "cannot seek" );
1364                     return VLC_EGENERIC;
1365                 }
1366             }
1367
1368             i_date = AVI_GetPTS( p_stream );
1369             /* TODO better support for i_samplesize != 0 */
1370             msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1371         }
1372
1373         /* */
1374         for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1375         {
1376             avi_track_t *p_stream = p_sys->track[i_stream];
1377
1378             if( !p_stream->b_activated )
1379                 continue;
1380
1381             p_stream->b_eof = AVI_TrackSeek( p_demux, i_stream, i_date ) != 0;
1382         }
1383         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1384         p_sys->i_time = i_date;
1385         msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /1000000 );
1386         return VLC_SUCCESS;
1387     }
1388     else
1389     {
1390         msg_Err( p_demux, "shouldn't yet be executed" );
1391         return VLC_EGENERIC;
1392     }
1393 }
1394
1395 /*****************************************************************************
1396  * Control:
1397  *****************************************************************************/
1398 static double ControlGetPosition( demux_t *p_demux )
1399 {
1400     demux_sys_t *p_sys = p_demux->p_sys;
1401
1402     if( p_sys->i_length > 0 )
1403     {
1404         return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)1000000 );
1405     }
1406     else if( stream_Size( p_demux->s ) > 0 )
1407     {
1408         unsigned int i;
1409         int64_t i_tmp;
1410         int64_t i64 = 0;
1411
1412         /* search the more advanced selected es */
1413         for( i = 0; i < p_sys->i_track; i++ )
1414         {
1415             avi_track_t *tk = p_sys->track[i];
1416             if( tk->b_activated && tk->i_idxposc < tk->idx.i_size )
1417             {
1418                 i_tmp = tk->idx.p_entry[tk->i_idxposc].i_pos +
1419                         tk->idx.p_entry[tk->i_idxposc].i_length + 8;
1420                 if( i_tmp > i64 )
1421                 {
1422                     i64 = i_tmp;
1423                 }
1424             }
1425         }
1426         return (double)i64 / stream_Size( p_demux->s );
1427     }
1428     return 0.0;
1429 }
1430
1431 static int Control( demux_t *p_demux, int i_query, va_list args )
1432 {
1433     demux_sys_t *p_sys = p_demux->p_sys;
1434     int i;
1435     double   f, *pf;
1436     int64_t i64, *pi64;
1437     vlc_meta_t *p_meta;
1438
1439     switch( i_query )
1440     {
1441         case DEMUX_GET_POSITION:
1442             pf = (double*)va_arg( args, double * );
1443             *pf = ControlGetPosition( p_demux );
1444             return VLC_SUCCESS;
1445         case DEMUX_SET_POSITION:
1446             f = (double)va_arg( args, double );
1447             if( p_sys->b_seekable )
1448             {
1449                 i64 = (mtime_t)(1000000.0 * p_sys->i_length * f );
1450                 return Seek( p_demux, i64, (int)(f * 100) );
1451             }
1452             else
1453             {
1454                 int64_t i_pos = stream_Size( p_demux->s ) * f;
1455                 return stream_Seek( p_demux->s, i_pos );
1456             }
1457
1458         case DEMUX_GET_TIME:
1459             pi64 = (int64_t*)va_arg( args, int64_t * );
1460             *pi64 = p_sys->i_time;
1461             return VLC_SUCCESS;
1462
1463         case DEMUX_SET_TIME:
1464         {
1465             int i_percent = 0;
1466
1467             i64 = (int64_t)va_arg( args, int64_t );
1468             if( p_sys->i_length > 0 )
1469             {
1470                 i_percent = 100 * i64 / (p_sys->i_length*1000000);
1471             }
1472             else if( p_sys->i_time > 0 )
1473             {
1474                 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1475                                    (double)i64 / (double)p_sys->i_time );
1476             }
1477             return Seek( p_demux, i64, i_percent );
1478         }
1479         case DEMUX_GET_LENGTH:
1480             pi64 = (int64_t*)va_arg( args, int64_t * );
1481             *pi64 = p_sys->i_length * (mtime_t)1000000;
1482             return VLC_SUCCESS;
1483
1484         case DEMUX_GET_FPS:
1485             pf = (double*)va_arg( args, double * );
1486             *pf = 0.0;
1487             for( i = 0; i < (int)p_sys->i_track; i++ )
1488             {
1489                 avi_track_t *tk = p_sys->track[i];
1490                 if( tk->i_cat == VIDEO_ES && tk->i_scale > 0)
1491                 {
1492                     *pf = (float)tk->i_rate / (float)tk->i_scale;
1493                     break;
1494                 }
1495             }
1496             return VLC_SUCCESS;
1497
1498         case DEMUX_GET_META:
1499             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1500             vlc_meta_Merge( p_meta,  p_sys->meta );
1501             return VLC_SUCCESS;
1502
1503         case DEMUX_GET_ATTACHMENTS:
1504         {
1505             if( p_sys->i_attachment <= 0 )
1506                 return VLC_EGENERIC;
1507
1508             input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1509             int *pi_int = va_arg( args, int * );
1510
1511             *pi_int     = p_sys->i_attachment;
1512             *ppp_attach = calloc( p_sys->i_attachment, sizeof(*ppp_attach));
1513             for( unsigned i = 0; i < p_sys->i_attachment && *ppp_attach; i++ )
1514                 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachment[i] );
1515             return VLC_SUCCESS;
1516         }
1517
1518         default:
1519             return VLC_EGENERIC;
1520     }
1521 }
1522
1523 /*****************************************************************************
1524  * Function to convert pts to chunk or byte
1525  *****************************************************************************/
1526
1527 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1528 {
1529     if( !tk->i_scale )
1530         return (mtime_t)0;
1531
1532     return (mtime_t)((int64_t)i_pts *
1533                      (int64_t)tk->i_rate /
1534                      (int64_t)tk->i_scale /
1535                      (int64_t)1000000 );
1536 }
1537 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1538 {
1539     if( !tk->i_scale || !tk->i_samplesize )
1540         return (mtime_t)0;
1541
1542     return (mtime_t)((int64_t)i_pts *
1543                      (int64_t)tk->i_rate /
1544                      (int64_t)tk->i_scale /
1545                      (int64_t)1000000 *
1546                      (int64_t)tk->i_samplesize );
1547 }
1548
1549 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1550 {
1551     mtime_t i_dpts = 0;
1552
1553     if( !tk->i_rate )
1554         return i_dpts;
1555
1556     i_dpts = (mtime_t)( (int64_t)1000000 *
1557                         (int64_t)i_count *
1558                         (int64_t)tk->i_scale /
1559                         (int64_t)tk->i_rate );
1560
1561     if( tk->i_samplesize )
1562     {
1563         return i_dpts / tk->i_samplesize;
1564     }
1565     return i_dpts;
1566 }
1567
1568 static mtime_t AVI_GetPTS( avi_track_t *tk )
1569 {
1570     if( tk->i_samplesize )
1571     {
1572         int64_t i_count = 0;
1573
1574         /* we need a valid entry we will emulate one */
1575         if( tk->i_idxposc == tk->idx.i_size )
1576         {
1577             if( tk->i_idxposc )
1578             {
1579                 /* use the last entry */
1580                 i_count = tk->idx.p_entry[tk->idx.i_size - 1].i_lengthtotal
1581                             + tk->idx.p_entry[tk->idx.i_size - 1].i_length;
1582             }
1583         }
1584         else
1585         {
1586             i_count = tk->idx.p_entry[tk->i_idxposc].i_lengthtotal;
1587         }
1588         return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1589     }
1590     else
1591     {
1592         if( tk->i_cat == AUDIO_ES )
1593         {
1594             return AVI_GetDPTS( tk, tk->i_blockno );
1595         }
1596         else
1597         {
1598             return AVI_GetDPTS( tk, tk->i_idxposc );
1599         }
1600     }
1601 }
1602
1603 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1604 {
1605     demux_sys_t *p_sys = p_demux->p_sys;
1606     avi_packet_t avi_pk;
1607     int i_loop_count = 0;
1608
1609     /* find first chunk of i_stream that isn't in index */
1610
1611     if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1612     {
1613         stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1614         if( AVI_PacketNext( p_demux ) )
1615         {
1616             return VLC_EGENERIC;
1617         }
1618     }
1619     else
1620     {
1621         stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1622     }
1623
1624     for( ;; )
1625     {
1626         if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
1627
1628         if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1629         {
1630             msg_Warn( p_demux, "cannot get packet header" );
1631             return VLC_EGENERIC;
1632         }
1633         if( avi_pk.i_stream >= p_sys->i_track ||
1634             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1635         {
1636             if( AVI_PacketNext( p_demux ) )
1637             {
1638                 return VLC_EGENERIC;
1639             }
1640
1641             /* Prevents from eating all the CPU with broken files.
1642              * This value should be low enough so that it doesn't
1643              * affect the reading speed too much. */
1644             if( !(++i_loop_count % 1024) )
1645             {
1646                 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
1647                 msleep( 10000 );
1648
1649                 if( !(i_loop_count % (1024 * 10)) )
1650                     msg_Warn( p_demux, "don't seem to find any data..." );
1651             }
1652         }
1653         else
1654         {
1655             avi_track_t *tk_pk = p_sys->track[avi_pk.i_stream];
1656
1657             /* add this chunk to the index */
1658             avi_entry_t index;
1659             index.i_id     = avi_pk.i_fourcc;
1660             index.i_flags  = AVI_GetKeyFlag(tk_pk->i_codec, avi_pk.i_peek);
1661             index.i_pos    = avi_pk.i_pos;
1662             index.i_length = avi_pk.i_size;
1663             avi_index_Append( &tk_pk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1664
1665             if( avi_pk.i_stream == i_stream  )
1666             {
1667                 return VLC_SUCCESS;
1668             }
1669
1670             if( AVI_PacketNext( p_demux ) )
1671             {
1672                 return VLC_EGENERIC;
1673             }
1674         }
1675     }
1676 }
1677
1678 /* be sure that i_ck will be a valid index entry */
1679 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1680                                unsigned int i_ck )
1681 {
1682     demux_sys_t *p_sys = p_demux->p_sys;
1683     avi_track_t *p_stream = p_sys->track[i_stream];
1684
1685     p_stream->i_idxposc = i_ck;
1686     p_stream->i_idxposb = 0;
1687
1688     if(  i_ck >= p_stream->idx.i_size )
1689     {
1690         p_stream->i_idxposc = p_stream->idx.i_size - 1;
1691         do
1692         {
1693             p_stream->i_idxposc++;
1694             if( AVI_StreamChunkFind( p_demux, i_stream ) )
1695             {
1696                 return VLC_EGENERIC;
1697             }
1698
1699         } while( p_stream->i_idxposc < i_ck );
1700     }
1701
1702     return VLC_SUCCESS;
1703 }
1704
1705 /* XXX FIXME up to now, we assume that all chunk are one after one */
1706 static int AVI_StreamBytesSet( demux_t    *p_demux,
1707                                unsigned int i_stream,
1708                                off_t   i_byte )
1709 {
1710     demux_sys_t *p_sys = p_demux->p_sys;
1711     avi_track_t *p_stream = p_sys->track[i_stream];
1712
1713     if( ( p_stream->idx.i_size > 0 )
1714         &&( i_byte < p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_lengthtotal +
1715                 p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_length ) )
1716     {
1717         /* index is valid to find the ck */
1718         /* uses dichototmie to be fast enougth */
1719         int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->idx.i_size - 1 );
1720         int i_idxmax  = p_stream->idx.i_size;
1721         int i_idxmin  = 0;
1722         for( ;; )
1723         {
1724             if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal > i_byte )
1725             {
1726                 i_idxmax  = i_idxposc ;
1727                 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1728             }
1729             else
1730             {
1731                 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal +
1732                         p_stream->idx.p_entry[i_idxposc].i_length <= i_byte)
1733                 {
1734                     i_idxmin  = i_idxposc ;
1735                     i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1736                 }
1737                 else
1738                 {
1739                     p_stream->i_idxposc = i_idxposc;
1740                     p_stream->i_idxposb = i_byte -
1741                             p_stream->idx.p_entry[i_idxposc].i_lengthtotal;
1742                     return VLC_SUCCESS;
1743                 }
1744             }
1745         }
1746
1747     }
1748     else
1749     {
1750         p_stream->i_idxposc = p_stream->idx.i_size - 1;
1751         p_stream->i_idxposb = 0;
1752         do
1753         {
1754             p_stream->i_idxposc++;
1755             if( AVI_StreamChunkFind( p_demux, i_stream ) )
1756             {
1757                 return VLC_EGENERIC;
1758             }
1759
1760         } while( p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal +
1761                     p_stream->idx.p_entry[p_stream->i_idxposc].i_length <= i_byte );
1762
1763         p_stream->i_idxposb = i_byte -
1764                        p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal;
1765         return VLC_SUCCESS;
1766     }
1767 }
1768
1769 static int AVI_TrackSeek( demux_t *p_demux,
1770                            int i_stream,
1771                            mtime_t i_date )
1772 {
1773     demux_sys_t  *p_sys = p_demux->p_sys;
1774     avi_track_t  *tk = p_sys->track[i_stream];
1775
1776 #define p_stream    p_sys->track[i_stream]
1777     mtime_t i_oldpts;
1778
1779     i_oldpts = AVI_GetPTS( p_stream );
1780
1781     if( !p_stream->i_samplesize )
1782     {
1783         if( AVI_StreamChunkSet( p_demux,
1784                                 i_stream,
1785                                 AVI_PTSToChunk( p_stream, i_date ) ) )
1786         {
1787             return VLC_EGENERIC;
1788         }
1789
1790         if( p_stream->i_cat == AUDIO_ES )
1791         {
1792             unsigned int i;
1793             tk->i_blockno = 0;
1794             for( i = 0; i < tk->i_idxposc; i++ )
1795             {
1796                 if( tk->i_blocksize > 0 )
1797                 {
1798                     tk->i_blockno += ( tk->idx.p_entry[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
1799                 }
1800                 else
1801                 {
1802                     tk->i_blockno++;
1803                 }
1804             }
1805         }
1806
1807         msg_Dbg( p_demux,
1808                  "old:%"PRId64" %s new %"PRId64,
1809                  i_oldpts,
1810                  i_oldpts > i_date ? ">" : "<",
1811                  i_date );
1812
1813         if( p_stream->i_cat == VIDEO_ES )
1814         {
1815             /* search key frame */
1816             //if( i_date < i_oldpts || 1 )
1817             {
1818                 while( p_stream->i_idxposc > 0 &&
1819                    !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
1820                                                                 AVIIF_KEYFRAME ) )
1821                 {
1822                     if( AVI_StreamChunkSet( p_demux,
1823                                             i_stream,
1824                                             p_stream->i_idxposc - 1 ) )
1825                     {
1826                         return VLC_EGENERIC;
1827                     }
1828                 }
1829             }
1830 #if 0
1831             else
1832             {
1833                 while( p_stream->i_idxposc < p_stream->idx.i_size &&
1834                         !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
1835                                                                 AVIIF_KEYFRAME ) )
1836                 {
1837                     if( AVI_StreamChunkSet( p_demux,
1838                                             i_stream,
1839                                             p_stream->i_idxposc + 1 ) )
1840                     {
1841                         return VLC_EGENERIC;
1842                     }
1843                 }
1844             }
1845 #endif
1846         }
1847     }
1848     else
1849     {
1850         if( AVI_StreamBytesSet( p_demux,
1851                                 i_stream,
1852                                 AVI_PTSToByte( p_stream, i_date ) ) )
1853         {
1854             return VLC_EGENERIC;
1855         }
1856     }
1857     return VLC_SUCCESS;
1858 #undef p_stream
1859 }
1860
1861 /****************************************************************************
1862  * Return true if it's a key frame
1863  ****************************************************************************/
1864 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
1865 {
1866     switch( i_fourcc )
1867     {
1868         case VLC_CODEC_DIV1:
1869             /* we have:
1870              *  startcode:      0x00000100   32bits
1871              *  framenumber     ?             5bits
1872              *  piture type     0(I),1(P)     2bits
1873              */
1874             if( GetDWBE( p_byte ) != 0x00000100 )
1875             {
1876                 /* it's not an msmpegv1 stream, strange...*/
1877                 return AVIIF_KEYFRAME;
1878             }
1879             return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
1880
1881         case VLC_CODEC_DIV2:
1882         case VLC_CODEC_DIV3:
1883         case VLC_CODEC_WMV1:
1884             /* we have
1885              *  picture type    0(I),1(P)     2bits
1886              */
1887             return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
1888         case VLC_CODEC_MP4V:
1889             /* we should find first occurrence of 0x000001b6 (32bits)
1890              *  startcode:      0x000001b6   32bits
1891              *  piture type     0(I),1(P)     2bits
1892              */
1893             if( GetDWBE( p_byte ) != 0x000001b6 )
1894             {
1895                 /* not true , need to find the first VOP header */
1896                 return AVIIF_KEYFRAME;
1897             }
1898             return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
1899
1900         default:
1901             /* I can't do it, so say yes */
1902             return AVIIF_KEYFRAME;
1903     }
1904 }
1905
1906 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
1907 {
1908     switch( i_cat )
1909     {
1910         case AUDIO_ES:
1911             wf_tag_to_fourcc( i_codec, &i_codec, NULL );
1912             return i_codec;
1913         case VIDEO_ES:
1914             return vlc_fourcc_GetCodec( i_cat, i_codec );
1915         default:
1916             return VLC_FOURCC( 'u', 'n', 'd', 'f' );
1917     }
1918 }
1919
1920 /****************************************************************************
1921  *
1922  ****************************************************************************/
1923 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
1924                                    unsigned int *pi_number, unsigned int *pi_type )
1925 {
1926 #define SET_PTR( p, v ) if( p ) *(p) = (v);
1927     int c1, c2;
1928
1929     c1 = ((uint8_t *)&i_id)[0];
1930     c2 = ((uint8_t *)&i_id)[1];
1931
1932     if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
1933     {
1934         SET_PTR( pi_number, 100 ); /* > max stream number */
1935         SET_PTR( pi_type, UNKNOWN_ES );
1936     }
1937     else
1938     {
1939         SET_PTR( pi_number, (c1 - '0') * 10 + (c2 - '0' ) );
1940         switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
1941         {
1942             case AVITWOCC_wb:
1943                 SET_PTR( pi_type, AUDIO_ES );
1944                 break;
1945             case AVITWOCC_dc:
1946             case AVITWOCC_db:
1947             case AVITWOCC_AC:
1948                 SET_PTR( pi_type, VIDEO_ES );
1949                 break;
1950             case AVITWOCC_tx:
1951             case AVITWOCC_sb:
1952                 SET_PTR( pi_type, SPU_ES );
1953                 break;
1954             case AVITWOCC_pc:
1955                 SET_PTR( pi_type, IGNORE_ES );
1956                 break;
1957             default:
1958                 SET_PTR( pi_type, UNKNOWN_ES );
1959                 break;
1960         }
1961     }
1962 #undef SET_PTR
1963 }
1964
1965 /****************************************************************************
1966  *
1967  ****************************************************************************/
1968 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
1969 {
1970     const uint8_t *p_peek;
1971
1972     if( stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
1973     {
1974         return VLC_EGENERIC;
1975     }
1976     p_pk->i_fourcc  = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
1977     p_pk->i_size    = GetDWLE( p_peek + 4 );
1978     p_pk->i_pos     = stream_Tell( p_demux->s );
1979     if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
1980     {
1981         p_pk->i_type = VLC_FOURCC( p_peek[8],  p_peek[9],
1982                                    p_peek[10], p_peek[11] );
1983     }
1984     else
1985     {
1986         p_pk->i_type = 0;
1987     }
1988
1989     memcpy( p_pk->i_peek, p_peek + 8, 8 );
1990
1991     AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
1992     return VLC_SUCCESS;
1993 }
1994
1995 static int AVI_PacketNext( demux_t *p_demux )
1996 {
1997     avi_packet_t    avi_ck;
1998     int             i_skip = 0;
1999
2000     if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2001     {
2002         return VLC_EGENERIC;
2003     }
2004
2005     if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2006         ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2007     {
2008         i_skip = 12;
2009     }
2010     else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2011              avi_ck.i_type == AVIFOURCC_AVIX )
2012     {
2013         i_skip = 24;
2014     }
2015     else
2016     {
2017         i_skip = __EVEN( avi_ck.i_size ) + 8;
2018     }
2019
2020     if( stream_Read( p_demux->s, NULL, i_skip ) != i_skip )
2021     {
2022         return VLC_EGENERIC;
2023     }
2024     return VLC_SUCCESS;
2025 }
2026
2027 static int AVI_PacketRead( demux_t   *p_demux,
2028                            avi_packet_t     *p_pk,
2029                            block_t          **pp_frame )
2030 {
2031     size_t i_size;
2032
2033     i_size = __EVEN( p_pk->i_size + 8 );
2034
2035     if( ( *pp_frame = stream_Block( p_demux->s, i_size ) ) == NULL )
2036     {
2037         return VLC_EGENERIC;
2038     }
2039     (*pp_frame)->p_buffer += 8;
2040     (*pp_frame)->i_buffer -= 8;
2041
2042     if( i_size != p_pk->i_size + 8 )
2043     {
2044         (*pp_frame)->i_buffer--;
2045     }
2046
2047     return VLC_SUCCESS;
2048 }
2049
2050 static int AVI_PacketSearch( demux_t *p_demux )
2051 {
2052     demux_sys_t     *p_sys = p_demux->p_sys;
2053     avi_packet_t    avi_pk;
2054     int             i_count = 0;
2055
2056     for( ;; )
2057     {
2058         if( stream_Read( p_demux->s, NULL, 1 ) != 1 )
2059         {
2060             return VLC_EGENERIC;
2061         }
2062         AVI_PacketGetHeader( p_demux, &avi_pk );
2063         if( avi_pk.i_stream < p_sys->i_track &&
2064             ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2065         {
2066             return VLC_SUCCESS;
2067         }
2068         switch( avi_pk.i_fourcc )
2069         {
2070             case AVIFOURCC_JUNK:
2071             case AVIFOURCC_LIST:
2072             case AVIFOURCC_RIFF:
2073             case AVIFOURCC_idx1:
2074                 return VLC_SUCCESS;
2075         }
2076
2077         /* Prevents from eating all the CPU with broken files.
2078          * This value should be low enough so that it doesn't affect the
2079          * reading speed too much (not that we care much anyway because
2080          * this code is called only on broken files). */
2081         if( !(++i_count % 1024) )
2082         {
2083             if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
2084
2085             msleep( 10000 );
2086             if( !(i_count % (1024 * 10)) )
2087                 msg_Warn( p_demux, "trying to resync..." );
2088         }
2089     }
2090 }
2091
2092 /****************************************************************************
2093  * Index stuff.
2094  ****************************************************************************/
2095 static void avi_index_Init( avi_index_t *p_index )
2096 {
2097     p_index->i_size  = 0;
2098     p_index->i_max   = 0;
2099     p_index->p_entry = NULL;
2100 }
2101 static void avi_index_Clean( avi_index_t *p_index )
2102 {
2103     free( p_index->p_entry );
2104 }
2105 static void avi_index_Append( avi_index_t *p_index, off_t *pi_last_pos,
2106                               avi_entry_t *p_entry )
2107 {
2108     /* Update last chunk position */
2109     if( *pi_last_pos < p_entry->i_pos )
2110          *pi_last_pos = p_entry->i_pos;
2111
2112     /* add the entry */
2113     if( p_index->i_size >= p_index->i_max )
2114     {
2115         p_index->i_max += 16384;
2116         p_index->p_entry = realloc_or_free( p_index->p_entry,
2117                                             p_index->i_max * sizeof( *p_index->p_entry ) );
2118         if( !p_index->p_entry )
2119             return;
2120     }
2121     /* calculate cumulate length */
2122     if( p_index->i_size > 0 )
2123     {
2124         p_entry->i_lengthtotal =
2125             p_index->p_entry[p_index->i_size - 1].i_length +
2126                 p_index->p_entry[p_index->i_size - 1].i_lengthtotal;
2127     }
2128     else
2129     {
2130         p_entry->i_lengthtotal = 0;
2131     }
2132
2133     p_index->p_entry[p_index->i_size++] = *p_entry;
2134 }
2135
2136 static int AVI_IndexFind_idx1( demux_t *p_demux,
2137                                avi_chunk_idx1_t **pp_idx1,
2138                                uint64_t *pi_offset )
2139 {
2140     demux_sys_t *p_sys = p_demux->p_sys;
2141
2142     avi_chunk_list_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2143     avi_chunk_idx1_t *p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2144
2145     if( !p_idx1 )
2146     {
2147         msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2148         return VLC_EGENERIC;
2149     }
2150     *pp_idx1 = p_idx1;
2151
2152     /* The offset in the index should be from the start of the movi content,
2153      * but some broken files use offset from the start of the file. Just
2154      * checking the offset of the first packet is not enough as some files
2155      * has unused chunk at the beginning of the movi content.
2156      */
2157     avi_chunk_list_t *p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2158     uint64_t i_first_pos = UINT64_MAX;
2159     for( unsigned i = 0; i < __MIN( p_idx1->i_entry_count, 100 ); i++ )
2160         i_first_pos = __MIN( i_first_pos, p_idx1->entry[i].i_pos );
2161
2162     const uint64_t i_movi_content = p_movi->i_chunk_pos + 8;
2163     if( i_first_pos < i_movi_content )
2164     {
2165         *pi_offset = i_movi_content;
2166     }
2167     else if( p_sys->b_seekable && i_first_pos < UINT64_MAX )
2168     {
2169         const uint8_t *p_peek;
2170         if( !stream_Seek( p_demux->s, i_movi_content + i_first_pos ) &&
2171             stream_Peek( p_demux->s, &p_peek, 4 ) >= 4 &&
2172             ( !isdigit( p_peek[0] ) || !isdigit( p_peek[1] ) ||
2173               !isalpha( p_peek[2] ) || !isalpha( p_peek[3] ) ) )
2174             *pi_offset = 0;
2175         else
2176             *pi_offset = i_movi_content;
2177     }
2178     else
2179     {
2180         *pi_offset = 0;
2181     }
2182     return VLC_SUCCESS;
2183 }
2184
2185 static int AVI_IndexLoad_idx1( demux_t *p_demux,
2186                                avi_index_t p_index[], off_t *pi_last_offset )
2187 {
2188     demux_sys_t *p_sys = p_demux->p_sys;
2189
2190     avi_chunk_idx1_t *p_idx1;
2191     uint64_t         i_offset;
2192     if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2193         return VLC_EGENERIC;
2194
2195     for( unsigned i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2196     {
2197         unsigned i_cat;
2198         unsigned i_stream;
2199
2200         AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2201                                &i_stream,
2202                                &i_cat );
2203         if( i_stream < p_sys->i_track &&
2204             (i_cat == p_sys->track[i_stream]->i_cat || i_cat == UNKNOWN_ES ) )
2205         {
2206             avi_entry_t index;
2207             index.i_id     = p_idx1->entry[i_index].i_fourcc;
2208             index.i_flags  = p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2209             index.i_pos    = p_idx1->entry[i_index].i_pos + i_offset;
2210             index.i_length = p_idx1->entry[i_index].i_length;
2211
2212             avi_index_Append( &p_index[i_stream], pi_last_offset, &index );
2213         }
2214     }
2215     return VLC_SUCCESS;
2216 }
2217
2218 static void __Parse_indx( demux_t *p_demux, avi_index_t *p_index, off_t *pi_max_offset,
2219                           avi_chunk_indx_t *p_indx )
2220 {
2221     avi_entry_t index;
2222
2223     msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2224     if( p_indx->i_indexsubtype == 0 )
2225     {
2226         for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2227         {
2228             index.i_id     = p_indx->i_id;
2229             index.i_flags  = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2230             index.i_pos    = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2231             index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2232
2233             avi_index_Append( p_index, pi_max_offset, &index );
2234         }
2235     }
2236     else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2237     {
2238         for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2239         {
2240             index.i_id     = p_indx->i_id;
2241             index.i_flags  = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2242             index.i_pos    = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2243             index.i_length = p_indx->idx.field[i].i_size;
2244
2245             avi_index_Append( p_index, pi_max_offset, &index );
2246         }
2247     }
2248     else
2249     {
2250         msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2251     }
2252 }
2253
2254 static void AVI_IndexLoad_indx( demux_t *p_demux,
2255                                 avi_index_t p_index[], off_t *pi_last_offset )
2256 {
2257     demux_sys_t         *p_sys = p_demux->p_sys;
2258
2259     avi_chunk_list_t    *p_riff;
2260     avi_chunk_list_t    *p_hdrl;
2261
2262     p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2263     p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2264
2265     for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2266     {
2267         avi_chunk_list_t    *p_strl;
2268         avi_chunk_indx_t    *p_indx;
2269
2270 #define p_stream  p_sys->track[i_stream]
2271         p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2272         p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2273
2274         if( !p_indx )
2275         {
2276             if( p_sys->b_odml )
2277                 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2278                                    "file?)" );
2279             continue;
2280         }
2281
2282         if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2283         {
2284             __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, p_indx );
2285         }
2286         else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2287         {
2288             avi_chunk_t    ck_sub;
2289             for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2290             {
2291                 if( stream_Seek( p_demux->s, p_indx->idx.super[i].i_offset )||
2292                     AVI_ChunkRead( p_demux->s, &ck_sub, NULL  ) )
2293                 {
2294                     break;
2295                 }
2296                 if( ck_sub.indx.i_indextype == AVI_INDEX_OF_CHUNKS )
2297                     __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, &ck_sub.indx );
2298                 AVI_ChunkFree( p_demux->s, &ck_sub );
2299             }
2300         }
2301         else
2302         {
2303             msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2304         }
2305 #undef p_stream
2306     }
2307 }
2308
2309 static void AVI_IndexLoad( demux_t *p_demux )
2310 {
2311     demux_sys_t *p_sys = p_demux->p_sys;
2312
2313     /* Load indexes */
2314     assert( p_sys->i_track <= 100 );
2315     avi_index_t p_idx_indx[p_sys->i_track];
2316     avi_index_t p_idx_idx1[p_sys->i_track];
2317     for( unsigned i = 0; i < p_sys->i_track; i++ )
2318     {
2319         avi_index_Init( &p_idx_indx[i] );
2320         avi_index_Init( &p_idx_idx1[i] );
2321     }
2322     off_t i_indx_last_pos = p_sys->i_movi_lastchunk_pos;
2323     off_t i_idx1_last_pos = p_sys->i_movi_lastchunk_pos;
2324
2325     AVI_IndexLoad_indx( p_demux, p_idx_indx, &i_indx_last_pos );
2326     if( !p_sys->b_odml )
2327         AVI_IndexLoad_idx1( p_demux, p_idx_idx1, &i_idx1_last_pos );
2328
2329     /* Select the longest index */
2330     for( unsigned i = 0; i < p_sys->i_track; i++ )
2331     {
2332         if( p_idx_indx[i].i_size > p_idx_idx1[i].i_size )
2333         {
2334             msg_Dbg( p_demux, "selected ODML index for stream[%u]", i );
2335             p_sys->track[i]->idx = p_idx_indx[i];
2336             avi_index_Clean( &p_idx_idx1[i] );
2337         }
2338         else
2339         {
2340             msg_Dbg( p_demux, "selected standard index for stream[%u]", i );
2341             p_sys->track[i]->idx = p_idx_idx1[i];
2342             avi_index_Clean( &p_idx_indx[i] );
2343         }
2344     }
2345     p_sys->i_movi_lastchunk_pos = __MAX( i_indx_last_pos, i_idx1_last_pos );
2346
2347     for( unsigned i = 0; i < p_sys->i_track; i++ )
2348     {
2349         avi_index_t *p_index = &p_sys->track[i]->idx;
2350
2351         /* Fix key flag */
2352         bool b_key = false;
2353         for( unsigned j = 0; !b_key && j < p_index->i_size; j++ )
2354             b_key = p_index->p_entry[j].i_flags & AVIIF_KEYFRAME;
2355         if( !b_key )
2356         {
2357             msg_Err( p_demux, "no key frame set for track %u", i );
2358             for( unsigned j = 0; j < p_index->i_size; j++ )
2359                 p_index->p_entry[j].i_flags |= AVIIF_KEYFRAME;
2360         }
2361
2362         /* */
2363         msg_Dbg( p_demux, "stream[%d] created %d index entries",
2364                  i, p_index->i_size );
2365     }
2366 }
2367
2368 static void AVI_IndexCreate( demux_t *p_demux )
2369 {
2370     demux_sys_t *p_sys = p_demux->p_sys;
2371
2372     avi_chunk_list_t *p_riff;
2373     avi_chunk_list_t *p_movi;
2374
2375     unsigned int i_stream;
2376     off_t i_movi_end;
2377
2378     mtime_t i_dialog_update;
2379     dialog_progress_bar_t *p_dialog = NULL;
2380
2381     p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2382     p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2383
2384     if( !p_movi )
2385     {
2386         msg_Err( p_demux, "cannot find p_movi" );
2387         return;
2388     }
2389
2390     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2391         avi_index_Init( &p_sys->track[i_stream]->idx );
2392
2393     i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2394                         stream_Size( p_demux->s ) );
2395
2396     stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2397     msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2398
2399
2400     /* Only show dialog if AVI is > 10MB */
2401     i_dialog_update = mdate();
2402     if( stream_Size( p_demux->s ) > 10000000 )
2403         p_dialog = dialog_ProgressCreate( p_demux, _("Fixing AVI Index..."),
2404                                        NULL, _("Cancel") );
2405
2406     for( ;; )
2407     {
2408         avi_packet_t pk;
2409
2410         if( !vlc_object_alive (p_demux) )
2411             break;
2412
2413         /* Don't update/check dialog too often */
2414         if( p_dialog && mdate() - i_dialog_update > 100000 )
2415         {
2416             if( dialog_ProgressCancelled( p_dialog ) )
2417                 break;
2418
2419             double f_current = stream_Tell( p_demux->s );
2420             double f_size    = stream_Size( p_demux->s );
2421             double f_pos     = f_current / f_size;
2422             dialog_ProgressSet( p_dialog, NULL, f_pos );
2423
2424             i_dialog_update = mdate();
2425         }
2426
2427         if( AVI_PacketGetHeader( p_demux, &pk ) )
2428             break;
2429
2430         if( pk.i_stream < p_sys->i_track &&
2431             pk.i_cat == p_sys->track[pk.i_stream]->i_cat )
2432         {
2433             avi_track_t *tk = p_sys->track[pk.i_stream];
2434
2435             avi_entry_t index;
2436             index.i_id      = pk.i_fourcc;
2437             index.i_flags   = AVI_GetKeyFlag(tk->i_codec, pk.i_peek);
2438             index.i_pos     = pk.i_pos;
2439             index.i_length  = pk.i_size;
2440             avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
2441         }
2442         else
2443         {
2444             switch( pk.i_fourcc )
2445             {
2446             case AVIFOURCC_idx1:
2447                 if( p_sys->b_odml )
2448                 {
2449                     avi_chunk_list_t *p_sysx;
2450                     p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2451                                             AVIFOURCC_RIFF, 1 );
2452
2453                     msg_Dbg( p_demux, "looking for new RIFF chunk" );
2454                     if( stream_Seek( p_demux->s, p_sysx->i_chunk_pos + 24 ) )
2455                         goto print_stat;
2456                     break;
2457                 }
2458                 goto print_stat;
2459
2460             case AVIFOURCC_RIFF:
2461                     msg_Dbg( p_demux, "new RIFF chunk found" );
2462                     break;
2463
2464             case AVIFOURCC_rec:
2465             case AVIFOURCC_JUNK:
2466                 break;
2467
2468             default:
2469                 msg_Warn( p_demux, "need resync, probably broken avi" );
2470                 if( AVI_PacketSearch( p_demux ) )
2471                 {
2472                     msg_Warn( p_demux, "lost sync, abord index creation" );
2473                     goto print_stat;
2474                 }
2475             }
2476         }
2477
2478         if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2479             AVI_PacketNext( p_demux ) )
2480         {
2481             break;
2482         }
2483     }
2484
2485 print_stat:
2486     if( p_dialog != NULL )
2487         dialog_ProgressDestroy( p_dialog );
2488
2489     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2490     {
2491         msg_Dbg( p_demux, "stream[%d] creating %d index entries",
2492                 i_stream, p_sys->track[i_stream]->idx.i_size );
2493     }
2494 }
2495
2496 /* */
2497 static void AVI_MetaLoad( demux_t *p_demux,
2498                           avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih )
2499 {
2500     demux_sys_t *p_sys = p_demux->p_sys;
2501
2502     vlc_meta_t *p_meta = p_sys->meta = vlc_meta_New();
2503     if( !p_meta )
2504         return;
2505
2506     char buffer[200];
2507     snprintf( buffer, sizeof(buffer), "%s%s%s%s",
2508               p_avih->i_flags&AVIF_HASINDEX      ? " HAS_INDEX"      : "",
2509               p_avih->i_flags&AVIF_MUSTUSEINDEX  ? " MUST_USE_INDEX" : "",
2510               p_avih->i_flags&AVIF_ISINTERLEAVED ? " IS_INTERLEAVED" : "",
2511               p_avih->i_flags&AVIF_TRUSTCKTYPE   ? " TRUST_CKTYPE"   : "" );
2512     vlc_meta_SetSetting( p_meta, buffer );
2513
2514     avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
2515     if( !p_info )
2516         return;
2517
2518     static const struct {
2519         vlc_fourcc_t i_id;
2520         int          i_type;
2521     } p_dsc[] = {
2522         { AVIFOURCC_IART, vlc_meta_Artist },
2523         { AVIFOURCC_ICMT, vlc_meta_Description },
2524         { AVIFOURCC_ICOP, vlc_meta_Copyright },
2525         { AVIFOURCC_IGNR, vlc_meta_Genre },
2526         { AVIFOURCC_INAM, vlc_meta_Title },
2527         { AVIFOURCC_ICRD, vlc_meta_Date },
2528         { AVIFOURCC_ILNG, vlc_meta_Language },
2529         { AVIFOURCC_IRTD, vlc_meta_Rating },
2530         { AVIFOURCC_IWEB, vlc_meta_URL },
2531         { AVIFOURCC_IPRT, vlc_meta_TrackNumber },
2532         { AVIFOURCC_IFRM, vlc_meta_TrackTotal },
2533         { 0, -1 }
2534     };
2535     for( int i = 0; p_dsc[i].i_id != 0; i++ )
2536     {
2537         avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_dsc[i].i_id, 0 );
2538         if( !p_strz )
2539             continue;
2540         char *psz_value = FromACP( p_strz->p_str );
2541         if( !psz_value )
2542             continue;
2543
2544         if( *psz_value )
2545             vlc_meta_Set( p_meta, p_dsc[i].i_type, psz_value );
2546         free( psz_value );
2547     }
2548
2549     static const vlc_fourcc_t p_extra[] = {
2550         AVIFOURCC_IARL, AVIFOURCC_ICMS, AVIFOURCC_ICRP, AVIFOURCC_IDIM, AVIFOURCC_IDPI,
2551         AVIFOURCC_IENG, AVIFOURCC_IKEY, AVIFOURCC_ILGT, AVIFOURCC_IMED, AVIFOURCC_IPLT,
2552         AVIFOURCC_IPRD, AVIFOURCC_ISBJ, AVIFOURCC_ISFT, AVIFOURCC_ISHP, AVIFOURCC_ISRC,
2553         AVIFOURCC_ISRF, AVIFOURCC_ITCH, AVIFOURCC_ISMP, AVIFOURCC_IDIT, AVIFOURCC_ISGN,
2554         AVIFOURCC_IWRI, AVIFOURCC_IPRO, AVIFOURCC_ICNM, AVIFOURCC_IPDS, AVIFOURCC_IEDT,
2555         AVIFOURCC_ICDS, AVIFOURCC_IMUS, AVIFOURCC_ISTD, AVIFOURCC_IDST, AVIFOURCC_ICNT,
2556         AVIFOURCC_ISTR, 0,
2557     };
2558
2559     for( int i = 0; p_extra[i] != 0; i++ )
2560     {
2561         avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_extra[i], 0 );
2562         if( !p_strz )
2563             continue;
2564         char *psz_value = FromACP( p_strz->p_str );
2565         if( !psz_value )
2566             continue;
2567
2568         if( *psz_value )
2569             vlc_meta_AddExtra( p_meta, p_strz->p_type, psz_value );
2570         free( psz_value );
2571     }
2572 }
2573
2574 static void AVI_DvHandleAudio( demux_t *p_demux, avi_track_t *tk, block_t *p_frame )
2575 {
2576     size_t i_offset = 80*6+80*16*3 + 3;
2577     if( p_frame->i_buffer < i_offset + 5 )
2578         return;
2579
2580     if( p_frame->p_buffer[i_offset] != 0x50 )
2581         return;
2582
2583     es_format_t fmt;
2584     dv_get_audio_format( &fmt, &p_frame->p_buffer[i_offset + 1] );
2585
2586     if( tk->p_es_dv_audio && tk->i_dv_audio_rate != fmt.audio.i_rate )
2587     {
2588         es_out_Del( p_demux->out, tk->p_es_dv_audio );
2589         tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2590     }
2591     else if( !tk->p_es_dv_audio )
2592     {
2593         tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2594     }
2595     tk->i_dv_audio_rate = fmt.audio.i_rate;
2596
2597     block_t *p_frame_audio = dv_extract_audio( p_frame );
2598     if( p_frame_audio )
2599         es_out_Send( p_demux->out, tk->p_es_dv_audio, p_frame_audio );
2600 }
2601
2602 /*****************************************************************************
2603  * Subtitles
2604  *****************************************************************************/
2605 static void AVI_ExtractSubtitle( demux_t *p_demux,
2606                                  unsigned int i_stream,
2607                                  avi_chunk_list_t *p_strl,
2608                                  avi_chunk_STRING_t *p_strn )
2609 {
2610     demux_sys_t *p_sys = p_demux->p_sys;
2611     block_t *p_block = NULL;
2612     input_attachment_t *p_attachment = NULL;
2613     char *psz_description = NULL;
2614     avi_chunk_indx_t *p_indx = NULL;
2615
2616     if( !p_sys->b_seekable )
2617         goto exit;
2618
2619     p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2620     avi_chunk_t ck;
2621     int64_t  i_position;
2622     unsigned i_size;
2623     if( p_indx )
2624     {
2625         if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES &&
2626             p_indx->i_entriesinuse > 0 )
2627         {
2628             if( stream_Seek( p_demux->s, p_indx->idx.super[0].i_offset )||
2629                 AVI_ChunkRead( p_demux->s, &ck, NULL  ) )
2630                 goto exit;
2631             p_indx = &ck.indx;
2632         }
2633
2634         if( p_indx->i_indextype != AVI_INDEX_OF_CHUNKS ||
2635             p_indx->i_entriesinuse != 1 ||
2636             p_indx->i_indexsubtype != 0 )
2637             goto exit;
2638
2639         i_position  = p_indx->i_baseoffset +
2640                       p_indx->idx.std[0].i_offset - 8;
2641         i_size      = (p_indx->idx.std[0].i_size & 0x7fffffff) + 8;
2642     }
2643     else
2644     {
2645         avi_chunk_idx1_t *p_idx1;
2646         uint64_t         i_offset;
2647
2648         if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2649             goto exit;
2650
2651         i_size = 0;
2652         for( unsigned i = 0; i < p_idx1->i_entry_count; i++ )
2653         {
2654             const idx1_entry_t *e = &p_idx1->entry[i];
2655             unsigned i_cat;
2656             unsigned i_stream_idx;
2657
2658             AVI_ParseStreamHeader( e->i_fourcc, &i_stream_idx, &i_cat );
2659             if( i_cat == SPU_ES && i_stream_idx == i_stream )
2660             {
2661                 i_position = e->i_pos + i_offset;
2662                 i_size     = e->i_length + 8;
2663                 break;
2664             }
2665         }
2666         if( i_size <= 0 )
2667             goto exit;
2668     }
2669
2670     /* */
2671     if( i_size > 1000000 )
2672         goto exit;
2673
2674     if( stream_Seek( p_demux->s, i_position ) )
2675         goto exit;
2676     p_block = stream_Block( p_demux->s, i_size );
2677     if( !p_block )
2678         goto exit;
2679
2680     /* Parse packet header */
2681     const uint8_t *p = p_block->p_buffer;
2682     if( i_size < 8 || p[2] != 't' || p[3] != 'x' )
2683         goto exit;
2684     p += 8;
2685     i_size -= 8;
2686
2687     /* Parse subtitle chunk header */
2688     if( i_size < 11 || memcmp( p, "GAB2", 4 ) ||
2689         p[4] != 0x00 || GetWLE( &p[5] ) != 0x2 )
2690         goto exit;
2691     const unsigned i_name = GetDWLE( &p[7] );
2692     if( 11 + i_size <= i_name )
2693         goto exit;
2694     if( i_name > 0 )
2695         psz_description = FromCharset( "UTF-16LE", &p[11], i_name );
2696     p += 11 + i_name;
2697     i_size -= 11 + i_name;
2698     if( i_size < 6 || GetWLE( &p[0] ) != 0x04 )
2699         goto exit;
2700     const unsigned i_payload = GetDWLE( &p[2] );
2701     if( i_size < 6 + i_payload || i_payload <= 0 )
2702         goto exit;
2703     p += 6;
2704     i_size -= 6;
2705
2706     if( !psz_description )
2707         psz_description = p_strn ? FromACP( p_strn->p_str ) : NULL;
2708     char *psz_name;
2709     if( asprintf( &psz_name, "subtitle%d.srt", p_sys->i_attachment ) <= 0 )
2710         psz_name = NULL;
2711     p_attachment = vlc_input_attachment_New( psz_name,
2712                                              "application/x-srt",
2713                                              psz_description,
2714                                              p, i_payload );
2715     if( p_attachment )
2716         TAB_APPEND( p_sys->i_attachment, p_sys->attachment, p_attachment );
2717     free( psz_name );
2718
2719 exit:
2720     free( psz_description );
2721
2722     if( p_block )
2723         block_Release( p_block );
2724
2725     if( p_attachment )
2726         msg_Dbg( p_demux, "Loaded an embedded subtitle" );
2727     else
2728         msg_Warn( p_demux, "Failed to load an embedded subtitle" );
2729
2730     if( p_indx == &ck.indx )
2731         AVI_ChunkFree( p_demux->s, &ck );
2732 }
2733 /*****************************************************************************
2734  * Stream management
2735  *****************************************************************************/
2736 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
2737 {
2738     demux_sys_t *p_sys = p_demux->p_sys;
2739     unsigned int i;
2740     int b_end = true;
2741
2742     for( i = 0; i < p_sys->i_track; i++ )
2743     {
2744         avi_track_t *tk = p_sys->track[i];
2745         if( tk->i_idxposc >= tk->idx.i_size )
2746         {
2747             tk->b_eof = true;
2748         }
2749         else
2750         {
2751             b_end = false;
2752         }
2753     }
2754     return( b_end );
2755 }
2756
2757 /****************************************************************************
2758  * AVI_MovieGetLength give max streams length in second
2759  ****************************************************************************/
2760 static mtime_t  AVI_MovieGetLength( demux_t *p_demux )
2761 {
2762     demux_sys_t  *p_sys = p_demux->p_sys;
2763     mtime_t      i_maxlength = 0;
2764     unsigned int i;
2765
2766     for( i = 0; i < p_sys->i_track; i++ )
2767     {
2768         avi_track_t *tk = p_sys->track[i];
2769         mtime_t i_length;
2770
2771         /* fix length for each stream */
2772         if( tk->idx.i_size < 1 || !tk->idx.p_entry )
2773         {
2774             continue;
2775         }
2776
2777         if( tk->i_samplesize )
2778         {
2779             i_length = AVI_GetDPTS( tk,
2780                                     tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal +
2781                                         tk->idx.p_entry[tk->idx.i_size-1].i_length );
2782         }
2783         else
2784         {
2785             i_length = AVI_GetDPTS( tk, tk->idx.i_size );
2786         }
2787         i_length /= (mtime_t)1000000;    /* in seconds */
2788
2789         msg_Dbg( p_demux,
2790                  "stream[%d] length:%"PRId64" (based on index)",
2791                  i,
2792                  i_length );
2793         i_maxlength = __MAX( i_maxlength, i_length );
2794     }
2795
2796     return i_maxlength;
2797 }