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