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