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