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