demux: avi: initialize bool
[vlc.git] / modules / demux / avi / avi.c
1 /*****************************************************************************
2  * avi.c : AVI file Stream input module for vlc
3  *****************************************************************************
4  * Copyright (C) 2001-2009 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify it
10  * under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation; either version 2.1 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17  * GNU Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with this program; if not, write to the Free Software Foundation,
21  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27
28 #ifdef HAVE_CONFIG_H
29 # include "config.h"
30 #endif
31 #include <assert.h>
32 #include <ctype.h>
33 #include <limits.h>
34
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_demux.h>
38 #include <vlc_input.h>
39
40 #include <vlc_dialog.h>
41
42 #include <vlc_meta.h>
43 #include <vlc_codecs.h>
44 #include <vlc_charset.h>
45 #include <vlc_memory.h>
46
47 #include "libavi.h"
48 #include "../rawdv.h"
49
50 /*****************************************************************************
51  * Module descriptor
52  *****************************************************************************/
53
54 #define INTERLEAVE_TEXT N_("Force interleaved method" )
55
56 #define INDEX_TEXT N_("Force index creation")
57 #define INDEX_LONGTEXT N_( \
58     "Recreate a index for the AVI file. Use this if your AVI file is damaged "\
59     "or incomplete (not seekable)." )
60
61 #define BI_RAWRGB 0x00
62 #define BI_RGBBITFIELDS 0x03
63
64 static int  Open ( vlc_object_t * );
65 static void Close( vlc_object_t * );
66
67 static const int pi_index[] = {0,1,2,3};
68
69 static const char *const ppsz_indexes[] = { N_("Ask for action"),
70                                             N_("Always fix"),
71                                             N_("Never fix"),
72                                             N_("Fix when necessary")};
73
74 vlc_module_begin ()
75     set_shortname( "AVI" )
76     set_description( N_("AVI demuxer") )
77     set_capability( "demux", 212 )
78     set_category( CAT_INPUT )
79     set_subcategory( SUBCAT_INPUT_DEMUX )
80
81     add_bool( "avi-interleaved", false,
82               INTERLEAVE_TEXT, INTERLEAVE_TEXT, true )
83     add_integer( "avi-index", 0,
84               INDEX_TEXT, INDEX_LONGTEXT, false )
85         change_integer_list( pi_index, ppsz_indexes )
86
87     set_callbacks( Open, Close )
88 vlc_module_end ()
89
90 /*****************************************************************************
91  * Local prototypes
92  *****************************************************************************/
93 static int Control         ( demux_t *, int, va_list );
94 static int Seek            ( demux_t *, mtime_t, int );
95 static int Demux_Seekable  ( demux_t * );
96 static int Demux_UnSeekable( demux_t * );
97
98 static char *FromACP( const char *str )
99 {
100     return FromCharset(vlc_pgettext("GetACP", "CP1252"), str, strlen(str));
101 }
102
103 #define IGNORE_ES NAV_ES
104 #define READ_LENGTH (25 * 1000) // 25ms
105 #define READ_LENGTH_NONINTERLEAVED (CLOCK_FREQ * 3 / 2)
106
107 //#define AVI_DEBUG
108
109 typedef struct
110 {
111     vlc_fourcc_t i_fourcc;
112     off_t        i_pos;
113     uint32_t     i_size;
114     vlc_fourcc_t i_type;     /* only for AVIFOURCC_LIST */
115
116     uint8_t      i_peek[8];  /* first 8 bytes */
117
118     unsigned int i_stream;
119     enum es_format_category_e i_cat;
120 } avi_packet_t;
121
122
123 typedef struct
124 {
125     vlc_fourcc_t i_id;
126     uint32_t     i_flags;
127     off_t        i_pos;
128     uint32_t     i_length;
129     int64_t      i_lengthtotal;
130
131 } avi_entry_t;
132
133 typedef struct
134 {
135     unsigned int    i_size;
136     unsigned int    i_max;
137     avi_entry_t     *p_entry;
138
139 } avi_index_t;
140 static void avi_index_Init( avi_index_t * );
141 static void avi_index_Clean( avi_index_t * );
142 static void avi_index_Append( avi_index_t *, off_t *, avi_entry_t * );
143
144 typedef struct
145 {
146     bool            b_activated;
147     bool            b_eof;
148
149     unsigned int    i_rate;
150     unsigned int    i_scale;
151     unsigned int    i_samplesize;
152
153     unsigned int    i_width_bytes;
154     bool            b_flipped;
155
156     es_format_t     fmt;
157     es_out_id_t     *p_es;
158
159     int             i_dv_audio_rate;
160     es_out_id_t     *p_es_dv_audio;
161
162     /* Avi Index */
163     avi_index_t     idx;
164
165     unsigned int    i_idxposc;  /* numero of chunk */
166     unsigned int    i_idxposb;  /* byte in the current chunk */
167
168     /* For VBR audio only */
169     unsigned int    i_blockno;
170     unsigned int    i_blocksize;
171
172 } avi_track_t;
173
174 struct demux_sys_t
175 {
176     mtime_t i_time;
177     mtime_t i_length;
178
179     bool  b_interleaved;
180     bool  b_seekable;
181     bool  b_fastseekable;
182     bool  b_indexloaded; /* if we read indexes from end of file before starting */
183     mtime_t i_read_increment;
184     uint32_t i_avih_flags;
185     avi_chunk_t ck_root;
186
187     bool  b_odml;
188
189     off_t   i_movi_begin;
190     off_t   i_movi_lastchunk_pos;   /* XXX position of last valid chunk */
191
192     /* number of streams and information */
193     unsigned int i_track;
194     avi_track_t  **track;
195
196     /* meta */
197     vlc_meta_t  *meta;
198
199     unsigned int       i_attachment;
200     input_attachment_t **attachment;
201 };
202
203 static inline off_t __EVEN( off_t i )
204 {
205     return (i & 1) ? i + 1 : i;
206 }
207
208 static mtime_t AVI_PTSToChunk( avi_track_t *, mtime_t i_pts );
209 static mtime_t AVI_PTSToByte ( avi_track_t *, mtime_t i_pts );
210 static mtime_t AVI_GetDPTS   ( avi_track_t *, int64_t i_count );
211 static mtime_t AVI_GetPTS    ( avi_track_t * );
212
213
214 static int AVI_StreamChunkFind( demux_t *, unsigned int i_stream );
215 static int AVI_StreamChunkSet ( demux_t *,
216                                 unsigned int i_stream, unsigned int i_ck );
217 static int AVI_StreamBytesSet ( demux_t *,
218                                 unsigned int i_stream, off_t   i_byte );
219
220 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t );
221 static int   AVI_GetKeyFlag    ( vlc_fourcc_t , uint8_t * );
222
223 static int AVI_PacketGetHeader( demux_t *, avi_packet_t *p_pk );
224 static int AVI_PacketNext     ( demux_t * );
225 static int AVI_PacketSearch   ( demux_t * );
226
227 static void AVI_IndexLoad    ( demux_t * );
228 static void AVI_IndexCreate  ( demux_t * );
229
230 static void AVI_ExtractSubtitle( demux_t *, unsigned int i_stream, avi_chunk_list_t *, avi_chunk_STRING_t * );
231
232 static void AVI_DvHandleAudio( demux_t *, avi_track_t *, block_t * );
233
234 static mtime_t  AVI_MovieGetLength( demux_t * );
235
236 static void AVI_MetaLoad( demux_t *, avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih );
237
238 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
239                      const int i_header, const int i_size );
240
241 /*****************************************************************************
242  * Stream management
243  *****************************************************************************/
244 static int        AVI_TrackSeek  ( demux_t *, int, mtime_t );
245 static int        AVI_TrackStopFinishedStreams( demux_t *);
246
247 /* Remarks:
248  - For VBR mp3 stream:
249     count blocks by rounded-up chunksizes instead of chunks
250     we need full emulation of dshow avi demuxer bugs :(
251     fixes silly nandub-style a-v delaying in avi with vbr mp3...
252     (from mplayer 2002/08/02)
253  - to complete....
254  */
255
256 /*****************************************************************************
257  * Open: check file and initializes AVI structures
258  *****************************************************************************/
259 static int Open( vlc_object_t * p_this )
260 {
261     demux_t  *p_demux = (demux_t *)p_this;
262     demux_sys_t     *p_sys;
263
264     bool       b_index = false, b_aborted = false;
265     int              i_do_index;
266
267     avi_chunk_list_t    *p_riff;
268     avi_chunk_list_t    *p_hdrl, *p_movi;
269     avi_chunk_avih_t    *p_avih;
270
271     unsigned int i_track;
272     unsigned int i_peeker;
273
274     const uint8_t *p_peek;
275
276     /* Is it an avi file ? */
277     if( vlc_stream_Peek( p_demux->s, &p_peek, 200 ) < 200 )
278         return VLC_EGENERIC;
279
280     for( i_peeker = 0; i_peeker < 188; i_peeker++ )
281     {
282         if( !strncmp( (char *)&p_peek[0], "RIFF", 4 ) && !strncmp( (char *)&p_peek[8], "AVI ", 4 ) )
283             break;
284         if( !strncmp( (char *)&p_peek[0], "ON2 ", 4 ) && !strncmp( (char *)&p_peek[8], "ON2f", 4 ) )
285             break;
286         p_peek++;
287     }
288     if( i_peeker == 188 )
289     {
290         return VLC_EGENERIC;
291     }
292
293     if( i_peeker > 0
294      && vlc_stream_Read( p_demux->s, NULL, i_peeker ) < i_peeker )
295         return VLC_EGENERIC;
296
297     /* Initialize input structures. */
298     p_sys = p_demux->p_sys = calloc( 1, sizeof(demux_sys_t) );
299     if( unlikely(!p_sys) )
300         return VLC_EGENERIC;
301     p_sys->b_odml   = false;
302     p_sys->track    = NULL;
303     p_sys->meta     = NULL;
304     TAB_INIT(p_sys->i_attachment, p_sys->attachment);
305
306     vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK,
307                         &p_sys->b_fastseekable );
308     vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
309
310     p_demux->pf_control = Control;
311     p_demux->pf_demux = (p_sys->b_seekable) ? Demux_Seekable : Demux_UnSeekable;
312
313     p_sys->b_interleaved = var_InheritBool( p_demux, "avi-interleaved" );
314
315     if( AVI_ChunkReadRoot( p_demux->s, &p_sys->ck_root ) )
316     {
317         msg_Err( p_demux, "avi module discarded (invalid file)" );
318         free(p_sys);
319         return VLC_EGENERIC;
320     }
321
322     if( AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF ) > 1 )
323     {
324         unsigned int i_count =
325             AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF );
326
327         msg_Warn( p_demux, "multiple riff -> OpenDML ?" );
328         for( unsigned i = 1; i < i_count; i++ )
329         {
330             avi_chunk_list_t *p_sysx;
331
332             p_sysx = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, i );
333             if( p_sysx->i_type == AVIFOURCC_AVIX )
334             {
335                 msg_Warn( p_demux, "detected OpenDML file" );
336                 p_sys->b_odml = true;
337                 break;
338             }
339         }
340     }
341
342     p_riff  = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
343     p_hdrl  = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
344     p_movi  = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0 );
345     if( !p_movi )
346         p_movi  = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_movi, 0 );
347
348     if( !p_hdrl || !p_movi )
349     {
350         msg_Err( p_demux, "invalid file: cannot find hdrl or movi chunks" );
351         goto error;
352     }
353
354     if( !( p_avih = AVI_ChunkFind( p_hdrl, AVIFOURCC_avih, 0 ) ) )
355     {
356         msg_Err( p_demux, "invalid file: cannot find avih chunk" );
357         goto error;
358     }
359     i_track = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
360     if( p_avih->i_streams != i_track )
361     {
362         msg_Warn( p_demux,
363                   "found %d stream but %d are declared",
364                   i_track, p_avih->i_streams );
365     }
366     if( i_track == 0 )
367     {
368         msg_Err( p_demux, "no stream defined!" );
369         goto error;
370     }
371
372     /* print information on streams */
373     msg_Dbg( p_demux, "AVIH: %d stream, flags %s%s%s%s ",
374              i_track,
375              p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
376              p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
377              p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
378              p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
379
380     p_sys->b_interleaved |= (p_avih->i_flags & AVIF_ISINTERLEAVED);
381
382     if( p_sys->b_interleaved && !p_sys->b_fastseekable )
383         p_sys->i_read_increment = READ_LENGTH;
384     else
385         p_sys->i_read_increment = READ_LENGTH_NONINTERLEAVED;
386     /* non seekable and non interleaved case ? well... */
387
388     AVI_MetaLoad( p_demux, p_riff, p_avih );
389     p_sys->i_avih_flags = p_avih->i_flags;
390
391     /* now read info on each stream and create ES */
392     for( unsigned i = 0 ; i < i_track; i++ )
393     {
394         avi_track_t           *tk     = calloc( 1, sizeof( avi_track_t ) );
395         if( unlikely( !tk ) )
396             goto error;
397
398         avi_chunk_list_t      *p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
399         avi_chunk_strh_t      *p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
400         avi_chunk_STRING_t    *p_strn = AVI_ChunkFind( p_strl, AVIFOURCC_strn, 0 );
401         avi_chunk_strf_auds_t *p_auds = NULL;
402         avi_chunk_strf_vids_t *p_vids = NULL;
403
404         tk->b_eof = false;
405         tk->b_activated = true;
406
407         p_vids = (avi_chunk_strf_vids_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
408         p_auds = (avi_chunk_strf_auds_t*)p_vids;
409
410         if( p_strl == NULL || p_strh == NULL || p_vids == NULL )
411         {
412             msg_Warn( p_demux, "stream[%d] incomplete", i );
413             free( tk );
414             continue;
415         }
416
417         tk->i_rate  = p_strh->i_rate;
418         tk->i_scale = p_strh->i_scale;
419         tk->i_samplesize = p_strh->i_samplesize;
420         msg_Dbg( p_demux, "stream[%u] rate:%u scale:%u samplesize:%u",
421                 i, tk->i_rate, tk->i_scale, tk->i_samplesize );
422
423         switch( p_strh->i_type )
424         {
425             case( AVIFOURCC_auds ):
426             {
427                 es_format_Init( &tk->fmt, AUDIO_ES, 0 );
428
429                 if( p_auds->p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
430                     p_auds->p_wf->cbSize >= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) )
431                 {
432                     WAVEFORMATEXTENSIBLE *p_wfe = (WAVEFORMATEXTENSIBLE *)p_auds->p_wf;
433                     tk->fmt.i_codec = AVI_FourccGetCodec( AUDIO_ES, p_wfe->SubFormat.Data1 );
434                 }
435                 else
436                     tk->fmt.i_codec = AVI_FourccGetCodec( AUDIO_ES, p_auds->p_wf->wFormatTag );
437
438                 tk->i_blocksize = p_auds->p_wf->nBlockAlign;
439                 if( tk->i_blocksize == 0 )
440                 {
441                     if( p_auds->p_wf->wFormatTag == 1 )
442                         tk->i_blocksize = p_auds->p_wf->nChannels * (p_auds->p_wf->wBitsPerSample/8);
443                     else
444                         tk->i_blocksize = 1;
445                 }
446                 else if( tk->i_samplesize != 0 && tk->i_samplesize != tk->i_blocksize )
447                 {
448                     msg_Warn( p_demux, "track[%u] samplesize=%u and blocksize=%u are not equal."
449                                        "Using blocksize as a workaround.",
450                                        i, tk->i_samplesize, tk->i_blocksize );
451                     tk->i_samplesize = tk->i_blocksize;
452                 }
453
454                 if( tk->fmt.i_codec == VLC_CODEC_VORBIS )
455                 {
456                     tk->i_blocksize = 0; /* fix vorbis VBR decoding */
457                 }
458
459                 if ( tk->fmt.i_codec == VLC_CODEC_MP4A )
460                 {
461                     tk->i_samplesize = 0; /* ADTS/AAC VBR */
462                 }
463
464                 /* Fix broken scale/rate */
465                 if ( tk->fmt.i_codec == VLC_CODEC_ADPCM_IMA_WAV &&
466                      tk->i_samplesize && tk->i_samplesize > tk->i_rate )
467                 {
468                     tk->i_scale = 1017;
469                     tk->i_rate = p_auds->p_wf->nSamplesPerSec;
470                 }
471
472                 /* From libavformat */
473                 /* Fix broken sample size (which is mp2 num samples / frame) #12722 */
474                 if( tk->fmt.i_codec == VLC_CODEC_MPGA &&
475                     tk->i_samplesize == 1152 && p_auds->p_wf->nBlockAlign == 1152 )
476                 {
477                     p_auds->p_wf->nBlockAlign = tk->i_samplesize = 0;
478                 }
479
480                 tk->fmt.audio.i_channels        = p_auds->p_wf->nChannels;
481                 tk->fmt.audio.i_rate            = p_auds->p_wf->nSamplesPerSec;
482                 tk->fmt.i_bitrate               = p_auds->p_wf->nAvgBytesPerSec*8;
483                 tk->fmt.audio.i_blockalign      = p_auds->p_wf->nBlockAlign;
484                 tk->fmt.audio.i_bitspersample   = p_auds->p_wf->wBitsPerSample;
485                 tk->fmt.b_packetized            = !tk->i_blocksize;
486
487                 avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
488                 if( p_info )
489                 {
490                     int i_chunk = AVIFOURCC_IAS1 + ((i - 1) << 24);
491                     avi_chunk_STRING_t *p_lang = AVI_ChunkFind( p_info, i_chunk, 0 );
492                     if( p_lang != NULL && p_lang->p_str != NULL )
493                         tk->fmt.psz_language = FromACP( p_lang->p_str );
494                 }
495
496                 msg_Dbg( p_demux,
497                     "stream[%u] audio(0x%x - %s) %d channels %dHz %dbits",
498                     i, p_auds->p_wf->wFormatTag,
499                     vlc_fourcc_GetDescription(AUDIO_ES, tk->fmt.i_codec),
500                     p_auds->p_wf->nChannels,
501                     p_auds->p_wf->nSamplesPerSec,
502                     p_auds->p_wf->wBitsPerSample );
503
504                 if( p_auds->p_wf->cbSize > 0 && p_auds->i_chunk_size > sizeof(WAVEFORMATEX) )
505                 {
506                     int i_extra = __MIN( p_auds->p_wf->cbSize,
507                                          p_auds->i_chunk_size - sizeof(WAVEFORMATEX) );
508                     tk->fmt.p_extra = malloc( i_extra );
509                     if( unlikely(tk->fmt.p_extra == NULL) )
510                     {
511                         es_format_Clean( &tk->fmt );
512                         free( tk );
513                         goto error;
514                     }
515                     tk->fmt.i_extra = i_extra;
516                     memcpy( tk->fmt.p_extra, &p_auds->p_wf[1], tk->fmt.i_extra );
517                 }
518                 break;
519             }
520
521             case( AVIFOURCC_vids ):
522             {
523                 if( p_vids->p_bih->biCompression == VLC_FOURCC( 'D', 'X', 'S', 'B' ) )
524                 {
525                    msg_Dbg( p_demux, "stream[%u] subtitles", i );
526                    es_format_Init( &tk->fmt, SPU_ES, p_vids->p_bih->biCompression );
527                    break;
528                 }
529
530                 es_format_Init( &tk->fmt, VIDEO_ES,
531                         AVI_FourccGetCodec( VIDEO_ES, p_vids->p_bih->biCompression ) );
532
533                 if( p_vids->p_bih->biCompression == BI_RAWRGB )
534                 {
535                     switch( p_vids->p_bih->biBitCount )
536                     {
537                         case 32:
538                             tk->fmt.i_codec = VLC_CODEC_RGB32;
539                             break;
540                         case 24:
541                             tk->fmt.i_codec = VLC_CODEC_RGB24;
542                             break;
543                         case 16: /* Yes it is RV15 */
544                         case 15:
545                             tk->fmt.i_codec = VLC_CODEC_RGB15;
546                             break;
547                         case 9: /* <- TODO check that */
548                             tk->fmt.i_codec = VLC_CODEC_I410;
549                             break;
550                         case 8:
551                             if ( p_vids->p_bih->biClrUsed )
552                                 tk->fmt.i_codec = VLC_CODEC_RGBP;
553                             else
554                                 tk->fmt.i_codec = VLC_CODEC_GREY;
555                             break;
556                     }
557
558                     switch( tk->fmt.i_codec )
559                     {
560                     case VLC_CODEC_RGB24:
561                     case VLC_CODEC_RGB32:
562                         tk->fmt.video.i_rmask = 0x00ff0000;
563                         tk->fmt.video.i_gmask = 0x0000ff00;
564                         tk->fmt.video.i_bmask = 0x000000ff;
565                         break;
566                     case VLC_CODEC_RGB15:
567                         tk->fmt.video.i_rmask = 0x7c00;
568                         tk->fmt.video.i_gmask = 0x03e0;
569                         tk->fmt.video.i_bmask = 0x001f;
570                         break;
571                     case VLC_CODEC_RGBP:
572                     {
573                         const VLC_BITMAPINFO *p_bi = (const VLC_BITMAPINFO *) p_vids->p_bih;
574                         tk->fmt.video.p_palette = malloc( sizeof(video_palette_t) );
575                         if ( tk->fmt.video.p_palette )
576                         {
577                             uint32_t entry;
578                             for( uint32_t j = 0; j < p_vids->p_bih->biClrUsed; j++ )
579                             {
580                                  entry = GetDWBE( &p_bi->bmiColors[j] );
581                                  tk->fmt.video.p_palette->palette[j][0] = entry >> 24;
582                                  tk->fmt.video.p_palette->palette[j][1] = (entry >> 16) & 0xFF;
583                                  tk->fmt.video.p_palette->palette[j][2] = (entry >> 8) & 0xFF;
584                                  tk->fmt.video.p_palette->palette[j][3] = entry & 0xFF;
585                             }
586                             tk->fmt.video.p_palette->i_entries = p_vids->p_bih->biClrUsed;
587                         }
588                     }
589                         break;
590                     default:
591                         break;
592                     }
593
594                     tk->i_width_bytes = p_vids->p_bih->biWidth * (p_vids->p_bih->biBitCount >> 3);
595                     /* RGB DIB are coded from bottom to top */
596                     if ( p_vids->p_bih->biHeight < INT32_MAX ) tk->b_flipped = true;
597                 }
598                 else
599                 {
600                     tk->fmt.i_codec = p_vids->p_bih->biCompression;
601                     if( tk->fmt.i_codec == VLC_CODEC_MP4V &&
602                         !strncasecmp( (char*)&p_strh->i_handler, "XVID", 4 ) )
603                     {
604                         tk->fmt.i_codec           =
605                         tk->fmt.i_original_fourcc = VLC_FOURCC( 'X', 'V', 'I', 'D' );
606                     }
607                 }
608                 tk->i_samplesize = 0;
609
610                 tk->fmt.video.i_visible_width =
611                 tk->fmt.video.i_width  = p_vids->p_bih->biWidth;
612                 tk->fmt.video.i_visible_height =
613                 tk->fmt.video.i_height = p_vids->p_bih->biHeight;
614                 tk->fmt.video.i_bits_per_pixel = p_vids->p_bih->biBitCount;
615                 tk->fmt.video.i_frame_rate = tk->i_rate;
616                 tk->fmt.video.i_frame_rate_base = tk->i_scale;
617
618                  /* Uncompresse Bitmap or YUV, YUV being always topdown */
619                 if ( tk->fmt.video.i_height > INT32_MAX )
620                     tk->fmt.video.i_height =
621                         (unsigned int)(-(int)p_vids->p_bih->biHeight);
622
623                 avi_chunk_vprp_t *p_vprp = AVI_ChunkFind( p_strl, AVIFOURCC_vprp, 0 );
624                 if( p_vprp )
625                 {
626                     uint32_t i_frame_aspect_ratio = p_vprp->i_frame_aspect_ratio;
627                     if( p_vprp->i_video_format_token >= 1 &&
628                         p_vprp->i_video_format_token <= 4 )
629                         i_frame_aspect_ratio = 0x00040003;
630                     tk->fmt.video.i_sar_num = ((i_frame_aspect_ratio >> 16) & 0xffff) *
631                                               tk->fmt.video.i_height;
632                     tk->fmt.video.i_sar_den = ((i_frame_aspect_ratio >>  0) & 0xffff) *
633                                               tk->fmt.video.i_width;
634                 }
635                 /* Extradata is the remainder of the chunk less the BIH */
636                 if( p_vids->i_chunk_size <= INT_MAX - sizeof(VLC_BITMAPINFOHEADER) )
637                 {
638                     int i_extra = p_vids->i_chunk_size - sizeof(VLC_BITMAPINFOHEADER);
639                     if( i_extra > 0 )
640                     {
641                         tk->fmt.p_extra = malloc( i_extra );
642                         if( unlikely(tk->fmt.p_extra == NULL) )
643                         {
644                             es_format_Clean( &tk->fmt );
645                             free( tk );
646                             goto error;
647                         }
648                         tk->fmt.i_extra = i_extra;
649                         memcpy( tk->fmt.p_extra, &p_vids->p_bih[1], tk->fmt.i_extra );
650                     }
651                 }
652
653                 msg_Dbg( p_demux, "stream[%u] video(%4.4s) %"PRIu32"x%"PRIu32" %dbpp %ffps",
654                          i, (char*)&p_vids->p_bih->biCompression,
655                          (uint32_t)p_vids->p_bih->biWidth,
656                          (uint32_t)p_vids->p_bih->biHeight,
657                          p_vids->p_bih->biBitCount,
658                          (float)tk->i_rate/(float)tk->i_scale );
659
660                 /* Extract palette from extradata if bpp <= 8 */
661                 if( tk->fmt.video.i_bits_per_pixel > 0 && tk->fmt.video.i_bits_per_pixel <= 8 )
662                 {
663                     /* The palette should not be included in biSize, but come
664                      * directly after BITMAPINFORHEADER in the BITMAPINFO structure */
665                     if( tk->fmt.i_extra > 0 )
666                     {
667                         tk->fmt.video.p_palette = calloc( 1, sizeof(video_palette_t) );
668                         if( likely(tk->fmt.video.p_palette) )
669                         {
670                             const uint8_t *p_pal = tk->fmt.p_extra;
671                             tk->fmt.video.p_palette->i_entries = __MIN(tk->fmt.i_extra/4, 256);
672                             for( int k = 0; k < tk->fmt.video.p_palette->i_entries; k++ )
673                             {
674                                 for( int j = 0; j < 4; j++ )
675                                     tk->fmt.video.p_palette->palette[k][j] = p_pal[4*k+j];
676                             }
677                         }
678                     }
679                 }
680                 break;
681             }
682
683             case( AVIFOURCC_txts):
684                 msg_Dbg( p_demux, "stream[%u] subtitle attachment", i );
685                 AVI_ExtractSubtitle( p_demux, i, p_strl, p_strn );
686                 free( tk );
687                 continue;
688
689             case( AVIFOURCC_iavs):
690             case( AVIFOURCC_ivas):
691                 msg_Dbg( p_demux, "stream[%u] iavs with handler %4.4s", i, (char *)&p_strh->i_handler );
692                 es_format_Init( &tk->fmt, VIDEO_ES, p_strh->i_handler );
693                 tk->i_samplesize = 0;
694                 tk->i_dv_audio_rate = p_strh->i_handler == VLC_CODEC_DV ? -1 : 0;
695
696                 tk->fmt.video.i_visible_width =
697                 tk->fmt.video.i_width  = p_avih->i_width;
698                 tk->fmt.video.i_visible_height =
699                 tk->fmt.video.i_height = p_avih->i_height;
700                 break;
701
702             case( AVIFOURCC_mids):
703                 msg_Dbg( p_demux, "stream[%u] midi is UNSUPPORTED", i );
704
705             default:
706                 msg_Warn( p_demux, "stream[%u] unknown type %4.4s", i, (char *)&p_strh->i_type );
707                 free( tk );
708                 continue;
709         }
710         if( p_strn && p_strn->p_str )
711             tk->fmt.psz_description = FromACP( p_strn->p_str );
712         tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
713         TAB_APPEND( p_sys->i_track, p_sys->track, tk );
714     }
715
716     if( p_sys->i_track <= 0 )
717     {
718         msg_Err( p_demux, "no valid track" );
719         goto error;
720     }
721
722     i_do_index = var_InheritInteger( p_demux, "avi-index" );
723     if( i_do_index == 1 ) /* Always fix */
724     {
725 aviindex:
726         if( p_sys->b_fastseekable )
727         {
728             AVI_IndexCreate( p_demux );
729         }
730         else if( p_sys->b_seekable )
731         {
732             AVI_IndexLoad( p_demux );
733         }
734         else
735         {
736             msg_Warn( p_demux, "cannot create index (unseekable stream)" );
737         }
738     }
739     else if( p_sys->b_seekable )
740     {
741         AVI_IndexLoad( p_demux );
742     }
743
744     /* *** movie length in sec *** */
745     p_sys->i_length = AVI_MovieGetLength( p_demux );
746
747     /* Check the index completeness */
748     unsigned int i_idx_totalframes = 0;
749     for( unsigned int i = 0; i < p_sys->i_track; i++ )
750     {
751         const avi_track_t *tk = p_sys->track[i];
752         if( tk->fmt.i_cat == VIDEO_ES && tk->idx.p_entry )
753             i_idx_totalframes = __MAX(i_idx_totalframes, tk->idx.i_size);
754     }
755     if( i_idx_totalframes != p_avih->i_totalframes &&
756         p_sys->i_length < (mtime_t)p_avih->i_totalframes *
757                           (mtime_t)p_avih->i_microsecperframe /
758                           CLOCK_FREQ )
759     {
760         msg_Warn( p_demux, "broken or missing index, 'seek' will be "
761                            "approximative or will exhibit strange behavior" );
762         if( (i_do_index == 0 || i_do_index == 3) && !b_index )
763         {
764             if( !p_sys->b_fastseekable ) {
765                 b_index = true;
766                 goto aviindex;
767             }
768             if( i_do_index == 0 )
769             {
770                 const char *psz_msg = _(
771                     "Because this file index is broken or missing, "
772                     "seeking will not work correctly.\n"
773                     "VLC won't repair your file but can temporary fix this "
774                     "problem by building an index in memory.\n"
775                     "This step might take a long time on a large file.\n"
776                     "What do you want to do?");
777                 switch( vlc_dialog_wait_question( p_demux,
778                                                   VLC_DIALOG_QUESTION_NORMAL,
779                                                   _("Do not play"),
780                                                   _("Build index then play"),
781                                                   _("Play as is"),
782                                                   _("Broken or missing Index"),
783                                                   "%s", psz_msg ) )
784                 {
785                     case 0:
786                         b_aborted = true;
787                         goto error;
788                     case 1:
789                         b_index = true;
790                         msg_Dbg( p_demux, "Fixing AVI index" );
791                         goto aviindex;
792                 }
793             }
794             else
795             {
796                 b_index = true;
797                 msg_Dbg( p_demux, "Fixing AVI index" );
798                 goto aviindex;
799             }
800         }
801     }
802
803     /* fix some BeOS MediaKit generated file */
804     for( unsigned i = 0 ; i < p_sys->i_track; i++ )
805     {
806         avi_track_t         *tk = p_sys->track[i];
807         avi_chunk_list_t    *p_strl;
808         avi_chunk_strf_auds_t    *p_auds;
809
810         if( tk->fmt.i_cat != AUDIO_ES )
811         {
812             continue;
813         }
814         if( tk->idx.i_size < 1 ||
815             tk->i_scale != 1 ||
816             tk->i_samplesize != 0 )
817         {
818             continue;
819         }
820         p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
821         p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
822
823         if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
824             tk->i_rate == p_auds->p_wf->nSamplesPerSec )
825         {
826             int64_t i_track_length =
827                 tk->idx.p_entry[tk->idx.i_size-1].i_length +
828                 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal;
829             mtime_t i_length = (mtime_t)p_avih->i_totalframes *
830                                (mtime_t)p_avih->i_microsecperframe;
831
832             if( i_length == 0 )
833             {
834                 msg_Warn( p_demux, "track[%u] cannot be fixed (BeOS MediaKit generated)", i );
835                 continue;
836             }
837             tk->i_samplesize = 1;
838             tk->i_rate       = i_track_length  * CLOCK_FREQ / i_length;
839             msg_Warn( p_demux, "track[%u] fixed with rate=%u scale=%u (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
840         }
841     }
842
843     if( p_sys->b_seekable )
844     {
845         /* we have read all chunk so go back to movi */
846         if( vlc_stream_Seek( p_demux->s, p_movi->i_chunk_pos ) )
847             goto error;
848     }
849     /* Skip movi header */
850     if( vlc_stream_Read( p_demux->s, NULL, 12 ) < 12 )
851         goto error;
852
853     p_sys->i_movi_begin = p_movi->i_chunk_pos;
854     return VLC_SUCCESS;
855
856 error:
857     for( unsigned i = 0; i < p_sys->i_attachment; i++)
858         vlc_input_attachment_Delete(p_sys->attachment[i]);
859     free(p_sys->attachment);
860
861     if( p_sys->meta )
862         vlc_meta_Delete( p_sys->meta );
863
864     AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
865     free( p_sys );
866     return b_aborted ? VLC_ETIMEOUT : VLC_EGENERIC;
867 }
868
869 /*****************************************************************************
870  * Close: frees unused data
871  *****************************************************************************/
872 static void Close ( vlc_object_t * p_this )
873 {
874     demux_t *    p_demux = (demux_t *)p_this;
875     demux_sys_t *p_sys = p_demux->p_sys  ;
876
877     for( unsigned int i = 0; i < p_sys->i_track; i++ )
878     {
879         if( p_sys->track[i] )
880         {
881             es_format_Clean( &p_sys->track[i]->fmt );
882             avi_index_Clean( &p_sys->track[i]->idx );
883             free( p_sys->track[i] );
884         }
885     }
886     free( p_sys->track );
887
888     AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
889     vlc_meta_Delete( p_sys->meta );
890
891     for( unsigned i = 0; i < p_sys->i_attachment; i++)
892         vlc_input_attachment_Delete(p_sys->attachment[i]);
893     free(p_sys->attachment);
894
895     free( p_sys );
896 }
897
898 /*****************************************************************************
899  * ReadFrame: Reads frame, using stride if necessary
900  *****************************************************************************/
901
902 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
903                      const int i_header, const int i_size )
904 {
905     block_t *p_frame = vlc_stream_Block( p_demux->s, __EVEN( i_size ) );
906     if ( !p_frame ) return p_frame;
907
908     if( i_size % 2 )    /* read was padded on word boundary */
909     {
910         p_frame->i_buffer--;
911     }
912
913     /* skip header */
914     p_frame->p_buffer += i_header;
915     p_frame->i_buffer -= i_header;
916
917     if ( !tk->i_width_bytes )
918         return p_frame;
919
920     const unsigned int i_stride_bytes = ((( (tk->i_width_bytes << 3) + 31) & ~31) >> 3);
921
922     if ( p_frame->i_buffer < i_stride_bytes )
923     {
924         p_frame->i_buffer = 0;
925         return p_frame;
926     }
927
928     if( !tk->b_flipped )
929     {
930         const uint8_t *p_src = p_frame->p_buffer + i_stride_bytes;
931         const uint8_t *p_end = p_frame->p_buffer + p_frame->i_buffer;
932         uint8_t *p_dst = p_frame->p_buffer + tk->i_width_bytes;
933
934         p_frame->i_buffer = tk->i_width_bytes;
935
936         while ( p_src + i_stride_bytes <= p_end )
937         {
938             memmove( p_dst, p_src, tk->i_width_bytes );
939             p_src += i_stride_bytes;
940             p_dst += tk->i_width_bytes;
941             p_frame->i_buffer += tk->i_width_bytes;
942         }
943     }
944     else
945     {
946         block_t *p_flippedframe = block_Alloc( p_frame->i_buffer );
947         if ( !p_flippedframe )
948         {
949             block_Release( p_frame );
950             return NULL;
951         }
952
953         unsigned int i_lines = p_frame->i_buffer / i_stride_bytes;
954         const uint8_t *p_src = p_frame->p_buffer + i_lines * i_stride_bytes;
955         uint8_t *p_dst = p_flippedframe->p_buffer;
956
957         p_flippedframe->i_buffer = 0;
958
959         while ( i_lines-- > 0 )
960         {
961             p_src -= i_stride_bytes;
962             memcpy( p_dst, p_src, tk->i_width_bytes );
963             p_dst += tk->i_width_bytes;
964             p_flippedframe->i_buffer += tk->i_width_bytes;
965         }
966
967         block_Release( p_frame );
968         p_frame = p_flippedframe;
969     }
970
971     return p_frame;
972 }
973
974 /*****************************************************************************
975  * Demux_Seekable: reads and demuxes data packets for stream seekable
976  *****************************************************************************
977  * AVIDemux: reads and demuxes data packets
978  *****************************************************************************
979  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
980  *****************************************************************************/
981 typedef struct
982 {
983     bool b_ok;
984
985     int i_toread;
986
987     off_t i_posf; /* where we will read :
988                    if i_idxposb == 0 : begining of chunk (+8 to acces data)
989                    else : point on data directly */
990 } avi_track_toread_t;
991
992 static int Demux_Seekable( demux_t *p_demux )
993 {
994     demux_sys_t *p_sys = p_demux->p_sys;
995
996     unsigned int i_track_count = 0;
997     unsigned int i_track;
998     /* cannot be more than 100 stream (dcXX or wbXX) */
999     avi_track_toread_t toread[100];
1000
1001
1002     /* detect new selected/unselected streams */
1003     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1004     {
1005         avi_track_t *tk = p_sys->track[i_track];
1006         bool  b = false;
1007
1008         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1009         if( tk->p_es_dv_audio )
1010         {
1011             bool b_extra = false;
1012             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1013             b |= b_extra;
1014         }
1015         if( b && !tk->b_activated )
1016         {
1017             if( p_sys->b_seekable)
1018             {
1019                 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
1020             }
1021             tk->b_activated = true;
1022         }
1023         else if( !b && tk->b_activated )
1024         {
1025             tk->b_activated = false;
1026         }
1027         if( b )
1028         {
1029             i_track_count++;
1030         }
1031     }
1032
1033     if( i_track_count <= 0 )
1034     {
1035         int64_t i_length = p_sys->i_length * CLOCK_FREQ;
1036
1037         p_sys->i_time += p_sys->i_read_increment;
1038         if( i_length > 0 )
1039         {
1040             if( p_sys->i_time >= i_length )
1041                 return VLC_DEMUXER_EOF;
1042             return VLC_DEMUXER_SUCCESS;
1043         }
1044         msg_Warn( p_demux, "no track selected, exiting..." );
1045         return VLC_DEMUXER_EOF;
1046     }
1047
1048     /* wait for the good time */
1049     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1050     p_sys->i_time += p_sys->i_read_increment;
1051
1052     /* init toread */
1053     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1054     {
1055         avi_track_t *tk = p_sys->track[i_track];
1056
1057         toread[i_track].b_ok = tk->b_activated && !tk->b_eof;
1058         if( tk->i_idxposc < tk->idx.i_size )
1059         {
1060             toread[i_track].i_posf = tk->idx.p_entry[tk->i_idxposc].i_pos;
1061            if( tk->i_idxposb > 0 )
1062            {
1063                 toread[i_track].i_posf += 8 + tk->i_idxposb;
1064            }
1065         }
1066         else
1067         {
1068             toread[i_track].i_posf = -1;
1069         }
1070
1071         mtime_t i_dpts = p_sys->i_time - AVI_GetPTS( tk );
1072
1073         if( tk->i_samplesize )
1074         {
1075             toread[i_track].i_toread = AVI_PTSToByte( tk, i_dpts );
1076         }
1077         else if ( i_dpts > -2 * CLOCK_FREQ ) /* don't send a too early dts (low fps video) */
1078         {
1079             toread[i_track].i_toread = AVI_PTSToChunk( tk, i_dpts );
1080         }
1081         else
1082             toread[i_track].i_toread = -1;
1083     }
1084
1085     for( ;; )
1086     {
1087         avi_track_t     *tk;
1088         bool       b_done;
1089         block_t         *p_frame;
1090         off_t i_pos;
1091         unsigned int i;
1092         size_t i_size;
1093
1094         /* search for first chunk to be read */
1095         for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
1096         {
1097             if( !toread[i].b_ok ||
1098                 ( p_sys->b_fastseekable && p_sys->b_interleaved &&
1099                   AVI_GetDPTS( p_sys->track[i], toread[i].i_toread ) <= -p_sys->i_read_increment ) )
1100             {
1101                 continue;
1102             }
1103
1104             if( toread[i].i_toread >= 0 )
1105             {
1106                 b_done = false; /* not yet finished */
1107             }
1108             if( toread[i].i_posf > 0 )
1109             {
1110                 if( i_pos == -1 || i_pos > toread[i].i_posf )
1111                 {
1112                     i_track = i;
1113                     i_pos = toread[i].i_posf;
1114                 }
1115             }
1116         }
1117
1118         if( b_done )
1119         {
1120             for( i = 0; i < p_sys->i_track; i++ )
1121             {
1122                 if( toread[i].b_ok )
1123                     return VLC_DEMUXER_SUCCESS;
1124             }
1125             msg_Warn( p_demux, "all tracks have failed, exiting..." );
1126             return VLC_DEMUXER_EOF;
1127         }
1128
1129         if( i_pos == -1 )
1130         {
1131             int i_loop_count = 0;
1132
1133             /* no valid index, we will parse directly the stream
1134              * in case we fail we will disable all finished stream */
1135             if( p_sys->b_seekable && p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1136             {
1137                 vlc_stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1138                 if( AVI_PacketNext( p_demux ) )
1139                 {
1140                     return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1141                 }
1142             }
1143             else
1144             {
1145                 vlc_stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1146             }
1147
1148             for( ;; )
1149             {
1150                 avi_packet_t avi_pk;
1151
1152                 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1153                 {
1154                     msg_Warn( p_demux,
1155                              "cannot get packet header, track disabled" );
1156                     return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1157                 }
1158                 if( avi_pk.i_stream >= p_sys->i_track ||
1159                     ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1160                 {
1161                     if( AVI_PacketNext( p_demux ) )
1162                     {
1163                         msg_Warn( p_demux,
1164                                   "cannot skip packet, track disabled" );
1165                         return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1166                     }
1167
1168                     /* Prevents from eating all the CPU with broken files.
1169                      * This value should be low enough so that it doesn't
1170                      * affect the reading speed too much. */
1171                     if( !(++i_loop_count % 1024) )
1172                     {
1173                         msleep( 10000 );
1174
1175                         if( !(i_loop_count % (1024 * 10)) )
1176                             msg_Warn( p_demux,
1177                                       "don't seem to find any data..." );
1178                     }
1179                     continue;
1180                 }
1181                 else
1182                 {
1183                     i_track = avi_pk.i_stream;
1184                     tk = p_sys->track[i_track];
1185
1186                     /* add this chunk to the index */
1187                     avi_entry_t index;
1188                     index.i_id     = avi_pk.i_fourcc;
1189                     index.i_flags  = AVI_GetKeyFlag(tk->fmt.i_codec, avi_pk.i_peek);
1190                     index.i_pos    = avi_pk.i_pos;
1191                     index.i_length = avi_pk.i_size;
1192                     index.i_lengthtotal = index.i_length;
1193                     avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1194
1195                     /* do we will read this data ? */
1196                     if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -p_sys->i_read_increment )
1197                     {
1198                         break;
1199                     }
1200                     else
1201                     {
1202                         if( AVI_PacketNext( p_demux ) )
1203                         {
1204                             msg_Warn( p_demux,
1205                                       "cannot skip packet, track disabled" );
1206                             return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1207                         }
1208                     }
1209                 }
1210             }
1211
1212         }
1213         else
1214         {
1215             if( !p_sys->b_fastseekable
1216              && (i_pos > vlc_stream_Tell( p_demux->s )) )
1217             {
1218                 vlc_stream_Read( p_demux->s, NULL,
1219                                  i_pos - vlc_stream_Tell( p_demux->s ) );
1220             }
1221             else
1222             {
1223                 vlc_stream_Seek( p_demux->s, i_pos );
1224             }
1225         }
1226
1227         /* Set the track to use */
1228         tk = p_sys->track[i_track];
1229
1230         /* read thoses data */
1231         if( tk->i_samplesize )
1232         {
1233             unsigned int i_toread;
1234
1235             if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1236             {
1237                 if( tk->i_samplesize > 1 )
1238                 {
1239                     i_toread = tk->i_samplesize;
1240                 }
1241                 else
1242                 {
1243                     i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1244                     i_toread = __MAX( i_toread, 100 );
1245                 }
1246             }
1247             i_size = __MIN( tk->idx.p_entry[tk->i_idxposc].i_length -
1248                                 tk->i_idxposb,
1249                             i_toread );
1250         }
1251         else
1252         {
1253             i_size = tk->idx.p_entry[tk->i_idxposc].i_length;
1254         }
1255
1256         if( tk->i_idxposb == 0 )
1257         {
1258             i_size += 8; /* need to read and skip header */
1259         }
1260
1261         if( ( p_frame = ReadFrame( p_demux, tk,
1262                         ( tk->i_idxposb == 0 ) ? 8 : 0, i_size ) )==NULL )
1263         {
1264             msg_Warn( p_demux, "failed reading data" );
1265             tk->b_eof = false;
1266             toread[i_track].b_ok = false;
1267             continue;
1268         }
1269
1270         p_frame->i_pts = VLC_TS_0 + AVI_GetPTS( tk );
1271         if( tk->idx.p_entry[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1272         {
1273             p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1274         }
1275         else
1276         {
1277             p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1278         }
1279
1280         /* read data */
1281         if( tk->i_samplesize )
1282         {
1283             if( tk->i_idxposb == 0 )
1284             {
1285                 i_size -= 8;
1286             }
1287             toread[i_track].i_toread -= i_size;
1288             tk->i_idxposb += i_size;
1289             if( tk->i_idxposb >=
1290                     tk->idx.p_entry[tk->i_idxposc].i_length )
1291             {
1292                 tk->i_idxposb = 0;
1293                 tk->i_idxposc++;
1294             }
1295         }
1296         else
1297         {
1298             int i_length = tk->idx.p_entry[tk->i_idxposc].i_length;
1299
1300             tk->i_idxposc++;
1301             if( tk->fmt.i_cat == AUDIO_ES )
1302             {
1303                 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1304             }
1305             toread[i_track].i_toread--;
1306         }
1307
1308         if( tk->i_idxposc < tk->idx.i_size)
1309         {
1310             toread[i_track].i_posf =
1311                 tk->idx.p_entry[tk->i_idxposc].i_pos;
1312             if( tk->i_idxposb > 0 )
1313             {
1314                 toread[i_track].i_posf += 8 + tk->i_idxposb;
1315             }
1316
1317         }
1318         else
1319         {
1320             toread[i_track].i_posf = -1;
1321         }
1322
1323         if( tk->fmt.i_cat != VIDEO_ES )
1324             p_frame->i_dts = p_frame->i_pts;
1325         else
1326         {
1327             p_frame->i_dts = p_frame->i_pts;
1328             p_frame->i_pts = VLC_TS_INVALID;
1329         }
1330
1331         if( tk->i_dv_audio_rate )
1332             AVI_DvHandleAudio( p_demux, tk, p_frame );
1333
1334         if( tk->p_es )
1335             es_out_Send( p_demux->out, tk->p_es, p_frame );
1336         else
1337             block_Release( p_frame );
1338     }
1339 }
1340
1341
1342 /*****************************************************************************
1343  * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1344  *****************************************************************************
1345  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1346  *****************************************************************************/
1347 static int Demux_UnSeekable( demux_t *p_demux )
1348 {
1349     demux_sys_t     *p_sys = p_demux->p_sys;
1350     avi_track_t *p_stream_master = NULL;
1351     unsigned int i_stream;
1352     unsigned int i_packet;
1353
1354     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1355
1356     /* *** find master stream for data packet skipping algo *** */
1357     /* *** -> first video, if any, or first audio ES *** */
1358     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1359     {
1360         avi_track_t *tk = p_sys->track[i_stream];
1361         bool  b;
1362
1363         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1364         if( tk->p_es_dv_audio )
1365         {
1366             bool b_extra;
1367             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1368             b |= b_extra;
1369         }
1370
1371         if( b )
1372         {
1373             if( tk->fmt.i_cat == VIDEO_ES )
1374             {
1375                 p_stream_master = tk;
1376                 break;
1377             }
1378             else if( !p_stream_master )
1379             {
1380                 p_stream_master = tk;
1381             }
1382         }
1383     }
1384
1385     if( !p_stream_master )
1386     {
1387         if( p_sys->i_track )
1388         {
1389             p_stream_master = p_sys->track[0];
1390         }
1391         else
1392         {
1393             msg_Warn( p_demux, "no more stream selected" );
1394             return VLC_DEMUXER_EOF;
1395         }
1396     }
1397
1398     p_sys->i_time = AVI_GetPTS( p_stream_master );
1399
1400     for( i_packet = 0; i_packet < 10; i_packet++)
1401     {
1402 #define p_stream    p_sys->track[avi_pk.i_stream]
1403
1404         avi_packet_t    avi_pk;
1405
1406         if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1407         {
1408             return VLC_DEMUXER_EOF;
1409         }
1410
1411         if( avi_pk.i_stream >= p_sys->i_track ||
1412             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1413         {
1414             /* we haven't found an audio or video packet:
1415              *  - we have seek, found first next packet
1416              *  - others packets could be found, skip them
1417              */
1418             switch( avi_pk.i_fourcc )
1419             {
1420                 case AVIFOURCC_JUNK:
1421                 case AVIFOURCC_LIST:
1422                 case AVIFOURCC_RIFF:
1423                     return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1424                 case AVIFOURCC_idx1:
1425                     if( p_sys->b_odml )
1426                     {
1427                         return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1428                     }
1429                     return VLC_DEMUXER_EOF;
1430                 default:
1431                     msg_Warn( p_demux,
1432                               "seems to have lost position @%"PRIu64", resync",
1433                               vlc_stream_Tell(p_demux->s) );
1434                     if( AVI_PacketSearch( p_demux ) )
1435                     {
1436                         msg_Err( p_demux, "resync failed" );
1437                         return VLC_DEMUXER_EGENERIC;
1438                     }
1439             }
1440         }
1441         else
1442         {
1443             /* check for time */
1444             if( p_stream == p_stream_master ||
1445                 llabs( AVI_GetPTS( p_stream ) -
1446                         AVI_GetPTS( p_stream_master ) )< 2 * CLOCK_FREQ )
1447             {
1448                 /* load it and send to decoder */
1449                 block_t *p_frame = ReadFrame( p_demux, p_stream, 8, avi_pk.i_size + 8 ) ;
1450                 if( p_frame == NULL )
1451                 {
1452                     return VLC_DEMUXER_EGENERIC;
1453                 }
1454                 p_frame->i_pts = VLC_TS_0 + AVI_GetPTS( p_stream );
1455
1456                 if( avi_pk.i_cat != VIDEO_ES )
1457                     p_frame->i_dts = p_frame->i_pts;
1458                 else
1459                 {
1460                     p_frame->i_dts = p_frame->i_pts;
1461                     p_frame->i_pts = VLC_TS_INVALID;
1462                 }
1463
1464                 if( p_stream->i_dv_audio_rate )
1465                     AVI_DvHandleAudio( p_demux, p_stream, p_frame );
1466
1467                 if( p_stream->p_es )
1468                     es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1469                 else
1470                     block_Release( p_frame );
1471             }
1472             else
1473             {
1474                 if( AVI_PacketNext( p_demux ) )
1475                 {
1476                     return VLC_DEMUXER_EOF;
1477                 }
1478             }
1479
1480             /* *** update stream time position *** */
1481             if( p_stream->i_samplesize )
1482             {
1483                 p_stream->i_idxposb += avi_pk.i_size;
1484             }
1485             else
1486             {
1487                 if( p_stream->fmt.i_cat == AUDIO_ES )
1488                 {
1489                     p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1490                 }
1491                 p_stream->i_idxposc++;
1492             }
1493
1494         }
1495 #undef p_stream
1496     }
1497
1498     return VLC_DEMUXER_SUCCESS;
1499 }
1500
1501 /*****************************************************************************
1502  * Seek: goto to i_date or i_percent
1503  *****************************************************************************/
1504 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1505 {
1506     demux_sys_t *p_sys = p_demux->p_sys;
1507     msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1508              i_date / CLOCK_FREQ, i_percent );
1509
1510     if( p_sys->b_seekable )
1511     {
1512         int64_t i_pos_backup = vlc_stream_Tell( p_demux->s );
1513
1514         /* Check and lazy load indexes if it was not done (not fastseekable) */
1515         if ( !p_sys->b_indexloaded && ( p_sys->i_avih_flags & AVIF_HASINDEX ) )
1516         {
1517             avi_chunk_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
1518             if (unlikely( !p_riff ))
1519                 return VLC_EGENERIC;
1520
1521             int i_ret = AVI_ChunkFetchIndexes( p_demux->s, p_riff );
1522             if ( i_ret )
1523             {
1524                 /* Go back to position before index failure */
1525                 if ( vlc_stream_Tell( p_demux->s ) - i_pos_backup )
1526                     vlc_stream_Seek( p_demux->s, i_pos_backup );
1527
1528                 if ( p_sys->i_avih_flags & AVIF_MUSTUSEINDEX )
1529                     return VLC_EGENERIC;
1530             }
1531             else AVI_IndexLoad( p_demux );
1532
1533             p_sys->b_indexloaded = true; /* we don't want to try each time */
1534         }
1535
1536         if( !p_sys->i_length )
1537         {
1538             avi_track_t *p_stream = NULL;
1539             unsigned i_stream = 0;
1540             int64_t i_pos;
1541
1542             if ( !p_sys->i_movi_lastchunk_pos && /* set when index is successfully loaded */
1543                  ! ( p_sys->i_avih_flags & AVIF_ISINTERLEAVED ) )
1544             {
1545                 msg_Err( p_demux, "seeking without index at %d%%"
1546                          " only works for interleaved files", i_percent );
1547                 goto failandresetpos;
1548             }
1549             /* use i_percent to create a true i_date */
1550             if( i_percent >= 100 )
1551             {
1552                 msg_Warn( p_demux, "cannot seek so far !" );
1553                 goto failandresetpos;
1554             }
1555             i_percent = __MAX( i_percent, 0 );
1556
1557             /* try to find chunk that is at i_percent or the file */
1558             i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1559                            p_sys->i_movi_begin );
1560             /* search first selected stream (and prefer non-EOF ones) */
1561             for( unsigned i = 0; i < p_sys->i_track; i++ )
1562             {
1563                 avi_track_t *p_track = p_sys->track[i];
1564                 if( !p_track->b_activated )
1565                     continue;
1566
1567                 p_stream = p_track;
1568                 i_stream = i;
1569                 if( !p_track->b_eof )
1570                     break;
1571             }
1572             if( p_stream == NULL )
1573             {
1574                 msg_Warn( p_demux, "cannot find any selected stream" );
1575                 goto failandresetpos;
1576             }
1577
1578             /* be sure that the index exist */
1579             if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1580             {
1581                 msg_Warn( p_demux, "cannot seek" );
1582                 goto failandresetpos;
1583             }
1584
1585             while( i_pos >= p_stream->idx.p_entry[p_stream->i_idxposc].i_pos +
1586                p_stream->idx.p_entry[p_stream->i_idxposc].i_length + 8 )
1587             {
1588                 /* search after i_idxposc */
1589                 if( AVI_StreamChunkSet( p_demux,
1590                                         i_stream, p_stream->i_idxposc + 1 ) )
1591                 {
1592                     msg_Warn( p_demux, "cannot seek" );
1593                     goto failandresetpos;
1594                 }
1595             }
1596
1597             i_date = AVI_GetPTS( p_stream );
1598             /* TODO better support for i_samplesize != 0 */
1599             msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1600         }
1601
1602         /* */
1603         for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1604         {
1605             avi_track_t *p_stream = p_sys->track[i_stream];
1606
1607             if( !p_stream->b_activated )
1608                 continue;
1609
1610             p_stream->b_eof = AVI_TrackSeek( p_demux, i_stream, i_date ) != 0;
1611         }
1612         p_sys->i_time = i_date;
1613         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1614         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + p_sys->i_time );
1615         msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /CLOCK_FREQ );
1616         return VLC_SUCCESS;
1617
1618 failandresetpos:
1619         /* Go back to position before index failure */
1620         if ( vlc_stream_Tell( p_demux->s ) - i_pos_backup )
1621             vlc_stream_Seek( p_demux->s, i_pos_backup );
1622
1623         return VLC_EGENERIC;
1624     }
1625     else
1626     {
1627         msg_Err( p_demux, "shouldn't yet be executed" );
1628         return VLC_EGENERIC;
1629     }
1630 }
1631
1632 /*****************************************************************************
1633  * Control:
1634  *****************************************************************************/
1635 static double ControlGetPosition( demux_t *p_demux )
1636 {
1637     demux_sys_t *p_sys = p_demux->p_sys;
1638
1639     if( p_sys->i_length > 0 )
1640     {
1641         return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)CLOCK_FREQ );
1642     }
1643     else if( stream_Size( p_demux->s ) > 0 )
1644     {
1645         double i64 = (uint64_t)vlc_stream_Tell( p_demux->s );
1646         return i64 / stream_Size( p_demux->s );
1647     }
1648     return 0.0;
1649 }
1650
1651 static int Control( demux_t *p_demux, int i_query, va_list args )
1652 {
1653     demux_sys_t *p_sys = p_demux->p_sys;
1654     double   f, *pf;
1655     int64_t i64, *pi64;
1656     vlc_meta_t *p_meta;
1657
1658     switch( i_query )
1659     {
1660         case DEMUX_CAN_SEEK:
1661             *va_arg( args, bool * ) = p_sys->b_seekable;
1662             return VLC_SUCCESS;
1663
1664         case DEMUX_GET_POSITION:
1665             pf = va_arg( args, double * );
1666             *pf = ControlGetPosition( p_demux );
1667             return VLC_SUCCESS;
1668         case DEMUX_SET_POSITION:
1669             f = va_arg( args, double );
1670             if ( !p_sys->b_seekable )
1671             {
1672                 return VLC_EGENERIC;
1673             }
1674             else
1675             {
1676                 i64 = (mtime_t)(f * CLOCK_FREQ * p_sys->i_length);
1677                 return Seek( p_demux, i64, (int)(f * 100) );
1678             }
1679
1680         case DEMUX_GET_TIME:
1681             pi64 = va_arg( args, int64_t * );
1682             *pi64 = p_sys->i_time;
1683             return VLC_SUCCESS;
1684
1685         case DEMUX_SET_TIME:
1686         {
1687             int i_percent = 0;
1688
1689             i64 = va_arg( args, int64_t );
1690             if( !p_sys->b_seekable )
1691             {
1692                 return VLC_EGENERIC;
1693             }
1694             else if( p_sys->i_length > 0 )
1695             {
1696                 i_percent = 100 * i64 / (p_sys->i_length*CLOCK_FREQ);
1697             }
1698             else if( p_sys->i_time > 0 )
1699             {
1700                 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1701                                    (double)i64 / (double)p_sys->i_time );
1702             }
1703             return Seek( p_demux, i64, i_percent );
1704         }
1705         case DEMUX_GET_LENGTH:
1706             pi64 = va_arg( args, int64_t * );
1707             *pi64 = p_sys->i_length * (mtime_t)CLOCK_FREQ;
1708             return VLC_SUCCESS;
1709
1710         case DEMUX_GET_FPS:
1711             pf = va_arg( args, double * );
1712             *pf = 0.0;
1713             for( unsigned i = 0; i < p_sys->i_track; i++ )
1714             {
1715                 avi_track_t *tk = p_sys->track[i];
1716                 if( tk->fmt.i_cat == VIDEO_ES && tk->i_scale > 0)
1717                 {
1718                     *pf = (float)tk->i_rate / (float)tk->i_scale;
1719                     break;
1720                 }
1721             }
1722             return VLC_SUCCESS;
1723
1724         case DEMUX_GET_META:
1725             p_meta = va_arg( args, vlc_meta_t * );
1726             vlc_meta_Merge( p_meta,  p_sys->meta );
1727             return VLC_SUCCESS;
1728
1729         case DEMUX_GET_ATTACHMENTS:
1730         {
1731             if( p_sys->i_attachment <= 0 )
1732                 return VLC_EGENERIC;
1733
1734             input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1735             int *pi_int = va_arg( args, int * );
1736
1737             *ppp_attach = calloc( p_sys->i_attachment, sizeof(**ppp_attach) );
1738             if( likely(*ppp_attach) )
1739             {
1740                 *pi_int = p_sys->i_attachment;
1741                 for( unsigned i = 0; i < p_sys->i_attachment; i++ )
1742                     (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachment[i] );
1743                 return VLC_SUCCESS;
1744             }
1745             return VLC_EGENERIC;
1746         }
1747
1748         default:
1749             return VLC_EGENERIC;
1750     }
1751 }
1752
1753 /*****************************************************************************
1754  * Function to convert pts to chunk or byte
1755  *****************************************************************************/
1756
1757 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1758 {
1759     if( !tk->i_scale )
1760         return (mtime_t)0;
1761
1762     return (mtime_t)((int64_t)i_pts *
1763                      (int64_t)tk->i_rate /
1764                      (int64_t)tk->i_scale /
1765                      (int64_t)CLOCK_FREQ );
1766 }
1767 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1768 {
1769     if( !tk->i_scale || !tk->i_samplesize )
1770         return (mtime_t)0;
1771
1772     return (mtime_t)((int64_t)i_pts *
1773                      (int64_t)tk->i_rate /
1774                      (int64_t)tk->i_scale /
1775                      (int64_t)1000000 *
1776                      (int64_t)tk->i_samplesize );
1777 }
1778
1779 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1780 {
1781     mtime_t i_dpts = 0;
1782
1783     if( !tk->i_rate )
1784         return i_dpts;
1785
1786     i_dpts = (mtime_t)( (int64_t)1000000 *
1787                         (int64_t)i_count *
1788                         (int64_t)tk->i_scale /
1789                         (int64_t)tk->i_rate );
1790
1791     if( tk->i_samplesize )
1792     {
1793         return i_dpts / tk->i_samplesize;
1794     }
1795     return i_dpts;
1796 }
1797
1798 static mtime_t AVI_GetPTS( avi_track_t *tk )
1799 {
1800     if( tk->i_samplesize )
1801     {
1802         int64_t i_count = 0;
1803
1804         /* we need a valid entry we will emulate one */
1805         if( tk->i_idxposc == tk->idx.i_size )
1806         {
1807             if( tk->i_idxposc )
1808             {
1809                 /* use the last entry */
1810                 i_count = tk->idx.p_entry[tk->idx.i_size - 1].i_lengthtotal
1811                             + tk->idx.p_entry[tk->idx.i_size - 1].i_length;
1812             }
1813         }
1814         else
1815         {
1816             i_count = tk->idx.p_entry[tk->i_idxposc].i_lengthtotal;
1817         }
1818         return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1819     }
1820     else
1821     {
1822         if( tk->fmt.i_cat == AUDIO_ES )
1823         {
1824             return AVI_GetDPTS( tk, tk->i_blockno );
1825         }
1826         else
1827         {
1828             return AVI_GetDPTS( tk, tk->i_idxposc );
1829         }
1830     }
1831 }
1832
1833 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1834 {
1835     demux_sys_t *p_sys = p_demux->p_sys;
1836     avi_packet_t avi_pk;
1837     int i_loop_count = 0;
1838
1839     /* find first chunk of i_stream that isn't in index */
1840
1841     if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1842     {
1843         vlc_stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1844         if( AVI_PacketNext( p_demux ) )
1845         {
1846             return VLC_EGENERIC;
1847         }
1848     }
1849     else
1850     {
1851         vlc_stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1852     }
1853
1854     for( ;; )
1855     {
1856         if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1857         {
1858             msg_Warn( p_demux, "cannot get packet header" );
1859             return VLC_EGENERIC;
1860         }
1861         if( avi_pk.i_stream >= p_sys->i_track ||
1862             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1863         {
1864             if( AVI_PacketNext( p_demux ) )
1865             {
1866                 return VLC_EGENERIC;
1867             }
1868
1869             /* Prevents from eating all the CPU with broken files.
1870              * This value should be low enough so that it doesn't
1871              * affect the reading speed too much. */
1872             if( !(++i_loop_count % 1024) )
1873             {
1874                 msleep( 10000 );
1875
1876                 if( !(i_loop_count % (1024 * 10)) )
1877                     msg_Warn( p_demux, "don't seem to find any data..." );
1878             }
1879         }
1880         else
1881         {
1882             avi_track_t *tk_pk = p_sys->track[avi_pk.i_stream];
1883
1884             /* add this chunk to the index */
1885             avi_entry_t index;
1886             index.i_id     = avi_pk.i_fourcc;
1887             index.i_flags  = AVI_GetKeyFlag(tk_pk->fmt.i_codec, avi_pk.i_peek);
1888             index.i_pos    = avi_pk.i_pos;
1889             index.i_length = avi_pk.i_size;
1890             index.i_lengthtotal = index.i_length;
1891             avi_index_Append( &tk_pk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1892
1893             if( avi_pk.i_stream == i_stream  )
1894             {
1895                 return VLC_SUCCESS;
1896             }
1897
1898             if( AVI_PacketNext( p_demux ) )
1899             {
1900                 return VLC_EGENERIC;
1901             }
1902         }
1903     }
1904 }
1905
1906 /* be sure that i_ck will be a valid index entry */
1907 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1908                                unsigned int i_ck )
1909 {
1910     demux_sys_t *p_sys = p_demux->p_sys;
1911     avi_track_t *p_stream = p_sys->track[i_stream];
1912
1913     p_stream->i_idxposc = i_ck;
1914     p_stream->i_idxposb = 0;
1915
1916     if(  i_ck >= p_stream->idx.i_size )
1917     {
1918         p_stream->i_idxposc = p_stream->idx.i_size - 1;
1919         do
1920         {
1921             p_stream->i_idxposc++;
1922             if( AVI_StreamChunkFind( p_demux, i_stream ) )
1923             {
1924                 return VLC_EGENERIC;
1925             }
1926
1927         } while( p_stream->i_idxposc < i_ck );
1928     }
1929
1930     return VLC_SUCCESS;
1931 }
1932
1933 /* XXX FIXME up to now, we assume that all chunk are one after one */
1934 static int AVI_StreamBytesSet( demux_t    *p_demux,
1935                                unsigned int i_stream,
1936                                off_t   i_byte )
1937 {
1938     demux_sys_t *p_sys = p_demux->p_sys;
1939     avi_track_t *p_stream = p_sys->track[i_stream];
1940
1941     if( ( p_stream->idx.i_size > 0 )
1942         &&( i_byte < p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_lengthtotal +
1943                 p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_length ) )
1944     {
1945         /* index is valid to find the ck */
1946         /* uses dichototmie to be fast enougth */
1947         int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->idx.i_size - 1 );
1948         int i_idxmax  = p_stream->idx.i_size;
1949         int i_idxmin  = 0;
1950         for( ;; )
1951         {
1952             if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal > i_byte )
1953             {
1954                 i_idxmax  = i_idxposc ;
1955                 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1956             }
1957             else
1958             {
1959                 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal +
1960                         p_stream->idx.p_entry[i_idxposc].i_length <= i_byte)
1961                 {
1962                     i_idxmin  = i_idxposc ;
1963                     i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1964                 }
1965                 else
1966                 {
1967                     p_stream->i_idxposc = i_idxposc;
1968                     p_stream->i_idxposb = i_byte -
1969                             p_stream->idx.p_entry[i_idxposc].i_lengthtotal;
1970                     return VLC_SUCCESS;
1971                 }
1972             }
1973         }
1974
1975     }
1976     else
1977     {
1978         p_stream->i_idxposc = p_stream->idx.i_size - 1;
1979         p_stream->i_idxposb = 0;
1980         do
1981         {
1982             p_stream->i_idxposc++;
1983             if( AVI_StreamChunkFind( p_demux, i_stream ) )
1984             {
1985                 return VLC_EGENERIC;
1986             }
1987
1988         } while( p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal +
1989                     p_stream->idx.p_entry[p_stream->i_idxposc].i_length <= i_byte );
1990
1991         p_stream->i_idxposb = i_byte -
1992                        p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal;
1993         return VLC_SUCCESS;
1994     }
1995 }
1996
1997 static int AVI_TrackSeek( demux_t *p_demux,
1998                            int i_stream,
1999                            mtime_t i_date )
2000 {
2001     demux_sys_t  *p_sys = p_demux->p_sys;
2002     avi_track_t  *tk = p_sys->track[i_stream];
2003
2004 #define p_stream    p_sys->track[i_stream]
2005     mtime_t i_oldpts;
2006
2007     i_oldpts = AVI_GetPTS( p_stream );
2008
2009     if( !p_stream->i_samplesize )
2010     {
2011         if( AVI_StreamChunkSet( p_demux,
2012                                 i_stream,
2013                                 AVI_PTSToChunk( p_stream, i_date ) ) )
2014         {
2015             return VLC_EGENERIC;
2016         }
2017
2018         if( p_stream->fmt.i_cat == AUDIO_ES )
2019         {
2020             unsigned int i;
2021             tk->i_blockno = 0;
2022             for( i = 0; i < tk->i_idxposc; i++ )
2023             {
2024                 if( tk->i_blocksize > 0 )
2025                 {
2026                     tk->i_blockno += ( tk->idx.p_entry[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
2027                 }
2028                 else
2029                 {
2030                     tk->i_blockno++;
2031                 }
2032             }
2033         }
2034
2035         msg_Dbg( p_demux,
2036                  "old:%"PRId64" %s new %"PRId64,
2037                  i_oldpts,
2038                  i_oldpts > i_date ? ">" : "<",
2039                  i_date );
2040
2041         if( p_stream->fmt.i_cat == VIDEO_ES )
2042         {
2043             /* search key frame */
2044             //if( i_date < i_oldpts || 1 )
2045             {
2046                 while( p_stream->i_idxposc > 0 &&
2047                    !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
2048                                                                 AVIIF_KEYFRAME ) )
2049                 {
2050                     if( AVI_StreamChunkSet( p_demux,
2051                                             i_stream,
2052                                             p_stream->i_idxposc - 1 ) )
2053                     {
2054                         return VLC_EGENERIC;
2055                     }
2056                 }
2057             }
2058 #if 0
2059             else
2060             {
2061                 while( p_stream->i_idxposc < p_stream->idx.i_size &&
2062                         !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
2063                                                                 AVIIF_KEYFRAME ) )
2064                 {
2065                     if( AVI_StreamChunkSet( p_demux,
2066                                             i_stream,
2067                                             p_stream->i_idxposc + 1 ) )
2068                     {
2069                         return VLC_EGENERIC;
2070                     }
2071                 }
2072             }
2073 #endif
2074         }
2075     }
2076     else
2077     {
2078         if( AVI_StreamBytesSet( p_demux,
2079                                 i_stream,
2080                                 AVI_PTSToByte( p_stream, i_date ) ) )
2081         {
2082             return VLC_EGENERIC;
2083         }
2084     }
2085     return VLC_SUCCESS;
2086 #undef p_stream
2087 }
2088
2089 /****************************************************************************
2090  * Return true if it's a key frame
2091  ****************************************************************************/
2092 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
2093 {
2094     switch( i_fourcc )
2095     {
2096         case VLC_CODEC_DIV1:
2097             /* we have:
2098              *  startcode:      0x00000100   32bits
2099              *  framenumber     ?             5bits
2100              *  piture type     0(I),1(P)     2bits
2101              */
2102             if( GetDWBE( p_byte ) != 0x00000100 )
2103             {
2104                 /* it's not an msmpegv1 stream, strange...*/
2105                 return AVIIF_KEYFRAME;
2106             }
2107             return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
2108
2109         case VLC_CODEC_DIV2:
2110         case VLC_CODEC_DIV3:
2111         case VLC_CODEC_WMV1:
2112             /* we have
2113              *  picture type    0(I),1(P)     2bits
2114              */
2115             return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2116         case VLC_CODEC_MP4V:
2117             /* we should find first occurrence of 0x000001b6 (32bits)
2118              *  startcode:      0x000001b6   32bits
2119              *  piture type     0(I),1(P)     2bits
2120              */
2121             if( GetDWBE( p_byte ) != 0x000001b6 )
2122             {
2123                 /* not true , need to find the first VOP header */
2124                 return AVIIF_KEYFRAME;
2125             }
2126             return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2127
2128         default:
2129             /* I can't do it, so say yes */
2130             return AVIIF_KEYFRAME;
2131     }
2132 }
2133
2134 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
2135 {
2136     switch( i_cat )
2137     {
2138         case AUDIO_ES:
2139             wf_tag_to_fourcc( i_codec, &i_codec, NULL );
2140             return i_codec;
2141         case VIDEO_ES:
2142             return vlc_fourcc_GetCodec( i_cat, i_codec );
2143         default:
2144             return VLC_CODEC_UNKNOWN;
2145     }
2146 }
2147
2148 /****************************************************************************
2149  *
2150  ****************************************************************************/
2151 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
2152                                    unsigned int *pi_number,
2153                                    enum es_format_category_e *pi_type )
2154 {
2155     int c1, c2;
2156
2157     c1 = ((uint8_t *)&i_id)[0];
2158     c2 = ((uint8_t *)&i_id)[1];
2159
2160     if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
2161     {
2162         *pi_number =  100; /* > max stream number */
2163         *pi_type = UNKNOWN_ES;
2164     }
2165     else
2166     {
2167         *pi_number = (c1 - '0') * 10 + (c2 - '0' );
2168         switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
2169         {
2170             case AVITWOCC_wb:
2171                 *pi_type = AUDIO_ES;
2172                 break;
2173             case AVITWOCC_dc:
2174             case AVITWOCC_db:
2175             case AVITWOCC_AC:
2176                 *pi_type = VIDEO_ES;
2177                 break;
2178             case AVITWOCC_tx:
2179             case AVITWOCC_sb:
2180                 *pi_type = SPU_ES;
2181                 break;
2182             case AVITWOCC_pc:
2183                 *pi_type = IGNORE_ES;
2184                 break;
2185             default:
2186                 *pi_type = UNKNOWN_ES;
2187                 break;
2188         }
2189     }
2190 }
2191
2192 /****************************************************************************
2193  *
2194  ****************************************************************************/
2195 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
2196 {
2197     const uint8_t *p_peek;
2198
2199     if( vlc_stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
2200     {
2201         return VLC_EGENERIC;
2202     }
2203     p_pk->i_fourcc  = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
2204     p_pk->i_size    = GetDWLE( p_peek + 4 );
2205     p_pk->i_pos     = vlc_stream_Tell( p_demux->s );
2206     if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
2207     {
2208         p_pk->i_type = VLC_FOURCC( p_peek[8],  p_peek[9],
2209                                    p_peek[10], p_peek[11] );
2210     }
2211     else
2212     {
2213         p_pk->i_type = 0;
2214     }
2215
2216     memcpy( p_pk->i_peek, p_peek + 8, 8 );
2217
2218     AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
2219     return VLC_SUCCESS;
2220 }
2221
2222 static int AVI_PacketNext( demux_t *p_demux )
2223 {
2224     avi_packet_t    avi_ck;
2225     size_t          i_skip = 0;
2226
2227     if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2228     {
2229         return VLC_EGENERIC;
2230     }
2231
2232     if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2233         ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2234     {
2235         i_skip = 12;
2236     }
2237     else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2238              avi_ck.i_type == AVIFOURCC_AVIX )
2239     {
2240         i_skip = 24;
2241     }
2242     else
2243     {
2244         if( avi_ck.i_size > UINT32_MAX - 9 )
2245             return VLC_EGENERIC;
2246         i_skip = __EVEN( avi_ck.i_size ) + 8;
2247     }
2248
2249     if( i_skip > SSIZE_MAX )
2250         return VLC_EGENERIC;
2251
2252     ssize_t i_ret = vlc_stream_Read( p_demux->s, NULL, i_skip );
2253     if( i_ret < 0 || (size_t) i_ret != i_skip )
2254     {
2255         return VLC_EGENERIC;
2256     }
2257     return VLC_SUCCESS;
2258 }
2259
2260 static int AVI_PacketSearch( demux_t *p_demux )
2261 {
2262     demux_sys_t     *p_sys = p_demux->p_sys;
2263     avi_packet_t    avi_pk;
2264     int             i_count = 0;
2265
2266     for( ;; )
2267     {
2268         if( vlc_stream_Read( p_demux->s, NULL, 1 ) != 1 )
2269         {
2270             return VLC_EGENERIC;
2271         }
2272         AVI_PacketGetHeader( p_demux, &avi_pk );
2273         if( avi_pk.i_stream < p_sys->i_track &&
2274             ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2275         {
2276             return VLC_SUCCESS;
2277         }
2278         switch( avi_pk.i_fourcc )
2279         {
2280             case AVIFOURCC_JUNK:
2281             case AVIFOURCC_LIST:
2282             case AVIFOURCC_RIFF:
2283             case AVIFOURCC_idx1:
2284                 return VLC_SUCCESS;
2285         }
2286
2287         /* Prevents from eating all the CPU with broken files.
2288          * This value should be low enough so that it doesn't affect the
2289          * reading speed too much (not that we care much anyway because
2290          * this code is called only on broken files). */
2291         if( !(++i_count % 1024) )
2292         {
2293             msleep( 10000 );
2294             if( !(i_count % (1024 * 10)) )
2295                 msg_Warn( p_demux, "trying to resync..." );
2296         }
2297     }
2298 }
2299
2300 /****************************************************************************
2301  * Index stuff.
2302  ****************************************************************************/
2303 static void avi_index_Init( avi_index_t *p_index )
2304 {
2305     p_index->i_size  = 0;
2306     p_index->i_max   = 0;
2307     p_index->p_entry = NULL;
2308 }
2309 static void avi_index_Clean( avi_index_t *p_index )
2310 {
2311     free( p_index->p_entry );
2312 }
2313 static void avi_index_Append( avi_index_t *p_index, off_t *pi_last_pos,
2314                               avi_entry_t *p_entry )
2315 {
2316     /* Update last chunk position */
2317     if( *pi_last_pos < p_entry->i_pos )
2318          *pi_last_pos = p_entry->i_pos;
2319
2320     /* add the entry */
2321     if( p_index->i_size >= p_index->i_max )
2322     {
2323         p_index->i_max += 16384;
2324         p_index->p_entry = realloc_or_free( p_index->p_entry,
2325                                             p_index->i_max * sizeof( *p_index->p_entry ) );
2326         if( !p_index->p_entry )
2327             return;
2328     }
2329     /* calculate cumulate length */
2330     if( p_index->i_size > 0 )
2331     {
2332         p_entry->i_lengthtotal =
2333             p_index->p_entry[p_index->i_size - 1].i_length +
2334                 p_index->p_entry[p_index->i_size - 1].i_lengthtotal;
2335     }
2336     else
2337     {
2338         p_entry->i_lengthtotal = 0;
2339     }
2340
2341     p_index->p_entry[p_index->i_size++] = *p_entry;
2342 }
2343
2344 static int AVI_IndexFind_idx1( demux_t *p_demux,
2345                                avi_chunk_idx1_t **pp_idx1,
2346                                uint64_t *pi_offset )
2347 {
2348     demux_sys_t *p_sys = p_demux->p_sys;
2349
2350     avi_chunk_list_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2351     avi_chunk_idx1_t *p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2352
2353     if( !p_idx1 )
2354     {
2355         msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2356         return VLC_EGENERIC;
2357     }
2358     *pp_idx1 = p_idx1;
2359
2360     /* The offset in the index should be from the start of the movi content,
2361      * but some broken files use offset from the start of the file. Just
2362      * checking the offset of the first packet is not enough as some files
2363      * has unused chunk at the beginning of the movi content.
2364      */
2365     avi_chunk_list_t *p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2366     uint64_t i_first_pos = UINT64_MAX;
2367     for( unsigned i = 0; i < __MIN( p_idx1->i_entry_count, 100 ); i++ )
2368     {
2369         if ( p_idx1->entry[i].i_length > 0 )
2370             i_first_pos = __MIN( i_first_pos, p_idx1->entry[i].i_pos );
2371     }
2372
2373     const uint64_t i_movi_content = p_movi->i_chunk_pos + 8;
2374     if( i_first_pos < i_movi_content )
2375     {
2376         *pi_offset = i_movi_content;
2377     }
2378     else if( p_sys->b_seekable && i_first_pos < UINT64_MAX )
2379     {
2380         const uint8_t *p_peek;
2381         if( !vlc_stream_Seek( p_demux->s, i_movi_content + i_first_pos ) &&
2382             vlc_stream_Peek( p_demux->s, &p_peek, 4 ) >= 4 &&
2383             ( !isdigit( p_peek[0] ) || !isdigit( p_peek[1] ) ||
2384               !isalpha( p_peek[2] ) || !isalpha( p_peek[3] ) ) )
2385             *pi_offset = 0;
2386         else
2387             *pi_offset = i_movi_content;
2388
2389         if( p_idx1->i_entry_count )
2390         {
2391             /* Invalidate offset if index refers past the data section to avoid false
2392                positives when the offset equals sample size */
2393             size_t i_dataend = *pi_offset + p_idx1->entry[p_idx1->i_entry_count - 1].i_pos +
2394                                             p_idx1->entry[p_idx1->i_entry_count - 1].i_length;
2395             if( i_dataend > p_movi->i_chunk_pos + p_movi->i_chunk_size )
2396                 *pi_offset = 0;
2397         }
2398     }
2399     else
2400     {
2401         *pi_offset = 0;
2402     }
2403
2404     return VLC_SUCCESS;
2405 }
2406
2407 static int AVI_IndexLoad_idx1( demux_t *p_demux,
2408                                avi_index_t p_index[], off_t *pi_last_offset )
2409 {
2410     demux_sys_t *p_sys = p_demux->p_sys;
2411
2412     avi_chunk_idx1_t *p_idx1;
2413     uint64_t         i_offset;
2414     if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2415         return VLC_EGENERIC;
2416
2417     p_sys->b_indexloaded = true;
2418
2419     for( unsigned i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2420     {
2421         enum es_format_category_e i_cat;
2422         unsigned i_stream;
2423
2424         AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2425                                &i_stream,
2426                                &i_cat );
2427         if( i_stream < p_sys->i_track &&
2428             (i_cat == p_sys->track[i_stream]->fmt.i_cat || i_cat == UNKNOWN_ES ) )
2429         {
2430             avi_entry_t index;
2431             index.i_id     = p_idx1->entry[i_index].i_fourcc;
2432             index.i_flags  = p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2433             index.i_pos    = p_idx1->entry[i_index].i_pos + i_offset;
2434             index.i_length = p_idx1->entry[i_index].i_length;
2435             index.i_lengthtotal = index.i_length;
2436
2437             avi_index_Append( &p_index[i_stream], pi_last_offset, &index );
2438         }
2439     }
2440
2441 #ifdef AVI_DEBUG
2442     for( unsigned i_index = 0; i_index< p_idx1->i_entry_count && i_index < p_sys->i_track; i_index++ )
2443     {
2444         for( unsigned i = 0; i < p_index[i_index].i_size; i++ )
2445         {
2446             mtime_t i_length;
2447             if( p_sys->track[i_index]->i_samplesize )
2448             {
2449                 i_length = AVI_GetDPTS( p_sys->track[i_index],
2450                                         p_index[i_index].p_entry[i].i_lengthtotal );
2451             }
2452             else
2453             {
2454                 i_length = AVI_GetDPTS( p_sys->track[i_index], i );
2455             }
2456             msg_Dbg( p_demux, "index stream %d @%ld time %ld", i_index,
2457                      p_index[i_index].p_entry[i].i_pos, i_length );
2458         }
2459     }
2460 #endif
2461     return VLC_SUCCESS;
2462 }
2463
2464 static void __Parse_indx( demux_t *p_demux, avi_index_t *p_index, off_t *pi_max_offset,
2465                           avi_chunk_indx_t *p_indx )
2466 {
2467     avi_entry_t index;
2468
2469     p_demux->p_sys->b_indexloaded = true;
2470
2471     msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2472     if( p_indx->i_indexsubtype == 0 )
2473     {
2474         for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2475         {
2476             index.i_id     = p_indx->i_id;
2477             index.i_flags  = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2478             index.i_pos    = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2479             index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2480             index.i_lengthtotal = index.i_length;
2481
2482             avi_index_Append( p_index, pi_max_offset, &index );
2483         }
2484     }
2485     else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2486     {
2487         for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2488         {
2489             index.i_id     = p_indx->i_id;
2490             index.i_flags  = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2491             index.i_pos    = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2492             index.i_length = p_indx->idx.field[i].i_size;
2493             index.i_lengthtotal = index.i_length;
2494
2495             avi_index_Append( p_index, pi_max_offset, &index );
2496         }
2497     }
2498     else
2499     {
2500         msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2501     }
2502 }
2503
2504 static void AVI_IndexLoad_indx( demux_t *p_demux,
2505                                 avi_index_t p_index[], off_t *pi_last_offset )
2506 {
2507     demux_sys_t         *p_sys = p_demux->p_sys;
2508
2509     avi_chunk_list_t    *p_riff;
2510     avi_chunk_list_t    *p_hdrl;
2511
2512     p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2513     p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2514
2515     for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2516     {
2517         avi_chunk_list_t    *p_strl;
2518         avi_chunk_indx_t    *p_indx;
2519
2520 #define p_stream  p_sys->track[i_stream]
2521         p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2522         p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2523
2524         if( !p_indx )
2525         {
2526             if( p_sys->b_odml )
2527                 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2528                                    "file?)" );
2529             continue;
2530         }
2531
2532         if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2533         {
2534             __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, p_indx );
2535         }
2536         else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2537         {
2538             if ( !p_sys->b_seekable )
2539                 return;
2540             avi_chunk_t    ck_sub;
2541             for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2542             {
2543                 if( vlc_stream_Seek( p_demux->s,
2544                                      p_indx->idx.super[i].i_offset ) ||
2545                     AVI_ChunkRead( p_demux->s, &ck_sub, NULL  ) )
2546                 {
2547                     break;
2548                 }
2549                 if( ck_sub.indx.i_indextype == AVI_INDEX_OF_CHUNKS )
2550                     __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, &ck_sub.indx );
2551                 AVI_ChunkClean( p_demux->s, &ck_sub );
2552             }
2553         }
2554         else
2555         {
2556             msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2557         }
2558 #undef p_stream
2559     }
2560 }
2561
2562 static void AVI_IndexLoad( demux_t *p_demux )
2563 {
2564     demux_sys_t *p_sys = p_demux->p_sys;
2565
2566     /* Load indexes */
2567     assert( p_sys->i_track <= 100 );
2568     avi_index_t p_idx_indx[p_sys->i_track];
2569     avi_index_t p_idx_idx1[p_sys->i_track];
2570     for( unsigned i = 0; i < p_sys->i_track; i++ )
2571     {
2572         avi_index_Init( &p_idx_indx[i] );
2573         avi_index_Init( &p_idx_idx1[i] );
2574     }
2575     off_t i_indx_last_pos = p_sys->i_movi_lastchunk_pos;
2576     off_t i_idx1_last_pos = p_sys->i_movi_lastchunk_pos;
2577
2578     AVI_IndexLoad_indx( p_demux, p_idx_indx, &i_indx_last_pos );
2579     if( !p_sys->b_odml )
2580         AVI_IndexLoad_idx1( p_demux, p_idx_idx1, &i_idx1_last_pos );
2581
2582     /* Select the longest index */
2583     for( unsigned i = 0; i < p_sys->i_track; i++ )
2584     {
2585         if( p_idx_indx[i].i_size > p_idx_idx1[i].i_size )
2586         {
2587             msg_Dbg( p_demux, "selected ODML index for stream[%u]", i );
2588             p_sys->track[i]->idx = p_idx_indx[i];
2589             avi_index_Clean( &p_idx_idx1[i] );
2590         }
2591         else
2592         {
2593             msg_Dbg( p_demux, "selected standard index for stream[%u]", i );
2594             p_sys->track[i]->idx = p_idx_idx1[i];
2595             avi_index_Clean( &p_idx_indx[i] );
2596         }
2597     }
2598     p_sys->i_movi_lastchunk_pos = __MAX( i_indx_last_pos, i_idx1_last_pos );
2599
2600     for( unsigned i = 0; i < p_sys->i_track; i++ )
2601     {
2602         avi_index_t *p_index = &p_sys->track[i]->idx;
2603
2604         /* Fix key flag */
2605         bool b_key = false;
2606         for( unsigned j = 0; !b_key && j < p_index->i_size; j++ )
2607             b_key = p_index->p_entry[j].i_flags & AVIIF_KEYFRAME;
2608         if( !b_key )
2609         {
2610             msg_Err( p_demux, "no key frame set for track %u", i );
2611             for( unsigned j = 0; j < p_index->i_size; j++ )
2612                 p_index->p_entry[j].i_flags |= AVIIF_KEYFRAME;
2613         }
2614
2615         /* */
2616         msg_Dbg( p_demux, "stream[%d] created %d index entries",
2617                  i, p_index->i_size );
2618     }
2619 }
2620
2621 static void AVI_IndexCreate( demux_t *p_demux )
2622 {
2623     demux_sys_t *p_sys = p_demux->p_sys;
2624
2625     avi_chunk_list_t *p_riff;
2626     avi_chunk_list_t *p_movi;
2627
2628     unsigned int i_stream;
2629     off_t i_movi_end;
2630
2631     mtime_t i_dialog_update;
2632     vlc_dialog_id *p_dialog_id = NULL;
2633
2634     p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2635     p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2636
2637     if( !p_movi )
2638     {
2639         msg_Err( p_demux, "cannot find p_movi" );
2640         return;
2641     }
2642
2643     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2644         avi_index_Init( &p_sys->track[i_stream]->idx );
2645
2646     i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2647                         stream_Size( p_demux->s ) );
2648
2649     vlc_stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2650     msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2651
2652
2653     /* Only show dialog if AVI is > 10MB */
2654     i_dialog_update = mdate();
2655     if( stream_Size( p_demux->s ) > 10000000 )
2656     {
2657         p_dialog_id =
2658             vlc_dialog_display_progress( p_demux, false, 0.0, _("Cancel"),
2659                                          _("Broken or missing AVI Index"),
2660                                          _("Fixing AVI Index...") );
2661     }
2662
2663     for( ;; )
2664     {
2665         avi_packet_t pk;
2666
2667         /* Don't update/check dialog too often */
2668         if( p_dialog_id != NULL && mdate() - i_dialog_update > 100000 )
2669         {
2670             if( vlc_dialog_is_cancelled( p_demux, p_dialog_id ) )
2671                 break;
2672
2673             double f_current = vlc_stream_Tell( p_demux->s );
2674             double f_size    = stream_Size( p_demux->s );
2675             double f_pos     = f_current / f_size;
2676             vlc_dialog_update_progress( p_demux, p_dialog_id, f_pos );
2677
2678             i_dialog_update = mdate();
2679         }
2680
2681         if( AVI_PacketGetHeader( p_demux, &pk ) )
2682             break;
2683
2684         if( pk.i_stream < p_sys->i_track &&
2685             pk.i_cat == p_sys->track[pk.i_stream]->fmt.i_cat )
2686         {
2687             avi_track_t *tk = p_sys->track[pk.i_stream];
2688
2689             avi_entry_t index;
2690             index.i_id      = pk.i_fourcc;
2691             index.i_flags   = AVI_GetKeyFlag(tk->fmt.i_codec, pk.i_peek);
2692             index.i_pos     = pk.i_pos;
2693             index.i_length  = pk.i_size;
2694             index.i_lengthtotal = pk.i_size;
2695             avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
2696         }
2697         else
2698         {
2699             switch( pk.i_fourcc )
2700             {
2701             case AVIFOURCC_idx1:
2702                 if( p_sys->b_odml )
2703                 {
2704                     avi_chunk_list_t *p_sysx;
2705                     p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2706                                             AVIFOURCC_RIFF, 1 );
2707
2708                     msg_Dbg( p_demux, "looking for new RIFF chunk" );
2709                     if( vlc_stream_Seek( p_demux->s,
2710                                          p_sysx->i_chunk_pos + 24 ) )
2711                         goto print_stat;
2712                     break;
2713                 }
2714                 goto print_stat;
2715
2716             case AVIFOURCC_RIFF:
2717                     msg_Dbg( p_demux, "new RIFF chunk found" );
2718                     break;
2719
2720             case AVIFOURCC_rec:
2721             case AVIFOURCC_JUNK:
2722                 break;
2723
2724             default:
2725                 msg_Warn( p_demux, "need resync, probably broken avi" );
2726                 if( AVI_PacketSearch( p_demux ) )
2727                 {
2728                     msg_Warn( p_demux, "lost sync, abord index creation" );
2729                     goto print_stat;
2730                 }
2731             }
2732         }
2733
2734         if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2735             AVI_PacketNext( p_demux ) )
2736         {
2737             break;
2738         }
2739     }
2740
2741 print_stat:
2742     if( p_dialog_id != NULL )
2743         vlc_dialog_release( p_demux, p_dialog_id );
2744
2745     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2746     {
2747         msg_Dbg( p_demux, "stream[%d] creating %d index entries",
2748                 i_stream, p_sys->track[i_stream]->idx.i_size );
2749     }
2750 }
2751
2752 /* */
2753 static void AVI_MetaLoad( demux_t *p_demux,
2754                           avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih )
2755 {
2756     demux_sys_t *p_sys = p_demux->p_sys;
2757
2758     vlc_meta_t *p_meta = p_sys->meta = vlc_meta_New();
2759     if( !p_meta )
2760         return;
2761
2762     char buffer[200];
2763     snprintf( buffer, sizeof(buffer), "%s%s%s%s",
2764               p_avih->i_flags&AVIF_HASINDEX      ? " HAS_INDEX"      : "",
2765               p_avih->i_flags&AVIF_MUSTUSEINDEX  ? " MUST_USE_INDEX" : "",
2766               p_avih->i_flags&AVIF_ISINTERLEAVED ? " IS_INTERLEAVED" : "",
2767               p_avih->i_flags&AVIF_TRUSTCKTYPE   ? " TRUST_CKTYPE"   : "" );
2768     vlc_meta_SetSetting( p_meta, buffer );
2769
2770     avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
2771     if( !p_info )
2772         return;
2773
2774     static const struct {
2775         vlc_fourcc_t i_id;
2776         int          i_type;
2777     } p_dsc[] = {
2778         { AVIFOURCC_IART, vlc_meta_Artist },
2779         { AVIFOURCC_ICMT, vlc_meta_Description },
2780         { AVIFOURCC_ICOP, vlc_meta_Copyright },
2781         { AVIFOURCC_IGNR, vlc_meta_Genre },
2782         { AVIFOURCC_INAM, vlc_meta_Title },
2783         { AVIFOURCC_ICRD, vlc_meta_Date },
2784         { AVIFOURCC_ILNG, vlc_meta_Language },
2785         { AVIFOURCC_IRTD, vlc_meta_Rating },
2786         { AVIFOURCC_IWEB, vlc_meta_URL },
2787         { AVIFOURCC_IPRT, vlc_meta_TrackNumber },
2788         { AVIFOURCC_IFRM, vlc_meta_TrackTotal },
2789         { 0, -1 }
2790     };
2791     for( int i = 0; p_dsc[i].i_id != 0; i++ )
2792     {
2793         avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_dsc[i].i_id, 0 );
2794         if( !p_strz || !p_strz->p_str )
2795             continue;
2796         char *psz_value = FromACP( p_strz->p_str );
2797         if( !psz_value )
2798             continue;
2799
2800         if( *psz_value )
2801             vlc_meta_Set( p_meta, p_dsc[i].i_type, psz_value );
2802         free( psz_value );
2803     }
2804
2805     static const vlc_fourcc_t p_extra[] = {
2806         AVIFOURCC_IARL, AVIFOURCC_ICMS, AVIFOURCC_ICRP, AVIFOURCC_IDIM, AVIFOURCC_IDPI,
2807         AVIFOURCC_IENG, AVIFOURCC_IKEY, AVIFOURCC_ILGT, AVIFOURCC_IMED, AVIFOURCC_IPLT,
2808         AVIFOURCC_IPRD, AVIFOURCC_ISBJ, AVIFOURCC_ISFT, AVIFOURCC_ISHP, AVIFOURCC_ISRC,
2809         AVIFOURCC_ISRF, AVIFOURCC_ITCH, AVIFOURCC_ISMP, AVIFOURCC_IDIT, AVIFOURCC_ISGN,
2810         AVIFOURCC_IWRI, AVIFOURCC_IPRO, AVIFOURCC_ICNM, AVIFOURCC_IPDS, AVIFOURCC_IEDT,
2811         AVIFOURCC_ICDS, AVIFOURCC_IMUS, AVIFOURCC_ISTD, AVIFOURCC_IDST, AVIFOURCC_ICNT,
2812         AVIFOURCC_ISTR, 0,
2813     };
2814
2815     for( int i = 0; p_extra[i] != 0; i++ )
2816     {
2817         avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_extra[i], 0 );
2818         if( !p_strz || !p_strz->p_str )
2819             continue;
2820         char *psz_value = FromACP( p_strz->p_str );
2821         if( !psz_value )
2822             continue;
2823
2824         if( *psz_value )
2825             vlc_meta_AddExtra( p_meta, p_strz->p_type, psz_value );
2826         free( psz_value );
2827     }
2828 }
2829
2830 static void AVI_DvHandleAudio( demux_t *p_demux, avi_track_t *tk, block_t *p_frame )
2831 {
2832     size_t i_offset = 80 * 6 + 80 * 16 * 3 + 3;
2833     if( p_frame->i_buffer < i_offset + 5 )
2834         return;
2835
2836     if( p_frame->p_buffer[i_offset] != 0x50 )
2837         return;
2838
2839     es_format_t fmt;
2840     dv_get_audio_format( &fmt, &p_frame->p_buffer[i_offset + 1] );
2841
2842     if( tk->p_es_dv_audio && tk->i_dv_audio_rate != (int)fmt.audio.i_rate )
2843     {
2844         es_out_Del( p_demux->out, tk->p_es_dv_audio );
2845         tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2846     }
2847     else if( !tk->p_es_dv_audio )
2848     {
2849         tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2850     }
2851     tk->i_dv_audio_rate = fmt.audio.i_rate;
2852     es_format_Clean( &fmt );
2853
2854     block_t *p_frame_audio = dv_extract_audio( p_frame );
2855     if( p_frame_audio )
2856     {
2857         if( tk->p_es_dv_audio )
2858             es_out_Send( p_demux->out, tk->p_es_dv_audio, p_frame_audio );
2859         else
2860             block_Release( p_frame_audio );
2861     }
2862 }
2863
2864 /*****************************************************************************
2865  * Subtitles
2866  *****************************************************************************/
2867 static void AVI_ExtractSubtitle( demux_t *p_demux,
2868                                  unsigned int i_stream,
2869                                  avi_chunk_list_t *p_strl,
2870                                  avi_chunk_STRING_t *p_strn )
2871 {
2872     demux_sys_t *p_sys = p_demux->p_sys;
2873     block_t *p_block = NULL;
2874     input_attachment_t *p_attachment = NULL;
2875     char *psz_description = NULL;
2876     avi_chunk_indx_t *p_indx = NULL;
2877
2878     if( !p_sys->b_seekable )
2879         goto exit;
2880
2881     p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2882     avi_chunk_t ck;
2883     int64_t  i_position;
2884     unsigned i_size;
2885     if( p_indx )
2886     {
2887         if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES &&
2888             p_indx->i_entriesinuse > 0 )
2889         {
2890             if( vlc_stream_Seek( p_demux->s, p_indx->idx.super[0].i_offset ) ||
2891                 AVI_ChunkRead( p_demux->s, &ck, NULL  ) )
2892                 goto exit;
2893             p_indx = &ck.indx;
2894         }
2895
2896         if( p_indx->i_indextype != AVI_INDEX_OF_CHUNKS ||
2897             p_indx->i_entriesinuse != 1 ||
2898             p_indx->i_indexsubtype != 0 )
2899             goto exit;
2900
2901         i_position  = p_indx->i_baseoffset +
2902                       p_indx->idx.std[0].i_offset - 8;
2903         i_size      = (p_indx->idx.std[0].i_size & 0x7fffffff) + 8;
2904     }
2905     else
2906     {
2907         avi_chunk_idx1_t *p_idx1;
2908         uint64_t         i_offset;
2909
2910         if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2911             goto exit;
2912
2913         i_size = 0;
2914         for( unsigned i = 0; i < p_idx1->i_entry_count; i++ )
2915         {
2916             const idx1_entry_t *e = &p_idx1->entry[i];
2917             enum es_format_category_e i_cat;
2918             unsigned i_stream_idx;
2919
2920             AVI_ParseStreamHeader( e->i_fourcc, &i_stream_idx, &i_cat );
2921             if( i_cat == SPU_ES && i_stream_idx == i_stream )
2922             {
2923                 i_position = e->i_pos + i_offset;
2924                 i_size     = e->i_length + 8;
2925                 break;
2926             }
2927         }
2928         if( i_size <= 0 )
2929             goto exit;
2930     }
2931
2932     /* */
2933     if( i_size > 10000000 )
2934     {
2935         msg_Dbg( p_demux, "Attached subtitle too big: %u", i_size );
2936         goto exit;
2937     }
2938
2939     if( vlc_stream_Seek( p_demux->s, i_position ) )
2940         goto exit;
2941     p_block = vlc_stream_Block( p_demux->s, i_size );
2942     if( !p_block )
2943         goto exit;
2944
2945     /* Parse packet header */
2946     const uint8_t *p = p_block->p_buffer;
2947     if( i_size < 8 || p[2] != 't' || p[3] != 'x' )
2948         goto exit;
2949     p += 8;
2950     i_size -= 8;
2951
2952     /* Parse subtitle chunk header */
2953     if( i_size < 11 || memcmp( p, "GAB2", 4 ) ||
2954         p[4] != 0x00 || GetWLE( &p[5] ) != 0x2 )
2955         goto exit;
2956     const unsigned i_name = GetDWLE( &p[7] );
2957     if( 11 + i_size <= i_name )
2958         goto exit;
2959     if( i_name > 0 )
2960         psz_description = FromCharset( "UTF-16LE", &p[11], i_name );
2961     p += 11 + i_name;
2962     i_size -= 11 + i_name;
2963     if( i_size < 6 || GetWLE( &p[0] ) != 0x04 )
2964         goto exit;
2965     const unsigned i_payload = GetDWLE( &p[2] );
2966     if( i_size < 6 + i_payload || i_payload <= 0 )
2967         goto exit;
2968     p += 6;
2969     i_size -= 6;
2970
2971     if( !psz_description )
2972         psz_description = p_strn && p_strn->p_str ? FromACP( p_strn->p_str ) : NULL;
2973     char *psz_name;
2974     if( asprintf( &psz_name, "subtitle%d.srt", p_sys->i_attachment ) <= 0 )
2975         psz_name = NULL;
2976     p_attachment = vlc_input_attachment_New( psz_name,
2977                                              "application/x-srt",
2978                                              psz_description,
2979                                              p, i_payload );
2980     if( p_attachment )
2981         TAB_APPEND( p_sys->i_attachment, p_sys->attachment, p_attachment );
2982     free( psz_name );
2983
2984 exit:
2985     free( psz_description );
2986
2987     if( p_block )
2988         block_Release( p_block );
2989
2990     if( p_attachment )
2991         msg_Dbg( p_demux, "Loaded an embedded subtitle" );
2992     else
2993         msg_Warn( p_demux, "Failed to load an embedded subtitle" );
2994
2995     if( p_indx == &ck.indx )
2996         AVI_ChunkClean( p_demux->s, &ck );
2997 }
2998 /*****************************************************************************
2999  * Stream management
3000  *****************************************************************************/
3001 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
3002 {
3003     demux_sys_t *p_sys = p_demux->p_sys;
3004     unsigned int i;
3005     int b_end = true;
3006
3007     for( i = 0; i < p_sys->i_track; i++ )
3008     {
3009         avi_track_t *tk = p_sys->track[i];
3010         if( tk->i_idxposc >= tk->idx.i_size )
3011         {
3012             tk->b_eof = true;
3013         }
3014         else
3015         {
3016             b_end = false;
3017         }
3018     }
3019     return( b_end );
3020 }
3021
3022 /****************************************************************************
3023  * AVI_MovieGetLength give max streams length in second
3024  ****************************************************************************/
3025 static mtime_t  AVI_MovieGetLength( demux_t *p_demux )
3026 {
3027     demux_sys_t  *p_sys = p_demux->p_sys;
3028     mtime_t      i_maxlength = 0;
3029     unsigned int i;
3030
3031     for( i = 0; i < p_sys->i_track; i++ )
3032     {
3033         avi_track_t *tk = p_sys->track[i];
3034         mtime_t i_length;
3035
3036         /* fix length for each stream */
3037         if( tk->idx.i_size < 1 || !tk->idx.p_entry )
3038         {
3039             continue;
3040         }
3041
3042         if( tk->i_samplesize )
3043         {
3044             i_length = AVI_GetDPTS( tk,
3045                                     tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal +
3046                                         tk->idx.p_entry[tk->idx.i_size-1].i_length );
3047         }
3048         else
3049         {
3050             i_length = AVI_GetDPTS( tk, tk->idx.i_size );
3051         }
3052         i_length /= CLOCK_FREQ;    /* in seconds */
3053
3054         msg_Dbg( p_demux,
3055                  "stream[%d] length:%"PRId64" (based on index)",
3056                  i,
3057                  i_length );
3058         i_maxlength = __MAX( i_maxlength, i_length );
3059     }
3060
3061     return i_maxlength;
3062 }