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