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