425748af3c78245ab93f155e867281a632a3995d
[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                 switch( dialog_Question( p_demux, _("Broken or missing AVI Index") ,
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                       _( "Build index then play" ), _( "Play as is" ), _( "Do not play") ) )
764                 {
765                     case 1:
766                         b_index = true;
767                         msg_Dbg( p_demux, "Fixing AVI index" );
768                         goto aviindex;
769                     case 3:
770                         b_aborted = true;
771                         goto error;
772                 }
773             }
774             else
775             {
776                 b_index = true;
777                 msg_Dbg( p_demux, "Fixing AVI index" );
778                 goto aviindex;
779             }
780         }
781     }
782
783     /* fix some BeOS MediaKit generated file */
784     for( i = 0 ; i < p_sys->i_track; i++ )
785     {
786         avi_track_t         *tk = p_sys->track[i];
787         avi_chunk_list_t    *p_strl;
788         avi_chunk_strf_auds_t    *p_auds;
789
790         if( tk->i_cat != AUDIO_ES )
791         {
792             continue;
793         }
794         if( tk->idx.i_size < 1 ||
795             tk->i_scale != 1 ||
796             tk->i_samplesize != 0 )
797         {
798             continue;
799         }
800         p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
801         p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
802
803         if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
804             tk->i_rate == p_auds->p_wf->nSamplesPerSec )
805         {
806             int64_t i_track_length =
807                 tk->idx.p_entry[tk->idx.i_size-1].i_length +
808                 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal;
809             mtime_t i_length = (mtime_t)p_avih->i_totalframes *
810                                (mtime_t)p_avih->i_microsecperframe;
811
812             if( i_length == 0 )
813             {
814                 msg_Warn( p_demux, "track[%d] cannot be fixed (BeOS MediaKit generated)", i );
815                 continue;
816             }
817             tk->i_samplesize = 1;
818             tk->i_rate       = i_track_length  * CLOCK_FREQ / i_length;
819             msg_Warn( p_demux, "track[%d] fixed with rate=%d scale=%d (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
820         }
821     }
822
823     if( p_sys->b_seekable )
824     {
825         /* we have read all chunk so go back to movi */
826         stream_Seek( p_demux->s, p_movi->i_chunk_pos );
827     }
828     /* Skip movi header */
829     stream_Read( p_demux->s, NULL, 12 );
830
831     p_sys->i_movi_begin = p_movi->i_chunk_pos;
832     return VLC_SUCCESS;
833
834 error:
835     for( unsigned i = 0; i < p_sys->i_attachment; i++)
836         vlc_input_attachment_Delete(p_sys->attachment[i]);
837     free(p_sys->attachment);
838
839     if( p_sys->meta )
840         vlc_meta_Delete( p_sys->meta );
841
842     AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
843     free( p_sys );
844     return b_aborted ? VLC_ETIMEOUT : VLC_EGENERIC;
845 }
846
847 /*****************************************************************************
848  * Close: frees unused data
849  *****************************************************************************/
850 static void Close ( vlc_object_t * p_this )
851 {
852     demux_t *    p_demux = (demux_t *)p_this;
853     demux_sys_t *p_sys = p_demux->p_sys  ;
854
855     for( unsigned int i = 0; i < p_sys->i_track; i++ )
856     {
857         if( p_sys->track[i] )
858         {
859             avi_index_Clean( &p_sys->track[i]->idx );
860             free( p_sys->track[i] );
861         }
862     }
863     free( p_sys->track );
864
865     AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
866     vlc_meta_Delete( p_sys->meta );
867
868     for( unsigned i = 0; i < p_sys->i_attachment; i++)
869         vlc_input_attachment_Delete(p_sys->attachment[i]);
870     free(p_sys->attachment);
871
872     free( p_sys );
873 }
874
875 /*****************************************************************************
876  * ReadFrame: Reads frame, using stride if necessary
877  *****************************************************************************/
878
879 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
880                      const int i_header, const int i_size )
881 {
882     block_t *p_frame = stream_Block( p_demux->s, __EVEN( i_size ) );
883     if ( !p_frame ) return p_frame;
884
885     if( i_size % 2 )    /* read was padded on word boundary */
886     {
887         p_frame->i_buffer--;
888     }
889
890     /* skip header */
891     p_frame->p_buffer += i_header;
892     p_frame->i_buffer -= i_header;
893
894     if ( !tk->i_width_bytes )
895         return p_frame;
896
897     const unsigned int i_stride_bytes = ((( (tk->i_width_bytes << 3) + 31) & ~31) >> 3);
898
899     if ( p_frame->i_buffer < i_stride_bytes )
900     {
901         p_frame->i_buffer = 0;
902         return p_frame;
903     }
904
905     if( !tk->b_flipped )
906     {
907         const uint8_t *p_src = p_frame->p_buffer + i_stride_bytes;
908         const uint8_t *p_end = p_frame->p_buffer + p_frame->i_buffer;
909         uint8_t *p_dst = p_frame->p_buffer + tk->i_width_bytes;
910
911         p_frame->i_buffer = tk->i_width_bytes;
912
913         while ( p_src + i_stride_bytes <= p_end )
914         {
915             memmove( p_dst, p_src, tk->i_width_bytes );
916             p_src += i_stride_bytes;
917             p_dst += tk->i_width_bytes;
918             p_frame->i_buffer += tk->i_width_bytes;
919         }
920     }
921     else
922     {
923         block_t *p_flippedframe = block_Alloc( p_frame->i_buffer );
924         if ( !p_flippedframe )
925         {
926             block_Release( p_frame );
927             return NULL;
928         }
929
930         unsigned int i_lines = p_frame->i_buffer / i_stride_bytes;
931         const uint8_t *p_src = p_frame->p_buffer + i_lines * i_stride_bytes;
932         uint8_t *p_dst = p_flippedframe->p_buffer;
933
934         p_flippedframe->i_buffer = 0;
935
936         while ( i_lines-- > 0 )
937         {
938             p_src -= i_stride_bytes;
939             memcpy( p_dst, p_src, tk->i_width_bytes );
940             p_dst += tk->i_width_bytes;
941             p_flippedframe->i_buffer += tk->i_width_bytes;
942         }
943
944         block_Release( p_frame );
945         p_frame = p_flippedframe;
946     }
947
948     return p_frame;
949 }
950
951 /*****************************************************************************
952  * Demux_Seekable: reads and demuxes data packets for stream seekable
953  *****************************************************************************
954  * AVIDemux: reads and demuxes data packets
955  *****************************************************************************
956  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
957  *****************************************************************************/
958 typedef struct
959 {
960     bool b_ok;
961
962     int i_toread;
963
964     off_t i_posf; /* where we will read :
965                    if i_idxposb == 0 : begining of chunk (+8 to acces data)
966                    else : point on data directly */
967 } avi_track_toread_t;
968
969 static int Demux_Seekable( demux_t *p_demux )
970 {
971     demux_sys_t *p_sys = p_demux->p_sys;
972
973     unsigned int i_track_count = 0;
974     unsigned int i_track;
975     /* cannot be more than 100 stream (dcXX or wbXX) */
976     avi_track_toread_t toread[100];
977
978
979     /* detect new selected/unselected streams */
980     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
981     {
982         avi_track_t *tk = p_sys->track[i_track];
983         bool  b;
984
985         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
986         if( tk->p_es_dv_audio )
987         {
988             bool b_extra;
989             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
990             b |= b_extra;
991         }
992         if( b && !tk->b_activated )
993         {
994             if( p_sys->b_seekable)
995             {
996                 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
997             }
998             tk->b_activated = true;
999         }
1000         else if( !b && tk->b_activated )
1001         {
1002             tk->b_activated = false;
1003         }
1004         if( b )
1005         {
1006             i_track_count++;
1007         }
1008     }
1009
1010     if( i_track_count <= 0 )
1011     {
1012         int64_t i_length = p_sys->i_length * CLOCK_FREQ;
1013
1014         p_sys->i_time += p_sys->i_read_increment;
1015         if( i_length > 0 )
1016         {
1017             if( p_sys->i_time >= i_length )
1018                 return VLC_DEMUXER_EOF;
1019             return VLC_DEMUXER_SUCCESS;
1020         }
1021         msg_Warn( p_demux, "no track selected, exiting..." );
1022         return VLC_DEMUXER_EOF;
1023     }
1024
1025     /* wait for the good time */
1026     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1027     p_sys->i_time += p_sys->i_read_increment;
1028
1029     /* init toread */
1030     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1031     {
1032         avi_track_t *tk = p_sys->track[i_track];
1033
1034         toread[i_track].b_ok = tk->b_activated && !tk->b_eof;
1035         if( tk->i_idxposc < tk->idx.i_size )
1036         {
1037             toread[i_track].i_posf = tk->idx.p_entry[tk->i_idxposc].i_pos;
1038            if( tk->i_idxposb > 0 )
1039            {
1040                 toread[i_track].i_posf += 8 + tk->i_idxposb;
1041            }
1042         }
1043         else
1044         {
1045             toread[i_track].i_posf = -1;
1046         }
1047
1048         mtime_t i_dpts = p_sys->i_time - AVI_GetPTS( tk );
1049
1050         if( tk->i_samplesize )
1051         {
1052             toread[i_track].i_toread = AVI_PTSToByte( tk, i_dpts );
1053         }
1054         else if ( i_dpts > -2 * CLOCK_FREQ ) /* don't send a too early dts (low fps video) */
1055         {
1056             toread[i_track].i_toread = AVI_PTSToChunk( tk, i_dpts );
1057         }
1058         else
1059             toread[i_track].i_toread = -1;
1060     }
1061
1062     for( ;; )
1063     {
1064         avi_track_t     *tk;
1065         bool       b_done;
1066         block_t         *p_frame;
1067         off_t i_pos;
1068         unsigned int i;
1069         size_t i_size;
1070
1071         /* search for first chunk to be read */
1072         for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
1073         {
1074             if( !toread[i].b_ok ||
1075                 ( p_sys->b_fastseekable && p_sys->b_interleaved &&
1076                   AVI_GetDPTS( p_sys->track[i], toread[i].i_toread ) <= -p_sys->i_read_increment ) )
1077             {
1078                 continue;
1079             }
1080
1081             if( toread[i].i_toread >= 0 )
1082             {
1083                 b_done = false; /* not yet finished */
1084             }
1085             if( toread[i].i_posf > 0 )
1086             {
1087                 if( i_pos == -1 || i_pos > toread[i].i_posf )
1088                 {
1089                     i_track = i;
1090                     i_pos = toread[i].i_posf;
1091                 }
1092             }
1093         }
1094
1095         if( b_done )
1096         {
1097             for( i = 0; i < p_sys->i_track; i++ )
1098             {
1099                 if( toread[i].b_ok )
1100                     return VLC_DEMUXER_SUCCESS;
1101             }
1102             msg_Warn( p_demux, "all tracks have failed, exiting..." );
1103             return VLC_DEMUXER_EOF;
1104         }
1105
1106         if( i_pos == -1 )
1107         {
1108             int i_loop_count = 0;
1109
1110             /* no valid index, we will parse directly the stream
1111              * in case we fail we will disable all finished stream */
1112             if( p_sys->b_seekable && p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1113             {
1114                 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1115                 if( AVI_PacketNext( p_demux ) )
1116                 {
1117                     return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1118                 }
1119             }
1120             else
1121             {
1122                 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1123             }
1124
1125             for( ;; )
1126             {
1127                 avi_packet_t avi_pk;
1128
1129                 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1130                 {
1131                     msg_Warn( p_demux,
1132                              "cannot get packet header, track disabled" );
1133                     return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1134                 }
1135                 if( avi_pk.i_stream >= p_sys->i_track ||
1136                     ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1137                 {
1138                     if( AVI_PacketNext( p_demux ) )
1139                     {
1140                         msg_Warn( p_demux,
1141                                   "cannot skip packet, track disabled" );
1142                         return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1143                     }
1144
1145                     /* Prevents from eating all the CPU with broken files.
1146                      * This value should be low enough so that it doesn't
1147                      * affect the reading speed too much. */
1148                     if( !(++i_loop_count % 1024) )
1149                     {
1150                         msleep( 10000 );
1151
1152                         if( !(i_loop_count % (1024 * 10)) )
1153                             msg_Warn( p_demux,
1154                                       "don't seem to find any data..." );
1155                     }
1156                     continue;
1157                 }
1158                 else
1159                 {
1160                     i_track = avi_pk.i_stream;
1161                     tk = p_sys->track[i_track];
1162
1163                     /* add this chunk to the index */
1164                     avi_entry_t index;
1165                     index.i_id     = avi_pk.i_fourcc;
1166                     index.i_flags  = AVI_GetKeyFlag(tk->i_codec, avi_pk.i_peek);
1167                     index.i_pos    = avi_pk.i_pos;
1168                     index.i_length = avi_pk.i_size;
1169                     index.i_lengthtotal = index.i_length;
1170                     avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1171
1172                     /* do we will read this data ? */
1173                     if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -p_sys->i_read_increment )
1174                     {
1175                         break;
1176                     }
1177                     else
1178                     {
1179                         if( AVI_PacketNext( p_demux ) )
1180                         {
1181                             msg_Warn( p_demux,
1182                                       "cannot skip packet, track disabled" );
1183                             return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1184                         }
1185                     }
1186                 }
1187             }
1188
1189         }
1190         else
1191         {
1192             if( !p_sys->b_fastseekable && (i_pos > stream_Tell( p_demux->s )) )
1193             {
1194                 stream_Read( p_demux->s, NULL, i_pos - stream_Tell( p_demux->s ) );
1195             }
1196             else
1197             {
1198                 stream_Seek( p_demux->s, i_pos );
1199             }
1200         }
1201
1202         /* Set the track to use */
1203         tk = p_sys->track[i_track];
1204
1205         /* read thoses data */
1206         if( tk->i_samplesize )
1207         {
1208             unsigned int i_toread;
1209
1210             if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1211             {
1212                 if( tk->i_samplesize > 1 )
1213                 {
1214                     i_toread = tk->i_samplesize;
1215                 }
1216                 else
1217                 {
1218                     i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1219                     i_toread = __MAX( i_toread, 100 );
1220                 }
1221             }
1222             i_size = __MIN( tk->idx.p_entry[tk->i_idxposc].i_length -
1223                                 tk->i_idxposb,
1224                             i_toread );
1225         }
1226         else
1227         {
1228             i_size = tk->idx.p_entry[tk->i_idxposc].i_length;
1229         }
1230
1231         if( tk->i_idxposb == 0 )
1232         {
1233             i_size += 8; /* need to read and skip header */
1234         }
1235
1236         if( ( p_frame = ReadFrame( p_demux, tk,
1237                         ( tk->i_idxposb == 0 ) ? 8 : 0, i_size ) )==NULL )
1238         {
1239             msg_Warn( p_demux, "failed reading data" );
1240             tk->b_eof = false;
1241             toread[i_track].b_ok = false;
1242             continue;
1243         }
1244
1245         p_frame->i_pts = VLC_TS_0 + AVI_GetPTS( tk );
1246         if( tk->idx.p_entry[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1247         {
1248             p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1249         }
1250         else
1251         {
1252             p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1253         }
1254
1255         /* read data */
1256         if( tk->i_samplesize )
1257         {
1258             if( tk->i_idxposb == 0 )
1259             {
1260                 i_size -= 8;
1261             }
1262             toread[i_track].i_toread -= i_size;
1263             tk->i_idxposb += i_size;
1264             if( tk->i_idxposb >=
1265                     tk->idx.p_entry[tk->i_idxposc].i_length )
1266             {
1267                 tk->i_idxposb = 0;
1268                 tk->i_idxposc++;
1269             }
1270         }
1271         else
1272         {
1273             int i_length = tk->idx.p_entry[tk->i_idxposc].i_length;
1274
1275             tk->i_idxposc++;
1276             if( tk->i_cat == AUDIO_ES )
1277             {
1278                 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1279             }
1280             toread[i_track].i_toread--;
1281         }
1282
1283         if( tk->i_idxposc < tk->idx.i_size)
1284         {
1285             toread[i_track].i_posf =
1286                 tk->idx.p_entry[tk->i_idxposc].i_pos;
1287             if( tk->i_idxposb > 0 )
1288             {
1289                 toread[i_track].i_posf += 8 + tk->i_idxposb;
1290             }
1291
1292         }
1293         else
1294         {
1295             toread[i_track].i_posf = -1;
1296         }
1297
1298         if( tk->i_cat != VIDEO_ES )
1299             p_frame->i_dts = p_frame->i_pts;
1300         else
1301         {
1302             p_frame->i_dts = p_frame->i_pts;
1303             p_frame->i_pts = VLC_TS_INVALID;
1304         }
1305
1306         if( tk->i_dv_audio_rate )
1307             AVI_DvHandleAudio( p_demux, tk, p_frame );
1308         es_out_Send( p_demux->out, tk->p_es, p_frame );
1309     }
1310 }
1311
1312
1313 /*****************************************************************************
1314  * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1315  *****************************************************************************
1316  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1317  *****************************************************************************/
1318 static int Demux_UnSeekable( demux_t *p_demux )
1319 {
1320     demux_sys_t     *p_sys = p_demux->p_sys;
1321     avi_track_t *p_stream_master = NULL;
1322     unsigned int i_stream;
1323     unsigned int i_packet;
1324
1325     es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1326
1327     /* *** find master stream for data packet skipping algo *** */
1328     /* *** -> first video, if any, or first audio ES *** */
1329     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1330     {
1331         avi_track_t *tk = p_sys->track[i_stream];
1332         bool  b;
1333
1334         es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1335         if( tk->p_es_dv_audio )
1336         {
1337             bool b_extra;
1338             es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1339             b |= b_extra;
1340         }
1341
1342         if( b )
1343         {
1344             if( tk->i_cat == VIDEO_ES )
1345             {
1346                 p_stream_master = tk;
1347                 break;
1348             }
1349             else if( !p_stream_master )
1350             {
1351                 p_stream_master = tk;
1352             }
1353         }
1354     }
1355
1356     if( !p_stream_master )
1357     {
1358         if( p_sys->i_track )
1359         {
1360             p_stream_master = p_sys->track[0];
1361         }
1362         else
1363         {
1364             msg_Warn( p_demux, "no more stream selected" );
1365             return VLC_DEMUXER_EOF;
1366         }
1367     }
1368
1369     p_sys->i_time = AVI_GetPTS( p_stream_master );
1370
1371     for( i_packet = 0; i_packet < 10; i_packet++)
1372     {
1373 #define p_stream    p_sys->track[avi_pk.i_stream]
1374
1375         avi_packet_t    avi_pk;
1376
1377         if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1378         {
1379             return VLC_DEMUXER_EOF;
1380         }
1381
1382         if( avi_pk.i_stream >= p_sys->i_track ||
1383             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1384         {
1385             /* we haven't found an audio or video packet:
1386              *  - we have seek, found first next packet
1387              *  - others packets could be found, skip them
1388              */
1389             switch( avi_pk.i_fourcc )
1390             {
1391                 case AVIFOURCC_JUNK:
1392                 case AVIFOURCC_LIST:
1393                 case AVIFOURCC_RIFF:
1394                     return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1395                 case AVIFOURCC_idx1:
1396                     if( p_sys->b_odml )
1397                     {
1398                         return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1399                     }
1400                     return VLC_DEMUXER_EOF;
1401                 default:
1402                     msg_Warn( p_demux,
1403                               "seems to have lost position @%ld, resync", stream_Tell(p_demux->s) );
1404                     if( AVI_PacketSearch( p_demux ) )
1405                     {
1406                         msg_Err( p_demux, "resync failed" );
1407                         return VLC_DEMUXER_EGENERIC;
1408                     }
1409             }
1410         }
1411         else
1412         {
1413             /* check for time */
1414             if( p_stream == p_stream_master ||
1415                 llabs( AVI_GetPTS( p_stream ) -
1416                         AVI_GetPTS( p_stream_master ) )< 2 * CLOCK_FREQ )
1417             {
1418                 /* load it and send to decoder */
1419                 block_t *p_frame = ReadFrame( p_demux, p_stream, 8, avi_pk.i_size + 8 ) ;
1420                 if( p_frame == NULL )
1421                 {
1422                     return VLC_DEMUXER_EGENERIC;
1423                 }
1424                 p_frame->i_pts = VLC_TS_0 + AVI_GetPTS( p_stream );
1425
1426                 if( avi_pk.i_cat != VIDEO_ES )
1427                     p_frame->i_dts = p_frame->i_pts;
1428                 else
1429                 {
1430                     p_frame->i_dts = p_frame->i_pts;
1431                     p_frame->i_pts = VLC_TS_INVALID;
1432                 }
1433
1434                 if( p_stream->i_dv_audio_rate )
1435                     AVI_DvHandleAudio( p_demux, p_stream, p_frame );
1436                 es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1437             }
1438             else
1439             {
1440                 if( AVI_PacketNext( p_demux ) )
1441                 {
1442                     return VLC_DEMUXER_EOF;
1443                 }
1444             }
1445
1446             /* *** update stream time position *** */
1447             if( p_stream->i_samplesize )
1448             {
1449                 p_stream->i_idxposb += avi_pk.i_size;
1450             }
1451             else
1452             {
1453                 if( p_stream->i_cat == AUDIO_ES )
1454                 {
1455                     p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1456                 }
1457                 p_stream->i_idxposc++;
1458             }
1459
1460         }
1461 #undef p_stream
1462     }
1463
1464     return VLC_DEMUXER_SUCCESS;
1465 }
1466
1467 /*****************************************************************************
1468  * Seek: goto to i_date or i_percent
1469  *****************************************************************************/
1470 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1471 {
1472     demux_sys_t *p_sys = p_demux->p_sys;
1473     msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1474              i_date / CLOCK_FREQ, i_percent );
1475
1476     if( p_sys->b_seekable )
1477     {
1478         int64_t i_pos_backup = stream_Tell( p_demux->s );
1479
1480         /* Check and lazy load indexes if it was not done (not fastseekable) */
1481         if ( !p_sys->b_indexloaded && ( p_sys->i_avih_flags & AVIF_HASINDEX ) )
1482         {
1483             avi_chunk_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
1484             if (unlikely( !p_riff ))
1485                 return VLC_EGENERIC;
1486
1487             int i_ret = AVI_ChunkFetchIndexes( p_demux->s, p_riff );
1488             if ( i_ret )
1489             {
1490                 /* Go back to position before index failure */
1491                 if ( stream_Tell( p_demux->s ) - i_pos_backup )
1492                     stream_Seek( p_demux->s, i_pos_backup );
1493
1494                 if ( p_sys->i_avih_flags & AVIF_MUSTUSEINDEX )
1495                     return VLC_EGENERIC;
1496             }
1497             else AVI_IndexLoad( p_demux );
1498
1499             p_sys->b_indexloaded = true; /* we don't want to try each time */
1500         }
1501
1502         if( !p_sys->i_length )
1503         {
1504             avi_track_t *p_stream = NULL;
1505             unsigned i_stream = 0;
1506             int64_t i_pos;
1507
1508             if ( !p_sys->i_movi_lastchunk_pos && /* set when index is successfully loaded */
1509                  ! ( p_sys->i_avih_flags & AVIF_ISINTERLEAVED ) )
1510             {
1511                 msg_Err( p_demux, "seeking without index at %d%%"
1512                          " only works for interleaved files", i_percent );
1513                 goto failandresetpos;
1514             }
1515             /* use i_percent to create a true i_date */
1516             if( i_percent >= 100 )
1517             {
1518                 msg_Warn( p_demux, "cannot seek so far !" );
1519                 goto failandresetpos;
1520             }
1521             i_percent = __MAX( i_percent, 0 );
1522
1523             /* try to find chunk that is at i_percent or the file */
1524             i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1525                            p_sys->i_movi_begin );
1526             /* search first selected stream (and prefer non-EOF ones) */
1527             for( unsigned i = 0; i < p_sys->i_track; i++ )
1528             {
1529                 avi_track_t *p_track = p_sys->track[i];
1530                 if( !p_track->b_activated )
1531                     continue;
1532
1533                 p_stream = p_track;
1534                 i_stream = i;
1535                 if( !p_track->b_eof )
1536                     break;
1537             }
1538             if( p_stream == NULL )
1539             {
1540                 msg_Warn( p_demux, "cannot find any selected stream" );
1541                 goto failandresetpos;
1542             }
1543
1544             /* be sure that the index exist */
1545             if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1546             {
1547                 msg_Warn( p_demux, "cannot seek" );
1548                 goto failandresetpos;
1549             }
1550
1551             while( i_pos >= p_stream->idx.p_entry[p_stream->i_idxposc].i_pos +
1552                p_stream->idx.p_entry[p_stream->i_idxposc].i_length + 8 )
1553             {
1554                 /* search after i_idxposc */
1555                 if( AVI_StreamChunkSet( p_demux,
1556                                         i_stream, p_stream->i_idxposc + 1 ) )
1557                 {
1558                     msg_Warn( p_demux, "cannot seek" );
1559                     goto failandresetpos;
1560                 }
1561             }
1562
1563             i_date = AVI_GetPTS( p_stream );
1564             /* TODO better support for i_samplesize != 0 */
1565             msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1566         }
1567
1568         /* */
1569         for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1570         {
1571             avi_track_t *p_stream = p_sys->track[i_stream];
1572
1573             if( !p_stream->b_activated )
1574                 continue;
1575
1576             p_stream->b_eof = AVI_TrackSeek( p_demux, i_stream, i_date ) != 0;
1577         }
1578         p_sys->i_time = i_date;
1579         es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1580         es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + p_sys->i_time );
1581         msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /CLOCK_FREQ );
1582         return VLC_SUCCESS;
1583
1584 failandresetpos:
1585         /* Go back to position before index failure */
1586         if ( stream_Tell( p_demux->s ) - i_pos_backup )
1587             stream_Seek( p_demux->s, i_pos_backup );
1588
1589         return VLC_EGENERIC;
1590     }
1591     else
1592     {
1593         msg_Err( p_demux, "shouldn't yet be executed" );
1594         return VLC_EGENERIC;
1595     }
1596 }
1597
1598 /*****************************************************************************
1599  * Control:
1600  *****************************************************************************/
1601 static double ControlGetPosition( demux_t *p_demux )
1602 {
1603     demux_sys_t *p_sys = p_demux->p_sys;
1604
1605     if( p_sys->i_length > 0 )
1606     {
1607         return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)CLOCK_FREQ );
1608     }
1609     else if( stream_Size( p_demux->s ) > 0 )
1610     {
1611         double i64 = (uint64_t)stream_Tell( p_demux->s );
1612         return i64 / stream_Size( p_demux->s );
1613     }
1614     return 0.0;
1615 }
1616
1617 static int Control( demux_t *p_demux, int i_query, va_list args )
1618 {
1619     demux_sys_t *p_sys = p_demux->p_sys;
1620     int i;
1621     double   f, *pf;
1622     int64_t i64, *pi64;
1623     vlc_meta_t *p_meta;
1624
1625     switch( i_query )
1626     {
1627         case DEMUX_CAN_SEEK:
1628             *va_arg( args, bool * ) = p_sys->b_seekable;
1629             return VLC_SUCCESS;
1630
1631         case DEMUX_GET_POSITION:
1632             pf = (double*)va_arg( args, double * );
1633             *pf = ControlGetPosition( p_demux );
1634             return VLC_SUCCESS;
1635         case DEMUX_SET_POSITION:
1636             f = (double)va_arg( args, double );
1637             if ( !p_sys->b_seekable )
1638             {
1639                 return VLC_EGENERIC;
1640             }
1641             else
1642             {
1643                 i64 = (mtime_t)(f * CLOCK_FREQ * p_sys->i_length);
1644                 return Seek( p_demux, i64, (int)(f * 100) );
1645             }
1646
1647         case DEMUX_GET_TIME:
1648             pi64 = (int64_t*)va_arg( args, int64_t * );
1649             *pi64 = p_sys->i_time;
1650             return VLC_SUCCESS;
1651
1652         case DEMUX_SET_TIME:
1653         {
1654             int i_percent = 0;
1655
1656             i64 = (int64_t)va_arg( args, int64_t );
1657             if( !p_sys->b_seekable )
1658             {
1659                 return VLC_EGENERIC;
1660             }
1661             else if( p_sys->i_length > 0 )
1662             {
1663                 i_percent = 100 * i64 / (p_sys->i_length*CLOCK_FREQ);
1664             }
1665             else if( p_sys->i_time > 0 )
1666             {
1667                 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1668                                    (double)i64 / (double)p_sys->i_time );
1669             }
1670             return Seek( p_demux, i64, i_percent );
1671         }
1672         case DEMUX_GET_LENGTH:
1673             pi64 = (int64_t*)va_arg( args, int64_t * );
1674             *pi64 = p_sys->i_length * (mtime_t)CLOCK_FREQ;
1675             return VLC_SUCCESS;
1676
1677         case DEMUX_GET_FPS:
1678             pf = (double*)va_arg( args, double * );
1679             *pf = 0.0;
1680             for( i = 0; i < (int)p_sys->i_track; i++ )
1681             {
1682                 avi_track_t *tk = p_sys->track[i];
1683                 if( tk->i_cat == VIDEO_ES && tk->i_scale > 0)
1684                 {
1685                     *pf = (float)tk->i_rate / (float)tk->i_scale;
1686                     break;
1687                 }
1688             }
1689             return VLC_SUCCESS;
1690
1691         case DEMUX_GET_META:
1692             p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1693             vlc_meta_Merge( p_meta,  p_sys->meta );
1694             return VLC_SUCCESS;
1695
1696         case DEMUX_GET_ATTACHMENTS:
1697         {
1698             if( p_sys->i_attachment <= 0 )
1699                 return VLC_EGENERIC;
1700
1701             input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1702             int *pi_int = va_arg( args, int * );
1703
1704             *pi_int     = p_sys->i_attachment;
1705             *ppp_attach = calloc( p_sys->i_attachment, sizeof(**ppp_attach));
1706             for( unsigned i = 0; i < p_sys->i_attachment && *ppp_attach; i++ )
1707                 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachment[i] );
1708             return VLC_SUCCESS;
1709         }
1710
1711         default:
1712             return VLC_EGENERIC;
1713     }
1714 }
1715
1716 /*****************************************************************************
1717  * Function to convert pts to chunk or byte
1718  *****************************************************************************/
1719
1720 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1721 {
1722     if( !tk->i_scale )
1723         return (mtime_t)0;
1724
1725     return (mtime_t)((int64_t)i_pts *
1726                      (int64_t)tk->i_rate /
1727                      (int64_t)tk->i_scale /
1728                      (int64_t)CLOCK_FREQ );
1729 }
1730 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1731 {
1732     if( !tk->i_scale || !tk->i_samplesize )
1733         return (mtime_t)0;
1734
1735     return (mtime_t)((int64_t)i_pts *
1736                      (int64_t)tk->i_rate /
1737                      (int64_t)tk->i_scale /
1738                      (int64_t)1000000 *
1739                      (int64_t)tk->i_samplesize );
1740 }
1741
1742 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1743 {
1744     mtime_t i_dpts = 0;
1745
1746     if( !tk->i_rate )
1747         return i_dpts;
1748
1749     i_dpts = (mtime_t)( (int64_t)1000000 *
1750                         (int64_t)i_count *
1751                         (int64_t)tk->i_scale /
1752                         (int64_t)tk->i_rate );
1753
1754     if( tk->i_samplesize )
1755     {
1756         return i_dpts / tk->i_samplesize;
1757     }
1758     return i_dpts;
1759 }
1760
1761 static mtime_t AVI_GetPTS( avi_track_t *tk )
1762 {
1763     if( tk->i_samplesize )
1764     {
1765         int64_t i_count = 0;
1766
1767         /* we need a valid entry we will emulate one */
1768         if( tk->i_idxposc == tk->idx.i_size )
1769         {
1770             if( tk->i_idxposc )
1771             {
1772                 /* use the last entry */
1773                 i_count = tk->idx.p_entry[tk->idx.i_size - 1].i_lengthtotal
1774                             + tk->idx.p_entry[tk->idx.i_size - 1].i_length;
1775             }
1776         }
1777         else
1778         {
1779             i_count = tk->idx.p_entry[tk->i_idxposc].i_lengthtotal;
1780         }
1781         return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1782     }
1783     else
1784     {
1785         if( tk->i_cat == AUDIO_ES )
1786         {
1787             return AVI_GetDPTS( tk, tk->i_blockno );
1788         }
1789         else
1790         {
1791             return AVI_GetDPTS( tk, tk->i_idxposc );
1792         }
1793     }
1794 }
1795
1796 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1797 {
1798     demux_sys_t *p_sys = p_demux->p_sys;
1799     avi_packet_t avi_pk;
1800     int i_loop_count = 0;
1801
1802     /* find first chunk of i_stream that isn't in index */
1803
1804     if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1805     {
1806         stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1807         if( AVI_PacketNext( p_demux ) )
1808         {
1809             return VLC_EGENERIC;
1810         }
1811     }
1812     else
1813     {
1814         stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1815     }
1816
1817     for( ;; )
1818     {
1819         if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1820         {
1821             msg_Warn( p_demux, "cannot get packet header" );
1822             return VLC_EGENERIC;
1823         }
1824         if( avi_pk.i_stream >= p_sys->i_track ||
1825             ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1826         {
1827             if( AVI_PacketNext( p_demux ) )
1828             {
1829                 return VLC_EGENERIC;
1830             }
1831
1832             /* Prevents from eating all the CPU with broken files.
1833              * This value should be low enough so that it doesn't
1834              * affect the reading speed too much. */
1835             if( !(++i_loop_count % 1024) )
1836             {
1837                 msleep( 10000 );
1838
1839                 if( !(i_loop_count % (1024 * 10)) )
1840                     msg_Warn( p_demux, "don't seem to find any data..." );
1841             }
1842         }
1843         else
1844         {
1845             avi_track_t *tk_pk = p_sys->track[avi_pk.i_stream];
1846
1847             /* add this chunk to the index */
1848             avi_entry_t index;
1849             index.i_id     = avi_pk.i_fourcc;
1850             index.i_flags  = AVI_GetKeyFlag(tk_pk->i_codec, avi_pk.i_peek);
1851             index.i_pos    = avi_pk.i_pos;
1852             index.i_length = avi_pk.i_size;
1853             index.i_lengthtotal = index.i_length;
1854             avi_index_Append( &tk_pk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1855
1856             if( avi_pk.i_stream == i_stream  )
1857             {
1858                 return VLC_SUCCESS;
1859             }
1860
1861             if( AVI_PacketNext( p_demux ) )
1862             {
1863                 return VLC_EGENERIC;
1864             }
1865         }
1866     }
1867 }
1868
1869 /* be sure that i_ck will be a valid index entry */
1870 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1871                                unsigned int i_ck )
1872 {
1873     demux_sys_t *p_sys = p_demux->p_sys;
1874     avi_track_t *p_stream = p_sys->track[i_stream];
1875
1876     p_stream->i_idxposc = i_ck;
1877     p_stream->i_idxposb = 0;
1878
1879     if(  i_ck >= p_stream->idx.i_size )
1880     {
1881         p_stream->i_idxposc = p_stream->idx.i_size - 1;
1882         do
1883         {
1884             p_stream->i_idxposc++;
1885             if( AVI_StreamChunkFind( p_demux, i_stream ) )
1886             {
1887                 return VLC_EGENERIC;
1888             }
1889
1890         } while( p_stream->i_idxposc < i_ck );
1891     }
1892
1893     return VLC_SUCCESS;
1894 }
1895
1896 /* XXX FIXME up to now, we assume that all chunk are one after one */
1897 static int AVI_StreamBytesSet( demux_t    *p_demux,
1898                                unsigned int i_stream,
1899                                off_t   i_byte )
1900 {
1901     demux_sys_t *p_sys = p_demux->p_sys;
1902     avi_track_t *p_stream = p_sys->track[i_stream];
1903
1904     if( ( p_stream->idx.i_size > 0 )
1905         &&( i_byte < p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_lengthtotal +
1906                 p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_length ) )
1907     {
1908         /* index is valid to find the ck */
1909         /* uses dichototmie to be fast enougth */
1910         int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->idx.i_size - 1 );
1911         int i_idxmax  = p_stream->idx.i_size;
1912         int i_idxmin  = 0;
1913         for( ;; )
1914         {
1915             if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal > i_byte )
1916             {
1917                 i_idxmax  = i_idxposc ;
1918                 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1919             }
1920             else
1921             {
1922                 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal +
1923                         p_stream->idx.p_entry[i_idxposc].i_length <= i_byte)
1924                 {
1925                     i_idxmin  = i_idxposc ;
1926                     i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1927                 }
1928                 else
1929                 {
1930                     p_stream->i_idxposc = i_idxposc;
1931                     p_stream->i_idxposb = i_byte -
1932                             p_stream->idx.p_entry[i_idxposc].i_lengthtotal;
1933                     return VLC_SUCCESS;
1934                 }
1935             }
1936         }
1937
1938     }
1939     else
1940     {
1941         p_stream->i_idxposc = p_stream->idx.i_size - 1;
1942         p_stream->i_idxposb = 0;
1943         do
1944         {
1945             p_stream->i_idxposc++;
1946             if( AVI_StreamChunkFind( p_demux, i_stream ) )
1947             {
1948                 return VLC_EGENERIC;
1949             }
1950
1951         } while( p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal +
1952                     p_stream->idx.p_entry[p_stream->i_idxposc].i_length <= i_byte );
1953
1954         p_stream->i_idxposb = i_byte -
1955                        p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal;
1956         return VLC_SUCCESS;
1957     }
1958 }
1959
1960 static int AVI_TrackSeek( demux_t *p_demux,
1961                            int i_stream,
1962                            mtime_t i_date )
1963 {
1964     demux_sys_t  *p_sys = p_demux->p_sys;
1965     avi_track_t  *tk = p_sys->track[i_stream];
1966
1967 #define p_stream    p_sys->track[i_stream]
1968     mtime_t i_oldpts;
1969
1970     i_oldpts = AVI_GetPTS( p_stream );
1971
1972     if( !p_stream->i_samplesize )
1973     {
1974         if( AVI_StreamChunkSet( p_demux,
1975                                 i_stream,
1976                                 AVI_PTSToChunk( p_stream, i_date ) ) )
1977         {
1978             return VLC_EGENERIC;
1979         }
1980
1981         if( p_stream->i_cat == AUDIO_ES )
1982         {
1983             unsigned int i;
1984             tk->i_blockno = 0;
1985             for( i = 0; i < tk->i_idxposc; i++ )
1986             {
1987                 if( tk->i_blocksize > 0 )
1988                 {
1989                     tk->i_blockno += ( tk->idx.p_entry[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
1990                 }
1991                 else
1992                 {
1993                     tk->i_blockno++;
1994                 }
1995             }
1996         }
1997
1998         msg_Dbg( p_demux,
1999                  "old:%"PRId64" %s new %"PRId64,
2000                  i_oldpts,
2001                  i_oldpts > i_date ? ">" : "<",
2002                  i_date );
2003
2004         if( p_stream->i_cat == VIDEO_ES )
2005         {
2006             /* search key frame */
2007             //if( i_date < i_oldpts || 1 )
2008             {
2009                 while( p_stream->i_idxposc > 0 &&
2010                    !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
2011                                                                 AVIIF_KEYFRAME ) )
2012                 {
2013                     if( AVI_StreamChunkSet( p_demux,
2014                                             i_stream,
2015                                             p_stream->i_idxposc - 1 ) )
2016                     {
2017                         return VLC_EGENERIC;
2018                     }
2019                 }
2020             }
2021 #if 0
2022             else
2023             {
2024                 while( p_stream->i_idxposc < p_stream->idx.i_size &&
2025                         !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
2026                                                                 AVIIF_KEYFRAME ) )
2027                 {
2028                     if( AVI_StreamChunkSet( p_demux,
2029                                             i_stream,
2030                                             p_stream->i_idxposc + 1 ) )
2031                     {
2032                         return VLC_EGENERIC;
2033                     }
2034                 }
2035             }
2036 #endif
2037         }
2038     }
2039     else
2040     {
2041         if( AVI_StreamBytesSet( p_demux,
2042                                 i_stream,
2043                                 AVI_PTSToByte( p_stream, i_date ) ) )
2044         {
2045             return VLC_EGENERIC;
2046         }
2047     }
2048     return VLC_SUCCESS;
2049 #undef p_stream
2050 }
2051
2052 /****************************************************************************
2053  * Return true if it's a key frame
2054  ****************************************************************************/
2055 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
2056 {
2057     switch( i_fourcc )
2058     {
2059         case VLC_CODEC_DIV1:
2060             /* we have:
2061              *  startcode:      0x00000100   32bits
2062              *  framenumber     ?             5bits
2063              *  piture type     0(I),1(P)     2bits
2064              */
2065             if( GetDWBE( p_byte ) != 0x00000100 )
2066             {
2067                 /* it's not an msmpegv1 stream, strange...*/
2068                 return AVIIF_KEYFRAME;
2069             }
2070             return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
2071
2072         case VLC_CODEC_DIV2:
2073         case VLC_CODEC_DIV3:
2074         case VLC_CODEC_WMV1:
2075             /* we have
2076              *  picture type    0(I),1(P)     2bits
2077              */
2078             return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2079         case VLC_CODEC_MP4V:
2080             /* we should find first occurrence of 0x000001b6 (32bits)
2081              *  startcode:      0x000001b6   32bits
2082              *  piture type     0(I),1(P)     2bits
2083              */
2084             if( GetDWBE( p_byte ) != 0x000001b6 )
2085             {
2086                 /* not true , need to find the first VOP header */
2087                 return AVIIF_KEYFRAME;
2088             }
2089             return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2090
2091         default:
2092             /* I can't do it, so say yes */
2093             return AVIIF_KEYFRAME;
2094     }
2095 }
2096
2097 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
2098 {
2099     switch( i_cat )
2100     {
2101         case AUDIO_ES:
2102             wf_tag_to_fourcc( i_codec, &i_codec, NULL );
2103             return i_codec;
2104         case VIDEO_ES:
2105             return vlc_fourcc_GetCodec( i_cat, i_codec );
2106         default:
2107             return VLC_FOURCC( 'u', 'n', 'd', 'f' );
2108     }
2109 }
2110
2111 /****************************************************************************
2112  *
2113  ****************************************************************************/
2114 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
2115                                    unsigned int *pi_number, unsigned int *pi_type )
2116 {
2117 #define SET_PTR( p, v ) if( p ) *(p) = (v);
2118     int c1, c2;
2119
2120     c1 = ((uint8_t *)&i_id)[0];
2121     c2 = ((uint8_t *)&i_id)[1];
2122
2123     if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
2124     {
2125         SET_PTR( pi_number, 100 ); /* > max stream number */
2126         SET_PTR( pi_type, UNKNOWN_ES );
2127     }
2128     else
2129     {
2130         SET_PTR( pi_number, (c1 - '0') * 10 + (c2 - '0' ) );
2131         switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
2132         {
2133             case AVITWOCC_wb:
2134                 SET_PTR( pi_type, AUDIO_ES );
2135                 break;
2136             case AVITWOCC_dc:
2137             case AVITWOCC_db:
2138             case AVITWOCC_AC:
2139                 SET_PTR( pi_type, VIDEO_ES );
2140                 break;
2141             case AVITWOCC_tx:
2142             case AVITWOCC_sb:
2143                 SET_PTR( pi_type, SPU_ES );
2144                 break;
2145             case AVITWOCC_pc:
2146                 SET_PTR( pi_type, IGNORE_ES );
2147                 break;
2148             default:
2149                 SET_PTR( pi_type, UNKNOWN_ES );
2150                 break;
2151         }
2152     }
2153 #undef SET_PTR
2154 }
2155
2156 /****************************************************************************
2157  *
2158  ****************************************************************************/
2159 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
2160 {
2161     const uint8_t *p_peek;
2162
2163     if( stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
2164     {
2165         return VLC_EGENERIC;
2166     }
2167     p_pk->i_fourcc  = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
2168     p_pk->i_size    = GetDWLE( p_peek + 4 );
2169     p_pk->i_pos     = stream_Tell( p_demux->s );
2170     if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
2171     {
2172         p_pk->i_type = VLC_FOURCC( p_peek[8],  p_peek[9],
2173                                    p_peek[10], p_peek[11] );
2174     }
2175     else
2176     {
2177         p_pk->i_type = 0;
2178     }
2179
2180     memcpy( p_pk->i_peek, p_peek + 8, 8 );
2181
2182     AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
2183     return VLC_SUCCESS;
2184 }
2185
2186 static int AVI_PacketNext( demux_t *p_demux )
2187 {
2188     avi_packet_t    avi_ck;
2189     int             i_skip = 0;
2190
2191     if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2192     {
2193         return VLC_EGENERIC;
2194     }
2195
2196     if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2197         ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2198     {
2199         i_skip = 12;
2200     }
2201     else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2202              avi_ck.i_type == AVIFOURCC_AVIX )
2203     {
2204         i_skip = 24;
2205     }
2206     else
2207     {
2208         i_skip = __EVEN( avi_ck.i_size ) + 8;
2209     }
2210
2211     if( stream_Read( p_demux->s, NULL, i_skip ) != i_skip )
2212     {
2213         return VLC_EGENERIC;
2214     }
2215     return VLC_SUCCESS;
2216 }
2217
2218 static int AVI_PacketRead( demux_t   *p_demux,
2219                            avi_packet_t     *p_pk,
2220                            block_t          **pp_frame )
2221 {
2222     size_t i_size;
2223
2224     i_size = __EVEN( p_pk->i_size + 8 );
2225
2226     if( ( *pp_frame = stream_Block( p_demux->s, i_size ) ) == NULL )
2227     {
2228         return VLC_EGENERIC;
2229     }
2230     (*pp_frame)->p_buffer += 8;
2231     (*pp_frame)->i_buffer -= 8;
2232
2233     if( i_size != p_pk->i_size + 8 )
2234     {
2235         (*pp_frame)->i_buffer--;
2236     }
2237
2238     return VLC_SUCCESS;
2239 }
2240
2241 static int AVI_PacketSearch( demux_t *p_demux )
2242 {
2243     demux_sys_t     *p_sys = p_demux->p_sys;
2244     avi_packet_t    avi_pk;
2245     int             i_count = 0;
2246
2247     for( ;; )
2248     {
2249         if( stream_Read( p_demux->s, NULL, 1 ) != 1 )
2250         {
2251             return VLC_EGENERIC;
2252         }
2253         AVI_PacketGetHeader( p_demux, &avi_pk );
2254         if( avi_pk.i_stream < p_sys->i_track &&
2255             ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2256         {
2257             return VLC_SUCCESS;
2258         }
2259         switch( avi_pk.i_fourcc )
2260         {
2261             case AVIFOURCC_JUNK:
2262             case AVIFOURCC_LIST:
2263             case AVIFOURCC_RIFF:
2264             case AVIFOURCC_idx1:
2265                 return VLC_SUCCESS;
2266         }
2267
2268         /* Prevents from eating all the CPU with broken files.
2269          * This value should be low enough so that it doesn't affect the
2270          * reading speed too much (not that we care much anyway because
2271          * this code is called only on broken files). */
2272         if( !(++i_count % 1024) )
2273         {
2274             msleep( 10000 );
2275             if( !(i_count % (1024 * 10)) )
2276                 msg_Warn( p_demux, "trying to resync..." );
2277         }
2278     }
2279 }
2280
2281 /****************************************************************************
2282  * Index stuff.
2283  ****************************************************************************/
2284 static void avi_index_Init( avi_index_t *p_index )
2285 {
2286     p_index->i_size  = 0;
2287     p_index->i_max   = 0;
2288     p_index->p_entry = NULL;
2289 }
2290 static void avi_index_Clean( avi_index_t *p_index )
2291 {
2292     free( p_index->p_entry );
2293 }
2294 static void avi_index_Append( avi_index_t *p_index, off_t *pi_last_pos,
2295                               avi_entry_t *p_entry )
2296 {
2297     /* Update last chunk position */
2298     if( *pi_last_pos < p_entry->i_pos )
2299          *pi_last_pos = p_entry->i_pos;
2300
2301     /* add the entry */
2302     if( p_index->i_size >= p_index->i_max )
2303     {
2304         p_index->i_max += 16384;
2305         p_index->p_entry = realloc_or_free( p_index->p_entry,
2306                                             p_index->i_max * sizeof( *p_index->p_entry ) );
2307         if( !p_index->p_entry )
2308             return;
2309     }
2310     /* calculate cumulate length */
2311     if( p_index->i_size > 0 )
2312     {
2313         p_entry->i_lengthtotal =
2314             p_index->p_entry[p_index->i_size - 1].i_length +
2315                 p_index->p_entry[p_index->i_size - 1].i_lengthtotal;
2316     }
2317     else
2318     {
2319         p_entry->i_lengthtotal = 0;
2320     }
2321
2322     p_index->p_entry[p_index->i_size++] = *p_entry;
2323 }
2324
2325 static int AVI_IndexFind_idx1( demux_t *p_demux,
2326                                avi_chunk_idx1_t **pp_idx1,
2327                                uint64_t *pi_offset )
2328 {
2329     demux_sys_t *p_sys = p_demux->p_sys;
2330
2331     avi_chunk_list_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2332     avi_chunk_idx1_t *p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2333
2334     if( !p_idx1 )
2335     {
2336         msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2337         return VLC_EGENERIC;
2338     }
2339     *pp_idx1 = p_idx1;
2340
2341     /* The offset in the index should be from the start of the movi content,
2342      * but some broken files use offset from the start of the file. Just
2343      * checking the offset of the first packet is not enough as some files
2344      * has unused chunk at the beginning of the movi content.
2345      */
2346     avi_chunk_list_t *p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2347     uint64_t i_first_pos = UINT64_MAX;
2348     for( unsigned i = 0; i < __MIN( p_idx1->i_entry_count, 100 ); i++ )
2349     {
2350         if ( p_idx1->entry[i].i_length > 0 )
2351             i_first_pos = __MIN( i_first_pos, p_idx1->entry[i].i_pos );
2352     }
2353
2354     const uint64_t i_movi_content = p_movi->i_chunk_pos + 8;
2355     if( i_first_pos < i_movi_content )
2356     {
2357         *pi_offset = i_movi_content;
2358     }
2359     else if( p_sys->b_seekable && i_first_pos < UINT64_MAX )
2360     {
2361         const uint8_t *p_peek;
2362         if( !stream_Seek( p_demux->s, i_movi_content + i_first_pos ) &&
2363             stream_Peek( p_demux->s, &p_peek, 4 ) >= 4 &&
2364             ( !isdigit( p_peek[0] ) || !isdigit( p_peek[1] ) ||
2365               !isalpha( p_peek[2] ) || !isalpha( p_peek[3] ) ) )
2366             *pi_offset = 0;
2367         else
2368             *pi_offset = i_movi_content;
2369
2370         if( p_idx1->i_entry_count )
2371         {
2372             /* Invalidate offset if index refers past the data section to avoid false
2373                positives when the offset equals sample size */
2374             size_t i_dataend = *pi_offset + p_idx1->entry[p_idx1->i_entry_count - 1].i_pos +
2375                                             p_idx1->entry[p_idx1->i_entry_count - 1].i_length;
2376             if( i_dataend > p_movi->i_chunk_pos + p_movi->i_chunk_size )
2377                 *pi_offset = 0;
2378         }
2379     }
2380     else
2381     {
2382         *pi_offset = 0;
2383     }
2384
2385     return VLC_SUCCESS;
2386 }
2387
2388 static int AVI_IndexLoad_idx1( demux_t *p_demux,
2389                                avi_index_t p_index[], off_t *pi_last_offset )
2390 {
2391     demux_sys_t *p_sys = p_demux->p_sys;
2392
2393     avi_chunk_idx1_t *p_idx1;
2394     uint64_t         i_offset;
2395     if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2396         return VLC_EGENERIC;
2397
2398     p_sys->b_indexloaded = true;
2399
2400     for( unsigned i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2401     {
2402         unsigned i_cat;
2403         unsigned i_stream;
2404
2405         AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2406                                &i_stream,
2407                                &i_cat );
2408         if( i_stream < p_sys->i_track &&
2409             (i_cat == p_sys->track[i_stream]->i_cat || i_cat == UNKNOWN_ES ) )
2410         {
2411             avi_entry_t index;
2412             index.i_id     = p_idx1->entry[i_index].i_fourcc;
2413             index.i_flags  = p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2414             index.i_pos    = p_idx1->entry[i_index].i_pos + i_offset;
2415             index.i_length = p_idx1->entry[i_index].i_length;
2416             index.i_lengthtotal = index.i_length;
2417
2418             avi_index_Append( &p_index[i_stream], pi_last_offset, &index );
2419         }
2420     }
2421
2422 #ifdef AVI_DEBUG
2423     for( unsigned i_index = 0; i_index< p_idx1->i_entry_count && i_index < p_sys->i_track; i_index++ )
2424     {
2425         for( unsigned i = 0; i < p_index[i_index].i_size; i++ )
2426         {
2427             mtime_t i_length;
2428             if( p_sys->track[i_index]->i_samplesize )
2429             {
2430                 i_length = AVI_GetDPTS( p_sys->track[i_index],
2431                                         p_index[i_index].p_entry[i].i_lengthtotal );
2432             }
2433             else
2434             {
2435                 i_length = AVI_GetDPTS( p_sys->track[i_index], i );
2436             }
2437             msg_Dbg( p_demux, "index stream %d @%ld time %ld", i_index,
2438                      p_index[i_index].p_entry[i].i_pos, i_length );
2439         }
2440     }
2441 #endif
2442     return VLC_SUCCESS;
2443 }
2444
2445 static void __Parse_indx( demux_t *p_demux, avi_index_t *p_index, off_t *pi_max_offset,
2446                           avi_chunk_indx_t *p_indx )
2447 {
2448     avi_entry_t index;
2449
2450     p_demux->p_sys->b_indexloaded = true;
2451
2452     msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2453     if( p_indx->i_indexsubtype == 0 )
2454     {
2455         for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2456         {
2457             index.i_id     = p_indx->i_id;
2458             index.i_flags  = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2459             index.i_pos    = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2460             index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2461             index.i_lengthtotal = index.i_length;
2462
2463             avi_index_Append( p_index, pi_max_offset, &index );
2464         }
2465     }
2466     else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2467     {
2468         for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2469         {
2470             index.i_id     = p_indx->i_id;
2471             index.i_flags  = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2472             index.i_pos    = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2473             index.i_length = p_indx->idx.field[i].i_size;
2474             index.i_lengthtotal = index.i_length;
2475
2476             avi_index_Append( p_index, pi_max_offset, &index );
2477         }
2478     }
2479     else
2480     {
2481         msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2482     }
2483 }
2484
2485 static void AVI_IndexLoad_indx( demux_t *p_demux,
2486                                 avi_index_t p_index[], off_t *pi_last_offset )
2487 {
2488     demux_sys_t         *p_sys = p_demux->p_sys;
2489
2490     avi_chunk_list_t    *p_riff;
2491     avi_chunk_list_t    *p_hdrl;
2492
2493     p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2494     p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2495
2496     for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2497     {
2498         avi_chunk_list_t    *p_strl;
2499         avi_chunk_indx_t    *p_indx;
2500
2501 #define p_stream  p_sys->track[i_stream]
2502         p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2503         p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2504
2505         if( !p_indx )
2506         {
2507             if( p_sys->b_odml )
2508                 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2509                                    "file?)" );
2510             continue;
2511         }
2512
2513         if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2514         {
2515             __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, p_indx );
2516         }
2517         else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2518         {
2519             if ( !p_sys->b_seekable )
2520                 return;
2521             avi_chunk_t    ck_sub;
2522             for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2523             {
2524                 if( stream_Seek( p_demux->s, p_indx->idx.super[i].i_offset )||
2525                     AVI_ChunkRead( p_demux->s, &ck_sub, NULL  ) )
2526                 {
2527                     break;
2528                 }
2529                 if( ck_sub.indx.i_indextype == AVI_INDEX_OF_CHUNKS )
2530                     __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, &ck_sub.indx );
2531                 AVI_ChunkFree( p_demux->s, &ck_sub );
2532             }
2533         }
2534         else
2535         {
2536             msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2537         }
2538 #undef p_stream
2539     }
2540 }
2541
2542 static void AVI_IndexLoad( demux_t *p_demux )
2543 {
2544     demux_sys_t *p_sys = p_demux->p_sys;
2545
2546     /* Load indexes */
2547     assert( p_sys->i_track <= 100 );
2548     avi_index_t p_idx_indx[p_sys->i_track];
2549     avi_index_t p_idx_idx1[p_sys->i_track];
2550     for( unsigned i = 0; i < p_sys->i_track; i++ )
2551     {
2552         avi_index_Init( &p_idx_indx[i] );
2553         avi_index_Init( &p_idx_idx1[i] );
2554     }
2555     off_t i_indx_last_pos = p_sys->i_movi_lastchunk_pos;
2556     off_t i_idx1_last_pos = p_sys->i_movi_lastchunk_pos;
2557
2558     AVI_IndexLoad_indx( p_demux, p_idx_indx, &i_indx_last_pos );
2559     if( !p_sys->b_odml )
2560         AVI_IndexLoad_idx1( p_demux, p_idx_idx1, &i_idx1_last_pos );
2561
2562     /* Select the longest index */
2563     for( unsigned i = 0; i < p_sys->i_track; i++ )
2564     {
2565         if( p_idx_indx[i].i_size > p_idx_idx1[i].i_size )
2566         {
2567             msg_Dbg( p_demux, "selected ODML index for stream[%u]", i );
2568             p_sys->track[i]->idx = p_idx_indx[i];
2569             avi_index_Clean( &p_idx_idx1[i] );
2570         }
2571         else
2572         {
2573             msg_Dbg( p_demux, "selected standard index for stream[%u]", i );
2574             p_sys->track[i]->idx = p_idx_idx1[i];
2575             avi_index_Clean( &p_idx_indx[i] );
2576         }
2577     }
2578     p_sys->i_movi_lastchunk_pos = __MAX( i_indx_last_pos, i_idx1_last_pos );
2579
2580     for( unsigned i = 0; i < p_sys->i_track; i++ )
2581     {
2582         avi_index_t *p_index = &p_sys->track[i]->idx;
2583
2584         /* Fix key flag */
2585         bool b_key = false;
2586         for( unsigned j = 0; !b_key && j < p_index->i_size; j++ )
2587             b_key = p_index->p_entry[j].i_flags & AVIIF_KEYFRAME;
2588         if( !b_key )
2589         {
2590             msg_Err( p_demux, "no key frame set for track %u", i );
2591             for( unsigned j = 0; j < p_index->i_size; j++ )
2592                 p_index->p_entry[j].i_flags |= AVIIF_KEYFRAME;
2593         }
2594
2595         /* */
2596         msg_Dbg( p_demux, "stream[%d] created %d index entries",
2597                  i, p_index->i_size );
2598     }
2599 }
2600
2601 static void AVI_IndexCreate( demux_t *p_demux )
2602 {
2603     demux_sys_t *p_sys = p_demux->p_sys;
2604
2605     avi_chunk_list_t *p_riff;
2606     avi_chunk_list_t *p_movi;
2607
2608     unsigned int i_stream;
2609     off_t i_movi_end;
2610
2611     mtime_t i_dialog_update;
2612     dialog_progress_bar_t *p_dialog = NULL;
2613
2614     p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2615     p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2616
2617     if( !p_movi )
2618     {
2619         msg_Err( p_demux, "cannot find p_movi" );
2620         return;
2621     }
2622
2623     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2624         avi_index_Init( &p_sys->track[i_stream]->idx );
2625
2626     i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2627                         stream_Size( p_demux->s ) );
2628
2629     stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2630     msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2631
2632
2633     /* Only show dialog if AVI is > 10MB */
2634     i_dialog_update = mdate();
2635     if( stream_Size( p_demux->s ) > 10000000 )
2636         p_dialog = dialog_ProgressCreate( p_demux, _("Fixing AVI Index..."),
2637                                        NULL, _("Cancel") );
2638
2639     for( ;; )
2640     {
2641         avi_packet_t pk;
2642
2643         /* Don't update/check dialog too often */
2644         if( p_dialog && mdate() - i_dialog_update > 100000 )
2645         {
2646             if( dialog_ProgressCancelled( p_dialog ) )
2647                 break;
2648
2649             double f_current = stream_Tell( p_demux->s );
2650             double f_size    = stream_Size( p_demux->s );
2651             double f_pos     = f_current / f_size;
2652             dialog_ProgressSet( p_dialog, NULL, f_pos );
2653
2654             i_dialog_update = mdate();
2655         }
2656
2657         if( AVI_PacketGetHeader( p_demux, &pk ) )
2658             break;
2659
2660         if( pk.i_stream < p_sys->i_track &&
2661             pk.i_cat == p_sys->track[pk.i_stream]->i_cat )
2662         {
2663             avi_track_t *tk = p_sys->track[pk.i_stream];
2664
2665             avi_entry_t index;
2666             index.i_id      = pk.i_fourcc;
2667             index.i_flags   = AVI_GetKeyFlag(tk->i_codec, pk.i_peek);
2668             index.i_pos     = pk.i_pos;
2669             index.i_length  = pk.i_size;
2670             index.i_lengthtotal = pk.i_size;
2671             avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
2672         }
2673         else
2674         {
2675             switch( pk.i_fourcc )
2676             {
2677             case AVIFOURCC_idx1:
2678                 if( p_sys->b_odml )
2679                 {
2680                     avi_chunk_list_t *p_sysx;
2681                     p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2682                                             AVIFOURCC_RIFF, 1 );
2683
2684                     msg_Dbg( p_demux, "looking for new RIFF chunk" );
2685                     if( stream_Seek( p_demux->s, p_sysx->i_chunk_pos + 24 ) )
2686                         goto print_stat;
2687                     break;
2688                 }
2689                 goto print_stat;
2690
2691             case AVIFOURCC_RIFF:
2692                     msg_Dbg( p_demux, "new RIFF chunk found" );
2693                     break;
2694
2695             case AVIFOURCC_rec:
2696             case AVIFOURCC_JUNK:
2697                 break;
2698
2699             default:
2700                 msg_Warn( p_demux, "need resync, probably broken avi" );
2701                 if( AVI_PacketSearch( p_demux ) )
2702                 {
2703                     msg_Warn( p_demux, "lost sync, abord index creation" );
2704                     goto print_stat;
2705                 }
2706             }
2707         }
2708
2709         if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2710             AVI_PacketNext( p_demux ) )
2711         {
2712             break;
2713         }
2714     }
2715
2716 print_stat:
2717     if( p_dialog != NULL )
2718         dialog_ProgressDestroy( p_dialog );
2719
2720     for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2721     {
2722         msg_Dbg( p_demux, "stream[%d] creating %d index entries",
2723                 i_stream, p_sys->track[i_stream]->idx.i_size );
2724     }
2725 }
2726
2727 /* */
2728 static void AVI_MetaLoad( demux_t *p_demux,
2729                           avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih )
2730 {
2731     demux_sys_t *p_sys = p_demux->p_sys;
2732
2733     vlc_meta_t *p_meta = p_sys->meta = vlc_meta_New();
2734     if( !p_meta )
2735         return;
2736
2737     char buffer[200];
2738     snprintf( buffer, sizeof(buffer), "%s%s%s%s",
2739               p_avih->i_flags&AVIF_HASINDEX      ? " HAS_INDEX"      : "",
2740               p_avih->i_flags&AVIF_MUSTUSEINDEX  ? " MUST_USE_INDEX" : "",
2741               p_avih->i_flags&AVIF_ISINTERLEAVED ? " IS_INTERLEAVED" : "",
2742               p_avih->i_flags&AVIF_TRUSTCKTYPE   ? " TRUST_CKTYPE"   : "" );
2743     vlc_meta_SetSetting( p_meta, buffer );
2744
2745     avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
2746     if( !p_info )
2747         return;
2748
2749     static const struct {
2750         vlc_fourcc_t i_id;
2751         int          i_type;
2752     } p_dsc[] = {
2753         { AVIFOURCC_IART, vlc_meta_Artist },
2754         { AVIFOURCC_ICMT, vlc_meta_Description },
2755         { AVIFOURCC_ICOP, vlc_meta_Copyright },
2756         { AVIFOURCC_IGNR, vlc_meta_Genre },
2757         { AVIFOURCC_INAM, vlc_meta_Title },
2758         { AVIFOURCC_ICRD, vlc_meta_Date },
2759         { AVIFOURCC_ILNG, vlc_meta_Language },
2760         { AVIFOURCC_IRTD, vlc_meta_Rating },
2761         { AVIFOURCC_IWEB, vlc_meta_URL },
2762         { AVIFOURCC_IPRT, vlc_meta_TrackNumber },
2763         { AVIFOURCC_IFRM, vlc_meta_TrackTotal },
2764         { 0, -1 }
2765     };
2766     for( int i = 0; p_dsc[i].i_id != 0; i++ )
2767     {
2768         avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_dsc[i].i_id, 0 );
2769         if( !p_strz )
2770             continue;
2771         char *psz_value = FromACP( p_strz->p_str );
2772         if( !psz_value )
2773             continue;
2774
2775         if( *psz_value )
2776             vlc_meta_Set( p_meta, p_dsc[i].i_type, psz_value );
2777         free( psz_value );
2778     }
2779
2780     static const vlc_fourcc_t p_extra[] = {
2781         AVIFOURCC_IARL, AVIFOURCC_ICMS, AVIFOURCC_ICRP, AVIFOURCC_IDIM, AVIFOURCC_IDPI,
2782         AVIFOURCC_IENG, AVIFOURCC_IKEY, AVIFOURCC_ILGT, AVIFOURCC_IMED, AVIFOURCC_IPLT,
2783         AVIFOURCC_IPRD, AVIFOURCC_ISBJ, AVIFOURCC_ISFT, AVIFOURCC_ISHP, AVIFOURCC_ISRC,
2784         AVIFOURCC_ISRF, AVIFOURCC_ITCH, AVIFOURCC_ISMP, AVIFOURCC_IDIT, AVIFOURCC_ISGN,
2785         AVIFOURCC_IWRI, AVIFOURCC_IPRO, AVIFOURCC_ICNM, AVIFOURCC_IPDS, AVIFOURCC_IEDT,
2786         AVIFOURCC_ICDS, AVIFOURCC_IMUS, AVIFOURCC_ISTD, AVIFOURCC_IDST, AVIFOURCC_ICNT,
2787         AVIFOURCC_ISTR, 0,
2788     };
2789
2790     for( int i = 0; p_extra[i] != 0; i++ )
2791     {
2792         avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_extra[i], 0 );
2793         if( !p_strz )
2794             continue;
2795         char *psz_value = FromACP( p_strz->p_str );
2796         if( !psz_value )
2797             continue;
2798
2799         if( *psz_value )
2800             vlc_meta_AddExtra( p_meta, p_strz->p_type, psz_value );
2801         free( psz_value );
2802     }
2803 }
2804
2805 static void AVI_DvHandleAudio( demux_t *p_demux, avi_track_t *tk, block_t *p_frame )
2806 {
2807     size_t i_offset = 80 * 6 + 80 * 16 * 3 + 3;
2808     if( p_frame->i_buffer < i_offset + 5 )
2809         return;
2810
2811     if( p_frame->p_buffer[i_offset] != 0x50 )
2812         return;
2813
2814     es_format_t fmt;
2815     dv_get_audio_format( &fmt, &p_frame->p_buffer[i_offset + 1] );
2816
2817     if( tk->p_es_dv_audio && tk->i_dv_audio_rate != (int)fmt.audio.i_rate )
2818     {
2819         es_out_Del( p_demux->out, tk->p_es_dv_audio );
2820         tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2821     }
2822     else if( !tk->p_es_dv_audio )
2823     {
2824         tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2825     }
2826     tk->i_dv_audio_rate = fmt.audio.i_rate;
2827
2828     block_t *p_frame_audio = dv_extract_audio( p_frame );
2829     if( p_frame_audio )
2830         es_out_Send( p_demux->out, tk->p_es_dv_audio, p_frame_audio );
2831 }
2832
2833 /*****************************************************************************
2834  * Subtitles
2835  *****************************************************************************/
2836 static void AVI_ExtractSubtitle( demux_t *p_demux,
2837                                  unsigned int i_stream,
2838                                  avi_chunk_list_t *p_strl,
2839                                  avi_chunk_STRING_t *p_strn )
2840 {
2841     demux_sys_t *p_sys = p_demux->p_sys;
2842     block_t *p_block = NULL;
2843     input_attachment_t *p_attachment = NULL;
2844     char *psz_description = NULL;
2845     avi_chunk_indx_t *p_indx = NULL;
2846
2847     if( !p_sys->b_seekable )
2848         goto exit;
2849
2850     p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2851     avi_chunk_t ck;
2852     int64_t  i_position;
2853     unsigned i_size;
2854     if( p_indx )
2855     {
2856         if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES &&
2857             p_indx->i_entriesinuse > 0 )
2858         {
2859             if( stream_Seek( p_demux->s, p_indx->idx.super[0].i_offset )||
2860                 AVI_ChunkRead( p_demux->s, &ck, NULL  ) )
2861                 goto exit;
2862             p_indx = &ck.indx;
2863         }
2864
2865         if( p_indx->i_indextype != AVI_INDEX_OF_CHUNKS ||
2866             p_indx->i_entriesinuse != 1 ||
2867             p_indx->i_indexsubtype != 0 )
2868             goto exit;
2869
2870         i_position  = p_indx->i_baseoffset +
2871                       p_indx->idx.std[0].i_offset - 8;
2872         i_size      = (p_indx->idx.std[0].i_size & 0x7fffffff) + 8;
2873     }
2874     else
2875     {
2876         avi_chunk_idx1_t *p_idx1;
2877         uint64_t         i_offset;
2878
2879         if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2880             goto exit;
2881
2882         i_size = 0;
2883         for( unsigned i = 0; i < p_idx1->i_entry_count; i++ )
2884         {
2885             const idx1_entry_t *e = &p_idx1->entry[i];
2886             unsigned i_cat;
2887             unsigned i_stream_idx;
2888
2889             AVI_ParseStreamHeader( e->i_fourcc, &i_stream_idx, &i_cat );
2890             if( i_cat == SPU_ES && i_stream_idx == i_stream )
2891             {
2892                 i_position = e->i_pos + i_offset;
2893                 i_size     = e->i_length + 8;
2894                 break;
2895             }
2896         }
2897         if( i_size <= 0 )
2898             goto exit;
2899     }
2900
2901     /* */
2902     if( i_size > 10000000 )
2903     {
2904         msg_Dbg( p_demux, "Attached subtitle too big: %u", i_size );
2905         goto exit;
2906     }
2907
2908     if( stream_Seek( p_demux->s, i_position ) )
2909         goto exit;
2910     p_block = stream_Block( p_demux->s, i_size );
2911     if( !p_block )
2912         goto exit;
2913
2914     /* Parse packet header */
2915     const uint8_t *p = p_block->p_buffer;
2916     if( i_size < 8 || p[2] != 't' || p[3] != 'x' )
2917         goto exit;
2918     p += 8;
2919     i_size -= 8;
2920
2921     /* Parse subtitle chunk header */
2922     if( i_size < 11 || memcmp( p, "GAB2", 4 ) ||
2923         p[4] != 0x00 || GetWLE( &p[5] ) != 0x2 )
2924         goto exit;
2925     const unsigned i_name = GetDWLE( &p[7] );
2926     if( 11 + i_size <= i_name )
2927         goto exit;
2928     if( i_name > 0 )
2929         psz_description = FromCharset( "UTF-16LE", &p[11], i_name );
2930     p += 11 + i_name;
2931     i_size -= 11 + i_name;
2932     if( i_size < 6 || GetWLE( &p[0] ) != 0x04 )
2933         goto exit;
2934     const unsigned i_payload = GetDWLE( &p[2] );
2935     if( i_size < 6 + i_payload || i_payload <= 0 )
2936         goto exit;
2937     p += 6;
2938     i_size -= 6;
2939
2940     if( !psz_description )
2941         psz_description = p_strn ? FromACP( p_strn->p_str ) : NULL;
2942     char *psz_name;
2943     if( asprintf( &psz_name, "subtitle%d.srt", p_sys->i_attachment ) <= 0 )
2944         psz_name = NULL;
2945     p_attachment = vlc_input_attachment_New( psz_name,
2946                                              "application/x-srt",
2947                                              psz_description,
2948                                              p, i_payload );
2949     if( p_attachment )
2950         TAB_APPEND( p_sys->i_attachment, p_sys->attachment, p_attachment );
2951     free( psz_name );
2952
2953 exit:
2954     free( psz_description );
2955
2956     if( p_block )
2957         block_Release( p_block );
2958
2959     if( p_attachment )
2960         msg_Dbg( p_demux, "Loaded an embedded subtitle" );
2961     else
2962         msg_Warn( p_demux, "Failed to load an embedded subtitle" );
2963
2964     if( p_indx == &ck.indx )
2965         AVI_ChunkFree( p_demux->s, &ck );
2966 }
2967 /*****************************************************************************
2968  * Stream management
2969  *****************************************************************************/
2970 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
2971 {
2972     demux_sys_t *p_sys = p_demux->p_sys;
2973     unsigned int i;
2974     int b_end = true;
2975
2976     for( i = 0; i < p_sys->i_track; i++ )
2977     {
2978         avi_track_t *tk = p_sys->track[i];
2979         if( tk->i_idxposc >= tk->idx.i_size )
2980         {
2981             tk->b_eof = true;
2982         }
2983         else
2984         {
2985             b_end = false;
2986         }
2987     }
2988     return( b_end );
2989 }
2990
2991 /****************************************************************************
2992  * AVI_MovieGetLength give max streams length in second
2993  ****************************************************************************/
2994 static mtime_t  AVI_MovieGetLength( demux_t *p_demux )
2995 {
2996     demux_sys_t  *p_sys = p_demux->p_sys;
2997     mtime_t      i_maxlength = 0;
2998     unsigned int i;
2999
3000     for( i = 0; i < p_sys->i_track; i++ )
3001     {
3002         avi_track_t *tk = p_sys->track[i];
3003         mtime_t i_length;
3004
3005         /* fix length for each stream */
3006         if( tk->idx.i_size < 1 || !tk->idx.p_entry )
3007         {
3008             continue;
3009         }
3010
3011         if( tk->i_samplesize )
3012         {
3013             i_length = AVI_GetDPTS( tk,
3014                                     tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal +
3015                                         tk->idx.p_entry[tk->idx.i_size-1].i_length );
3016         }
3017         else
3018         {
3019             i_length = AVI_GetDPTS( tk, tk->idx.i_size );
3020         }
3021         i_length /= CLOCK_FREQ;    /* in seconds */
3022
3023         msg_Dbg( p_demux,
3024                  "stream[%d] length:%"PRId64" (based on index)",
3025                  i,
3026                  i_length );
3027         i_maxlength = __MAX( i_maxlength, i_length );
3028     }
3029
3030     return i_maxlength;
3031 }