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