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