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