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