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