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