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