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