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