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