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