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