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