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