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