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