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