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