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