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