1 /*****************************************************************************
2 * avi.c : AVI file Stream input module for vlc
3 *****************************************************************************
4 * Copyright (C) 2001-2004 the VideoLAN team
6 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
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.
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.
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 *****************************************************************************/
23 /*****************************************************************************
25 *****************************************************************************/
31 #include <vlc_common.h>
32 #include <vlc_plugin.h>
33 #include <vlc_demux.h>
35 #include <vlc_interface.h>
38 #include <vlc_codecs.h>
39 #include <vlc_charset.h>
43 /*****************************************************************************
45 *****************************************************************************/
47 #define INTERLEAVE_TEXT N_("Force interleaved method" )
48 #define INTERLEAVE_LONGTEXT N_( "Force interleaved method." )
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)." )
55 static int Open ( vlc_object_t * );
56 static void Close( vlc_object_t * );
58 static const int pi_index[] = {0,1,2};
60 static const char *const ppsz_indexes[] = { N_("Ask"), N_("Always fix"),
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 );
70 add_bool( "avi-interleaved", 0, NULL,
71 INTERLEAVE_TEXT, INTERLEAVE_LONGTEXT, true );
72 add_integer( "avi-index", 0, NULL,
73 INDEX_TEXT, INDEX_LONGTEXT, false );
74 change_integer_list( pi_index, ppsz_indexes, NULL );
76 set_callbacks( Open, Close );
79 /*****************************************************************************
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 * );
87 #define __ABS( x ) ( (x) < 0 ? (-(x)) : (x) )
91 vlc_fourcc_t i_fourcc;
94 vlc_fourcc_t i_type; /* only for AVIFOURCC_LIST */
96 uint8_t i_peek[8]; /* first 8 bytes */
98 unsigned int i_stream;
109 uint32_t i_lengthtotal;
117 unsigned int i_cat; /* AUDIO_ES, VIDEO_ES */
118 vlc_fourcc_t i_codec;
127 avi_entry_t *p_index;
128 unsigned int i_idxnb;
129 unsigned int i_idxmax;
131 unsigned int i_idxposc; /* numero of chunk */
132 unsigned int i_idxposb; /* byte in the current chunk */
134 /* extra information given to the decoder */
137 /* For VBR audio only */
138 unsigned int i_blockno;
139 unsigned int i_blocksize;
141 /* For muxed streams */
142 stream_t *p_out_muxed;
157 off_t i_movi_lastchunk_pos; /* XXX position of last valid chunk */
159 /* number of streams and information */
160 unsigned int i_track;
167 static inline off_t __EVEN( off_t i )
169 return (i & 1) ? i + 1 : i;
172 static mtime_t AVI_PTSToChunk( avi_track_t *, mtime_t i_pts );
173 static mtime_t AVI_PTSToByte ( avi_track_t *, mtime_t i_pts );
174 static mtime_t AVI_GetDPTS ( avi_track_t *, int64_t i_count );
175 static mtime_t AVI_GetPTS ( avi_track_t * );
178 static int AVI_StreamChunkFind( demux_t *, unsigned int i_stream );
179 static int AVI_StreamChunkSet ( demux_t *,
180 unsigned int i_stream, unsigned int i_ck );
181 static int AVI_StreamBytesSet ( demux_t *,
182 unsigned int i_stream, off_t i_byte );
184 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t );
185 static int AVI_GetKeyFlag ( vlc_fourcc_t , uint8_t * );
187 static int AVI_PacketGetHeader( demux_t *, avi_packet_t *p_pk );
188 static int AVI_PacketNext ( demux_t * );
189 static int AVI_PacketRead ( demux_t *, avi_packet_t *, block_t **);
190 static int AVI_PacketSearch ( demux_t * );
192 static void AVI_IndexLoad ( demux_t * );
193 static void AVI_IndexCreate ( demux_t * );
194 static void AVI_IndexAddEntry( demux_sys_t *, int, avi_entry_t * );
196 static mtime_t AVI_MovieGetLength( demux_t * );
198 /*****************************************************************************
200 *****************************************************************************/
201 static int AVI_TrackSeek ( demux_t *, int, mtime_t );
202 static int AVI_TrackStopFinishedStreams( demux_t *);
205 - For VBR mp3 stream:
206 count blocks by rounded-up chunksizes instead of chunks
207 we need full emulation of dshow avi demuxer bugs :(
208 fixes silly nandub-style a-v delaying in avi with vbr mp3...
209 (from mplayer 2002/08/02)
213 /*****************************************************************************
214 * Open: check file and initializes AVI structures
215 *****************************************************************************/
216 static int Open( vlc_object_t * p_this )
218 demux_t *p_demux = (demux_t *)p_this;
221 bool b_index = false;
225 avi_chunk_list_t *p_riff = (avi_chunk_list_t*)&ck_riff;
226 avi_chunk_list_t *p_hdrl, *p_movi;
227 avi_chunk_avih_t *p_avih;
229 unsigned int i_track;
230 unsigned int i, i_peeker;
232 const uint8_t *p_peek;
234 /* Is it an avi file ? */
235 if( stream_Peek( p_demux->s, &p_peek, 200 ) < 200 ) return VLC_EGENERIC;
237 for( i_peeker = 0; i_peeker < 188; i_peeker++ )
239 if( !strncmp( (char *)&p_peek[0], "RIFF", 4 ) && !strncmp( (char *)&p_peek[8], "AVI ", 4 ) )
241 if( !strncmp( (char *)&p_peek[0], "ON2 ", 4 ) && !strncmp( (char *)&p_peek[8], "ON2f", 4 ) )
245 if( i_peeker == 188 )
250 /* Initialize input structures. */
251 p_sys = p_demux->p_sys = malloc( sizeof(demux_sys_t) );
252 memset( p_sys, 0, sizeof( demux_sys_t ) );
255 p_sys->i_movi_lastchunk_pos = 0;
256 p_sys->b_odml = false;
257 p_sys->b_muxed = false;
262 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_seekable );
264 p_demux->pf_control = Control;
265 p_demux->pf_demux = Demux_Seekable;
267 /* For unseekable stream, automaticaly use Demux_UnSeekable */
268 if( !p_sys->b_seekable || config_GetInt( p_demux, "avi-interleaved" ) )
270 p_demux->pf_demux = Demux_UnSeekable;
275 stream_Read( p_demux->s, NULL, i_peeker );
278 if( AVI_ChunkReadRoot( p_demux->s, &p_sys->ck_root ) )
280 msg_Err( p_demux, "avi module discarded (invalid file)" );
284 if( AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF ) > 1 )
286 unsigned int i_count =
287 AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF );
289 msg_Warn( p_demux, "multiple riff -> OpenDML ?" );
290 for( i = 1; i < i_count; i++ )
292 avi_chunk_list_t *p_sysx;
294 p_sysx = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, i );
295 if( p_sysx->i_type == AVIFOURCC_AVIX )
297 msg_Warn( p_demux, "detected OpenDML file" );
298 p_sys->b_odml = true;
304 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
305 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
306 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0 );
308 if( !p_hdrl || !p_movi )
310 msg_Err( p_demux, "avi module discarded (invalid file)" );
314 if( !( p_avih = AVI_ChunkFind( p_hdrl, AVIFOURCC_avih, 0 ) ) )
316 msg_Err( p_demux, "cannot find avih chunk" );
319 i_track = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
320 if( p_avih->i_streams != i_track )
323 "found %d stream but %d are declared",
324 i_track, p_avih->i_streams );
328 msg_Err( p_demux, "no stream defined!" );
332 /* print information on streams */
333 msg_Dbg( p_demux, "AVIH: %d stream, flags %s%s%s%s ",
335 p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
336 p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
337 p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
338 p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
339 if( ( p_sys->meta = vlc_meta_New() ) )
342 sprintf( buffer, "%s%s%s%s",
343 p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
344 p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
345 p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
346 p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
347 vlc_meta_SetSetting( p_sys->meta, buffer );
350 /* now read info on each stream and create ES */
351 for( i = 0 ; i < i_track; i++ )
353 avi_track_t *tk = malloc( sizeof( avi_track_t ) );
357 avi_chunk_list_t *p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
358 avi_chunk_strh_t *p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
359 avi_chunk_STRING_t *p_strn = AVI_ChunkFind( p_strl, AVIFOURCC_strn, 0 );
360 avi_chunk_strf_auds_t *p_auds = NULL;
361 avi_chunk_strf_vids_t *p_vids = NULL;
364 memset( tk, 0, sizeof( avi_track_t ) );
366 p_vids = (avi_chunk_strf_vids_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
367 p_auds = (avi_chunk_strf_auds_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
369 if( p_strl == NULL || p_strh == NULL || p_auds == NULL || p_vids == NULL )
371 msg_Warn( p_demux, "stream[%d] incomplete", i );
375 tk->i_rate = p_strh->i_rate;
376 tk->i_scale = p_strh->i_scale;
377 tk->i_samplesize = p_strh->i_samplesize;
378 msg_Dbg( p_demux, "stream[%d] rate:%d scale:%d samplesize:%d",
379 i, tk->i_rate, tk->i_scale, tk->i_samplesize );
381 switch( p_strh->i_type )
383 case( AVIFOURCC_auds ):
384 tk->i_cat = AUDIO_ES;
385 tk->i_codec = AVI_FourccGetCodec( AUDIO_ES,
386 p_auds->p_wf->wFormatTag );
388 tk->i_blocksize = p_auds->p_wf->nBlockAlign;
389 if( tk->i_blocksize == 0 )
391 if( p_auds->p_wf->wFormatTag == 1 )
392 tk->i_blocksize = p_auds->p_wf->nChannels * (p_auds->p_wf->wBitsPerSample/8);
396 else if( tk->i_samplesize != 0 && tk->i_samplesize != tk->i_blocksize )
398 msg_Warn( p_demux, "track[%d] samplesize=%d and blocksize=%d are not equal."
399 "Using blocksize as a workaround.",
400 i, tk->i_samplesize, tk->i_blocksize );
401 tk->i_samplesize = tk->i_blocksize;
404 if( tk->i_codec == VLC_FOURCC( 'v', 'o', 'r', 'b' ) )
406 tk->i_blocksize = 0; /* fix vorbis VBR decoding */
409 es_format_Init( &fmt, AUDIO_ES, tk->i_codec );
411 fmt.audio.i_channels = p_auds->p_wf->nChannels;
412 fmt.audio.i_rate = p_auds->p_wf->nSamplesPerSec;
413 fmt.i_bitrate = p_auds->p_wf->nAvgBytesPerSec*8;
414 fmt.audio.i_blockalign = p_auds->p_wf->nBlockAlign;
415 fmt.audio.i_bitspersample = p_auds->p_wf->wBitsPerSample;
416 fmt.b_packetized = !tk->i_blocksize;
419 "stream[%d] audio(0x%x) %d channels %dHz %dbits",
420 i, p_auds->p_wf->wFormatTag, p_auds->p_wf->nChannels,
421 p_auds->p_wf->nSamplesPerSec,
422 p_auds->p_wf->wBitsPerSample );
424 fmt.i_extra = __MIN( p_auds->p_wf->cbSize,
425 p_auds->i_chunk_size - sizeof(WAVEFORMATEX) );
426 fmt.p_extra = tk->p_extra = malloc( fmt.i_extra );
427 if( !fmt.p_extra ) goto error;
428 memcpy( fmt.p_extra, &p_auds->p_wf[1], fmt.i_extra );
430 /* Rewrite the vorbis headers from Xiph-like format
431 * to VLC internal format
434 * - 1st byte == N, is the number of packets - 1
435 * - Following bytes are the size of the N first packets:
436 * while( *p == 0xFF ) { size += 0xFF; p++ } size += *p;
437 * (the size of the last packet is the size of remaining
438 * data in the buffer)
439 * - Finally, all the packets concatenated
442 * - Size of the packet on 16 bits (big endian) FIXME: should be 32 bits to be safe
443 * - The packet itself
444 * - Size of the next packet, and so on ...
447 if( tk->i_codec == VLC_FOURCC( 'v', 'o', 'r', 'b' ) )
449 uint8_t *p_extra = fmt.p_extra;
450 size_t i_extra = fmt.i_extra;
452 if( i_extra <= 1 ) break;
453 if( *p_extra++ != 2 ) break; /* 3 packets - 1 = 2 */
456 size_t i_identifier_len = 0;
457 while( *p_extra == 0xFF )
459 i_identifier_len += 0xFF;
461 if( --i_extra <= 1 ) break;
463 i_identifier_len += *p_extra++;
464 if( i_identifier_len > --i_extra ) break;
466 size_t i_comment_len = 0;
467 while( *p_extra == 0xFF )
469 i_comment_len += 0xFF;
471 if( --i_extra <= 1 ) break;
473 i_comment_len += *p_extra++;
474 if( i_comment_len > --i_extra ) break;
475 size_t i_cookbook_len = i_extra;
477 size_t i_headers_size = 3 * 2 + i_identifier_len +
478 i_comment_len + i_cookbook_len;
479 uint8_t *p_out = malloc( i_headers_size );
480 if( !p_out ) goto error;
482 fmt.p_extra = tk->p_extra = p_out;
483 fmt.i_extra = i_headers_size;
484 #define copy_packet( len ) \
485 *p_out++ = len >> 8; \
486 *p_out++ = len & 0xFF; \
487 memcpy( p_out, p_extra, len ); \
490 copy_packet( i_identifier_len );
491 copy_packet( i_comment_len );
492 copy_packet( i_cookbook_len );
498 case( AVIFOURCC_vids ):
499 tk->i_cat = VIDEO_ES;
500 tk->i_codec = AVI_FourccGetCodec( VIDEO_ES,
501 p_vids->p_bih->biCompression );
502 if( p_vids->p_bih->biCompression == 0x00 )
504 switch( p_vids->p_bih->biBitCount )
507 tk->i_codec = VLC_FOURCC('R','V','3','2');
510 tk->i_codec = VLC_FOURCC('R','V','2','4');
513 /* tk->i_codec = VLC_FOURCC('R','V','1','6');*/
516 tk->i_codec = VLC_FOURCC('R','V','1','5');
519 tk->i_codec = VLC_FOURCC( 'Y', 'V', 'U', '9' ); /* <- TODO check that */
522 tk->i_codec = VLC_FOURCC('Y','8','0','0');
525 es_format_Init( &fmt, VIDEO_ES, tk->i_codec );
527 if( p_vids->p_bih->biBitCount == 24 )
529 /* This is in BGR format */
530 fmt.video.i_bmask = 0x00ff0000;
531 fmt.video.i_gmask = 0x0000ff00;
532 fmt.video.i_rmask = 0x000000ff;
537 es_format_Init( &fmt, VIDEO_ES, p_vids->p_bih->biCompression );
538 if( tk->i_codec == FOURCC_mp4v &&
539 !strncasecmp( (char*)&p_strh->i_handler, "XVID", 4 ) )
541 fmt.i_codec = VLC_FOURCC( 'X', 'V', 'I', 'D' );
544 tk->i_samplesize = 0;
545 fmt.video.i_width = p_vids->p_bih->biWidth;
546 fmt.video.i_height = p_vids->p_bih->biHeight;
547 fmt.video.i_bits_per_pixel = p_vids->p_bih->biBitCount;
548 fmt.video.i_frame_rate = tk->i_rate;
549 fmt.video.i_frame_rate_base = tk->i_scale;
551 __MIN( p_vids->p_bih->biSize - sizeof( BITMAPINFOHEADER ),
552 p_vids->i_chunk_size - sizeof(BITMAPINFOHEADER) );
553 fmt.p_extra = &p_vids->p_bih[1];
554 msg_Dbg( p_demux, "stream[%d] video(%4.4s) %"PRIu32"x%"PRIu32" %dbpp %ffps",
555 i, (char*)&p_vids->p_bih->biCompression,
556 (uint32_t)p_vids->p_bih->biWidth,
557 (uint32_t)p_vids->p_bih->biHeight,
558 p_vids->p_bih->biBitCount,
559 (float)tk->i_rate/(float)tk->i_scale );
561 if( p_vids->p_bih->biCompression == 0x00 )
563 /* RGB DIB are coded from bottom to top */
565 (unsigned int)(-(int)p_vids->p_bih->biHeight);
568 /* Extract palette from extradata if bpp <= 8
569 * (assumes that extradata contains only palette but appears
570 * to be true for all palettized codecs we support) */
571 if( fmt.i_extra && fmt.video.i_bits_per_pixel <= 8 &&
572 fmt.video.i_bits_per_pixel > 0 )
576 fmt.video.p_palette = calloc( sizeof(video_palette_t), 1 );
577 fmt.video.p_palette->i_entries = 1;
579 /* Apparently this is necessary. But why ? */
581 p_vids->i_chunk_size - sizeof(BITMAPINFOHEADER);
582 for( i = 0; i < __MIN(fmt.i_extra/4, 256); i++ )
584 ((uint32_t *)&fmt.video.p_palette->palette[0][0])[i] =
585 GetDWLE((uint32_t*)fmt.p_extra + i);
590 case( AVIFOURCC_txts):
592 tk->i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
593 msg_Dbg( p_demux, "stream[%d] subtitles", i );
594 es_format_Init( &fmt, SPU_ES, tk->i_codec );
597 case( AVIFOURCC_iavs):
598 case( AVIFOURCC_ivas):
599 p_sys->b_muxed = true;
600 msg_Dbg( p_demux, "stream[%d] iavs with handler %4.4s", i, (char *)&p_strh->i_handler );
601 if( p_strh->i_handler == FOURCC_dvsd ||
602 p_strh->i_handler == FOURCC_dvhd ||
603 p_strh->i_handler == FOURCC_dvsl ||
604 p_strh->i_handler == FOURCC_dv25 ||
605 p_strh->i_handler == FOURCC_dv50 )
607 tk->p_out_muxed = stream_DemuxNew( p_demux, (char *)"rawdv", p_demux->out );
608 if( !tk->p_out_muxed )
609 msg_Err( p_demux, "could not load the DV parser" );
615 case( AVIFOURCC_mids):
616 msg_Dbg( p_demux, "stream[%d] midi is UNSUPPORTED", i );
619 msg_Warn( p_demux, "stream[%d] unknown type %4.4s", i, (char *)&p_strh->i_type );
625 /* The charset of p_strn is undefined */
626 EnsureUTF8( p_strn->p_str );
627 fmt.psz_description = strdup( p_strn->p_str );
629 if( tk->p_out_muxed == NULL )
630 tk->p_es = es_out_Add( p_demux->out, &fmt );
631 TAB_APPEND( p_sys->i_track, p_sys->track, tk );
634 if( p_sys->i_track <= 0 )
636 msg_Err( p_demux, "no valid track" );
640 i_do_index = config_GetInt( p_demux, "avi-index" );
641 if( i_do_index == 1 ) /* Always fix */
644 if( p_sys->b_seekable )
646 AVI_IndexCreate( p_demux );
650 msg_Warn( p_demux, "cannot create index (unseekable stream)" );
651 AVI_IndexLoad( p_demux );
656 AVI_IndexLoad( p_demux );
659 /* *** movie length in sec *** */
660 p_sys->i_length = AVI_MovieGetLength( p_demux );
661 if( p_sys->i_length < (mtime_t)p_avih->i_totalframes *
662 (mtime_t)p_avih->i_microsecperframe /
665 msg_Warn( p_demux, "broken or missing index, 'seek' will be "
666 "approximative or will exhibit strange behavior" );
667 if( i_do_index == 0 && !b_index )
669 if( !p_sys->b_seekable ) {
674 i_create = intf_UserYesNo( p_demux, _("AVI Index") ,
675 _( "This AVI file is broken. Seeking will not "
676 "work correctly.\nDo you want to "
677 "try to repair it?\n\nThis might take a long time." ),
678 _( "Repair" ), _( "Don't repair" ), _( "Cancel") );
679 if( i_create == DIALOG_OK_YES )
682 msg_Dbg( p_demux, "Fixing AVI index" );
685 else if( i_create == DIALOG_CANCELLED )
688 vlc_object_kill( p_demux->p_parent );
694 /* fix some BeOS MediaKit generated file */
695 for( i = 0 ; i < p_sys->i_track; i++ )
697 avi_track_t *tk = p_sys->track[i];
698 avi_chunk_list_t *p_strl;
699 avi_chunk_strh_t *p_strh;
700 avi_chunk_strf_auds_t *p_auds;
702 if( tk->i_cat != AUDIO_ES )
706 if( tk->i_idxnb < 1 ||
708 tk->i_samplesize != 0 )
712 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
713 p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
714 p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
716 if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
717 (unsigned int)tk->i_rate == p_auds->p_wf->nSamplesPerSec )
719 int64_t i_track_length =
720 tk->p_index[tk->i_idxnb-1].i_length +
721 tk->p_index[tk->i_idxnb-1].i_lengthtotal;
722 mtime_t i_length = (mtime_t)p_avih->i_totalframes *
723 (mtime_t)p_avih->i_microsecperframe;
727 msg_Warn( p_demux, "track[%d] cannot be fixed (BeOS MediaKit generated)", i );
730 tk->i_samplesize = 1;
731 tk->i_rate = i_track_length * (int64_t)1000000/ i_length;
732 msg_Warn( p_demux, "track[%d] fixed with rate=%d scale=%d (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
736 if( p_sys->b_seekable )
738 /* we have read all chunk so go back to movi */
739 stream_Seek( p_demux->s, p_movi->i_chunk_pos );
741 /* Skip movi header */
742 stream_Read( p_demux->s, NULL, 12 );
744 p_sys->i_movi_begin = p_movi->i_chunk_pos;
750 vlc_meta_Delete( p_sys->meta );
752 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
757 /*****************************************************************************
758 * Close: frees unused data
759 *****************************************************************************/
760 static void Close ( vlc_object_t * p_this )
762 demux_t * p_demux = (demux_t *)p_this;
764 demux_sys_t *p_sys = p_demux->p_sys ;
766 for( i = 0; i < p_sys->i_track; i++ )
768 if( p_sys->track[i] )
770 if( p_sys->track[i]->p_out_muxed )
771 stream_DemuxDelete( p_sys->track[i]->p_out_muxed );
772 free( p_sys->track[i]->p_index );
773 free( p_sys->track[i]->p_extra );
774 free( p_sys->track[i] );
777 free( p_sys->track );
778 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
779 vlc_meta_Delete( p_sys->meta );
784 /*****************************************************************************
785 * Demux_Seekable: reads and demuxes data packets for stream seekable
786 *****************************************************************************
787 * AVIDemux: reads and demuxes data packets
788 *****************************************************************************
789 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
790 *****************************************************************************/
797 off_t i_posf; /* where we will read :
798 if i_idxposb == 0 : begining of chunk (+8 to acces data)
799 else : point on data directly */
800 } avi_track_toread_t;
802 static int Demux_Seekable( demux_t *p_demux )
804 demux_sys_t *p_sys = p_demux->p_sys;
806 unsigned int i_track_count = 0;
807 unsigned int i_track;
809 /* cannot be more than 100 stream (dcXX or wbXX) */
810 avi_track_toread_t toread[100];
813 /* detect new selected/unselected streams */
814 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
816 avi_track_t *tk = p_sys->track[i_track];
819 if( p_sys->b_muxed && tk->p_out_muxed )
822 tk->b_activated = true;
826 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
827 if( b && !tk->b_activated )
829 if( p_sys->b_seekable)
831 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
833 tk->b_activated = true;
835 else if( !b && tk->b_activated )
837 tk->b_activated = false;
845 if( i_track_count <= 0 )
847 int64_t i_length = p_sys->i_length * (mtime_t)1000000;
849 p_sys->i_time += 25*1000; /* read 25ms */
852 if( p_sys->i_time >= i_length )
856 msg_Warn( p_demux, "no track selected, exiting..." );
860 /* wait for the good time */
861 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
862 p_sys->i_time += 25*1000; /* read 25ms */
865 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
867 avi_track_t *tk = p_sys->track[i_track];
870 toread[i_track].b_ok = tk->b_activated;
871 if( tk->i_idxposc < tk->i_idxnb )
873 toread[i_track].i_posf = tk->p_index[tk->i_idxposc].i_pos;
874 if( tk->i_idxposb > 0 )
876 toread[i_track].i_posf += 8 + tk->i_idxposb;
881 toread[i_track].i_posf = -1;
884 i_dpts = p_sys->i_time - AVI_GetPTS( tk );
886 if( tk->i_samplesize )
888 toread[i_track].i_toread = AVI_PTSToByte( tk, __ABS( i_dpts ) );
892 toread[i_track].i_toread = AVI_PTSToChunk( tk, __ABS( i_dpts ) );
897 toread[i_track].i_toread *= -1;
912 /* search for first chunk to be read */
913 for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
915 if( !toread[i].b_ok ||
916 AVI_GetDPTS( p_sys->track[i],
917 toread[i].i_toread ) <= -25 * 1000 )
922 if( toread[i].i_toread > 0 )
924 b_done = false; /* not yet finished */
926 if( toread[i].i_posf > 0 )
928 if( i_pos == -1 || i_pos > toread[i].i_posf )
931 i_pos = toread[i].i_posf;
943 int i_loop_count = 0;
945 /* no valid index, we will parse directly the stream
946 * in case we fail we will disable all finished stream */
947 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
949 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
950 if( AVI_PacketNext( p_demux ) )
952 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
957 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
964 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
967 "cannot get packet header, track disabled" );
968 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
970 if( avi_pk.i_stream >= p_sys->i_track ||
971 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
973 if( AVI_PacketNext( p_demux ) )
976 "cannot skip packet, track disabled" );
977 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
980 /* Prevents from eating all the CPU with broken files.
981 * This value should be low enough so that it doesn't
982 * affect the reading speed too much. */
983 if( !(++i_loop_count % 1024) )
985 if( !vlc_object_alive (p_demux) ) return -1;
988 if( !(i_loop_count % (1024 * 10)) )
990 "don't seem to find any data..." );
996 /* add this chunk to the index */
999 index.i_id = avi_pk.i_fourcc;
1001 AVI_GetKeyFlag(p_sys->track[avi_pk.i_stream]->i_codec,
1003 index.i_pos = avi_pk.i_pos;
1004 index.i_length = avi_pk.i_size;
1005 AVI_IndexAddEntry( p_sys, avi_pk.i_stream, &index );
1007 i_track = avi_pk.i_stream;
1008 tk = p_sys->track[i_track];
1009 /* do we will read this data ? */
1010 if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -25*1000 )
1016 if( AVI_PacketNext( p_demux ) )
1019 "cannot skip packet, track disabled" );
1020 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1029 stream_Seek( p_demux->s, i_pos );
1032 /* Set the track to use */
1033 tk = p_sys->track[i_track];
1035 /* read thoses data */
1036 if( tk->i_samplesize )
1038 unsigned int i_toread;
1040 if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1042 if( tk->i_samplesize > 1 )
1044 i_toread = tk->i_samplesize;
1048 i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1049 i_toread = __MAX( i_toread, 100 );
1052 i_size = __MIN( tk->p_index[tk->i_idxposc].i_length -
1058 i_size = tk->p_index[tk->i_idxposc].i_length;
1061 if( tk->i_idxposb == 0 )
1063 i_size += 8; /* need to read and skip header */
1066 if( ( p_frame = stream_Block( p_demux->s, __EVEN( i_size ) ) )==NULL )
1068 msg_Warn( p_demux, "failed reading data" );
1069 tk->b_activated = false;
1070 toread[i_track].b_ok = false;
1073 if( i_size % 2 ) /* read was padded on word boundary */
1075 p_frame->i_buffer--;
1078 if( tk->i_idxposb == 0 )
1080 p_frame->p_buffer += 8;
1081 p_frame->i_buffer -= 8;
1083 p_frame->i_pts = AVI_GetPTS( tk ) + 1;
1084 if( tk->p_index[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1086 p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1090 p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1094 if( tk->i_samplesize )
1096 if( tk->i_idxposb == 0 )
1100 toread[i_track].i_toread -= i_size;
1101 tk->i_idxposb += i_size;
1102 if( tk->i_idxposb >=
1103 tk->p_index[tk->i_idxposc].i_length )
1111 int i_length = tk->p_index[tk->i_idxposc].i_length;
1114 if( tk->i_cat == AUDIO_ES )
1116 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1118 toread[i_track].i_toread--;
1121 if( tk->i_idxposc < tk->i_idxnb)
1123 toread[i_track].i_posf =
1124 tk->p_index[tk->i_idxposc].i_pos;
1125 if( tk->i_idxposb > 0 )
1127 toread[i_track].i_posf += 8 + tk->i_idxposb;
1133 toread[i_track].i_posf = -1;
1136 b_stream = true; /* at least one read succeed */
1138 if( tk->i_cat != VIDEO_ES )
1139 p_frame->i_dts = p_frame->i_pts;
1142 p_frame->i_dts = p_frame->i_pts;
1146 //p_pes->i_rate = p_demux->stream.control.i_rate;
1147 if( tk->p_out_muxed )
1148 stream_DemuxSend( tk->p_out_muxed, p_frame );
1150 es_out_Send( p_demux->out, tk->p_es, p_frame );
1155 /*****************************************************************************
1156 * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1157 *****************************************************************************
1158 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1159 *****************************************************************************/
1160 static int Demux_UnSeekable( demux_t *p_demux )
1162 demux_sys_t *p_sys = p_demux->p_sys;
1163 avi_track_t *p_stream_master = NULL;
1164 unsigned int i_stream;
1165 unsigned int i_packet;
1167 if( p_sys->b_muxed )
1169 msg_Err( p_demux, "Can not yet process muxed avi substreams without seeking" );
1170 return VLC_EGENERIC;
1173 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
1175 /* *** find master stream for data packet skipping algo *** */
1176 /* *** -> first video, if any, or first audio ES *** */
1177 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1179 avi_track_t *tk = p_sys->track[i_stream];
1182 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1184 if( b && tk->i_cat == VIDEO_ES )
1186 p_stream_master = tk;
1190 p_stream_master = tk;
1194 if( !p_stream_master )
1196 msg_Warn( p_demux, "no more stream selected" );
1200 p_sys->i_time = AVI_GetPTS( p_stream_master );
1202 for( i_packet = 0; i_packet < 10; i_packet++)
1204 #define p_stream p_sys->track[avi_pk.i_stream]
1206 avi_packet_t avi_pk;
1208 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1213 if( avi_pk.i_stream >= p_sys->i_track ||
1214 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1216 /* we haven't found an audio or video packet:
1217 * - we have seek, found first next packet
1218 * - others packets could be found, skip them
1220 switch( avi_pk.i_fourcc )
1222 case AVIFOURCC_JUNK:
1223 case AVIFOURCC_LIST:
1224 case AVIFOURCC_RIFF:
1225 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1226 case AVIFOURCC_idx1:
1229 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1231 return( 0 ); /* eof */
1234 "seems to have lost position, resync" );
1235 if( AVI_PacketSearch( p_demux ) )
1237 msg_Err( p_demux, "resync failed" );
1244 /* check for time */
1245 if( __ABS( AVI_GetPTS( p_stream ) -
1246 AVI_GetPTS( p_stream_master ) )< 600*1000 )
1248 /* load it and send to decoder */
1250 if( AVI_PacketRead( p_demux, &avi_pk, &p_frame ) || p_frame == NULL )
1254 p_frame->i_pts = AVI_GetPTS( p_stream ) + 1;
1256 if( avi_pk.i_cat != VIDEO_ES )
1257 p_frame->i_dts = p_frame->i_pts;
1260 p_frame->i_dts = p_frame->i_pts;
1264 //p_pes->i_rate = p_demux->stream.control.i_rate;
1265 es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1269 if( AVI_PacketNext( p_demux ) )
1275 /* *** update stream time position *** */
1276 if( p_stream->i_samplesize )
1278 p_stream->i_idxposb += avi_pk.i_size;
1282 if( p_stream->i_cat == AUDIO_ES )
1284 p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1286 p_stream->i_idxposc++;
1296 /*****************************************************************************
1297 * Seek: goto to i_date or i_percent
1298 *****************************************************************************/
1299 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1302 demux_sys_t *p_sys = p_demux->p_sys;
1303 unsigned int i_stream;
1304 msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1305 i_date / 1000000, i_percent );
1307 if( p_sys->b_seekable )
1309 if( !p_sys->i_length )
1311 avi_track_t *p_stream;
1314 /* use i_percent to create a true i_date */
1315 msg_Warn( p_demux, "seeking without index at %d%%"
1316 " only works for interleaved files", i_percent );
1317 if( i_percent >= 100 )
1319 msg_Warn( p_demux, "cannot seek so far !" );
1320 return VLC_EGENERIC;
1322 i_percent = __MAX( i_percent, 0 );
1324 /* try to find chunk that is at i_percent or the file */
1325 i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1326 p_sys->i_movi_begin );
1327 /* search first selected stream */
1328 for( i_stream = 0, p_stream = NULL;
1329 i_stream < p_sys->i_track; i_stream++ )
1331 p_stream = p_sys->track[i_stream];
1332 if( p_stream->b_activated )
1337 if( !p_stream || !p_stream->b_activated )
1339 msg_Warn( p_demux, "cannot find any selected stream" );
1340 return VLC_EGENERIC;
1343 /* be sure that the index exist */
1344 if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1346 msg_Warn( p_demux, "cannot seek" );
1347 return VLC_EGENERIC;
1350 while( i_pos >= p_stream->p_index[p_stream->i_idxposc].i_pos +
1351 p_stream->p_index[p_stream->i_idxposc].i_length + 8 )
1353 /* search after i_idxposc */
1354 if( AVI_StreamChunkSet( p_demux,
1355 i_stream, p_stream->i_idxposc + 1 ) )
1357 msg_Warn( p_demux, "cannot seek" );
1358 return VLC_EGENERIC;
1362 i_date = AVI_GetPTS( p_stream );
1363 /* TODO better support for i_samplesize != 0 */
1364 msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1368 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1370 avi_track_t *p_stream = p_sys->track[i_stream];
1372 if( !p_stream->b_activated )
1375 AVI_TrackSeek( p_demux, i_stream, i_date );
1377 p_sys->i_time = i_date;
1378 msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /1000000 );
1383 msg_Err( p_demux, "shouldn't yet be executed" );
1384 return VLC_EGENERIC;
1388 /*****************************************************************************
1390 *****************************************************************************/
1391 static double ControlGetPosition( demux_t *p_demux )
1393 demux_sys_t *p_sys = p_demux->p_sys;
1395 if( p_sys->i_length > 0 )
1397 return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)1000000 );
1399 else if( stream_Size( p_demux->s ) > 0 )
1405 /* search the more advanced selected es */
1406 for( i = 0; i < p_sys->i_track; i++ )
1408 avi_track_t *tk = p_sys->track[i];
1409 if( tk->b_activated && tk->i_idxposc < tk->i_idxnb )
1411 i_tmp = tk->p_index[tk->i_idxposc].i_pos +
1412 tk->p_index[tk->i_idxposc].i_length + 8;
1419 return (double)i64 / stream_Size( p_demux->s );
1424 static int Control( demux_t *p_demux, int i_query, va_list args )
1426 demux_sys_t *p_sys = p_demux->p_sys;
1434 case DEMUX_GET_POSITION:
1435 pf = (double*)va_arg( args, double * );
1436 *pf = ControlGetPosition( p_demux );
1438 case DEMUX_SET_POSITION:
1439 f = (double)va_arg( args, double );
1440 if( p_sys->b_seekable )
1442 i64 = (mtime_t)(1000000.0 * p_sys->i_length * f );
1443 return Seek( p_demux, i64, (int)(f * 100) );
1447 int64_t i_pos = stream_Size( p_demux->s ) * f;
1448 return stream_Seek( p_demux->s, i_pos );
1451 case DEMUX_GET_TIME:
1452 pi64 = (int64_t*)va_arg( args, int64_t * );
1453 *pi64 = p_sys->i_time;
1456 case DEMUX_SET_TIME:
1460 i64 = (int64_t)va_arg( args, int64_t );
1461 if( p_sys->i_length > 0 )
1463 i_percent = 100 * i64 / (p_sys->i_length*1000000);
1465 else if( p_sys->i_time > 0 )
1467 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1468 (double)i64 / (double)p_sys->i_time );
1470 return Seek( p_demux, i64, i_percent );
1472 case DEMUX_GET_LENGTH:
1473 pi64 = (int64_t*)va_arg( args, int64_t * );
1474 *pi64 = p_sys->i_length * (mtime_t)1000000;
1478 pf = (double*)va_arg( args, double * );
1480 for( i = 0; i < (int)p_sys->i_track; i++ )
1482 avi_track_t *tk = p_sys->track[i];
1483 if( tk->i_cat == VIDEO_ES && tk->i_scale > 0)
1485 *pf = (float)tk->i_rate / (float)tk->i_scale;
1490 case DEMUX_GET_META:
1491 p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1492 vlc_meta_Merge( p_meta, p_sys->meta );
1496 return VLC_EGENERIC;
1500 /*****************************************************************************
1501 * Function to convert pts to chunk or byte
1502 *****************************************************************************/
1504 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1509 return (mtime_t)((int64_t)i_pts *
1510 (int64_t)tk->i_rate /
1511 (int64_t)tk->i_scale /
1514 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1516 if( !tk->i_scale || !tk->i_samplesize )
1519 return (mtime_t)((int64_t)i_pts *
1520 (int64_t)tk->i_rate /
1521 (int64_t)tk->i_scale /
1523 (int64_t)tk->i_samplesize );
1526 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1533 i_dpts = (mtime_t)( (int64_t)1000000 *
1535 (int64_t)tk->i_scale /
1536 (int64_t)tk->i_rate );
1538 if( tk->i_samplesize )
1540 return i_dpts / tk->i_samplesize;
1545 static mtime_t AVI_GetPTS( avi_track_t *tk )
1547 if( tk->i_samplesize )
1549 int64_t i_count = 0;
1551 /* we need a valid entry we will emulate one */
1552 if( tk->i_idxposc == tk->i_idxnb )
1556 /* use the last entry */
1557 i_count = tk->p_index[tk->i_idxnb - 1].i_lengthtotal
1558 + tk->p_index[tk->i_idxnb - 1].i_length;
1563 i_count = tk->p_index[tk->i_idxposc].i_lengthtotal;
1565 return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1569 if( tk->i_cat == AUDIO_ES )
1571 return AVI_GetDPTS( tk, tk->i_blockno );
1575 return AVI_GetDPTS( tk, tk->i_idxposc );
1580 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1582 demux_sys_t *p_sys = p_demux->p_sys;
1583 avi_packet_t avi_pk;
1584 int i_loop_count = 0;
1586 /* find first chunk of i_stream that isn't in index */
1588 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1590 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1591 if( AVI_PacketNext( p_demux ) )
1593 return VLC_EGENERIC;
1598 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1603 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
1605 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1607 msg_Warn( p_demux, "cannot get packet header" );
1608 return VLC_EGENERIC;
1610 if( avi_pk.i_stream >= p_sys->i_track ||
1611 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1613 if( AVI_PacketNext( p_demux ) )
1615 return VLC_EGENERIC;
1618 /* Prevents from eating all the CPU with broken files.
1619 * This value should be low enough so that it doesn't
1620 * affect the reading speed too much. */
1621 if( !(++i_loop_count % 1024) )
1623 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
1626 if( !(i_loop_count % (1024 * 10)) )
1627 msg_Warn( p_demux, "don't seem to find any data..." );
1632 /* add this chunk to the index */
1635 index.i_id = avi_pk.i_fourcc;
1637 AVI_GetKeyFlag(p_sys->track[avi_pk.i_stream]->i_codec,
1639 index.i_pos = avi_pk.i_pos;
1640 index.i_length = avi_pk.i_size;
1641 AVI_IndexAddEntry( p_sys, avi_pk.i_stream, &index );
1643 if( avi_pk.i_stream == i_stream )
1648 if( AVI_PacketNext( p_demux ) )
1650 return VLC_EGENERIC;
1656 /* be sure that i_ck will be a valid index entry */
1657 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1660 demux_sys_t *p_sys = p_demux->p_sys;
1661 avi_track_t *p_stream = p_sys->track[i_stream];
1663 p_stream->i_idxposc = i_ck;
1664 p_stream->i_idxposb = 0;
1666 if( i_ck >= p_stream->i_idxnb )
1668 p_stream->i_idxposc = p_stream->i_idxnb - 1;
1671 p_stream->i_idxposc++;
1672 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1674 return VLC_EGENERIC;
1677 } while( p_stream->i_idxposc < i_ck );
1683 /* XXX FIXME up to now, we assume that all chunk are one after one */
1684 static int AVI_StreamBytesSet( demux_t *p_demux,
1685 unsigned int i_stream,
1688 demux_sys_t *p_sys = p_demux->p_sys;
1689 avi_track_t *p_stream = p_sys->track[i_stream];
1691 if( ( p_stream->i_idxnb > 0 )
1692 &&( i_byte < p_stream->p_index[p_stream->i_idxnb - 1].i_lengthtotal +
1693 p_stream->p_index[p_stream->i_idxnb - 1].i_length ) )
1695 /* index is valid to find the ck */
1696 /* uses dichototmie to be fast enougth */
1697 int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->i_idxnb - 1 );
1698 int i_idxmax = p_stream->i_idxnb;
1702 if( p_stream->p_index[i_idxposc].i_lengthtotal > i_byte )
1704 i_idxmax = i_idxposc ;
1705 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1709 if( p_stream->p_index[i_idxposc].i_lengthtotal +
1710 p_stream->p_index[i_idxposc].i_length <= i_byte)
1712 i_idxmin = i_idxposc ;
1713 i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1717 p_stream->i_idxposc = i_idxposc;
1718 p_stream->i_idxposb = i_byte -
1719 p_stream->p_index[i_idxposc].i_lengthtotal;
1728 p_stream->i_idxposc = p_stream->i_idxnb - 1;
1729 p_stream->i_idxposb = 0;
1732 p_stream->i_idxposc++;
1733 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1735 return VLC_EGENERIC;
1738 } while( p_stream->p_index[p_stream->i_idxposc].i_lengthtotal +
1739 p_stream->p_index[p_stream->i_idxposc].i_length <= i_byte );
1741 p_stream->i_idxposb = i_byte -
1742 p_stream->p_index[p_stream->i_idxposc].i_lengthtotal;
1747 static int AVI_TrackSeek( demux_t *p_demux,
1751 demux_sys_t *p_sys = p_demux->p_sys;
1752 avi_track_t *tk = p_sys->track[i_stream];
1754 #define p_stream p_sys->track[i_stream]
1757 i_oldpts = AVI_GetPTS( p_stream );
1759 if( !p_stream->i_samplesize )
1761 if( AVI_StreamChunkSet( p_demux,
1763 AVI_PTSToChunk( p_stream, i_date ) ) )
1765 return VLC_EGENERIC;
1768 if( p_stream->i_cat == AUDIO_ES )
1772 for( i = 0; i < tk->i_idxposc; i++ )
1774 if( tk->i_blocksize > 0 )
1776 tk->i_blockno += ( tk->p_index[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
1786 "old:%"PRId64" %s new %"PRId64,
1788 i_oldpts > i_date ? ">" : "<",
1791 if( p_stream->i_cat == VIDEO_ES )
1793 /* search key frame */
1794 //if( i_date < i_oldpts || 1 )
1796 while( p_stream->i_idxposc > 0 &&
1797 !( p_stream->p_index[p_stream->i_idxposc].i_flags &
1800 if( AVI_StreamChunkSet( p_demux,
1802 p_stream->i_idxposc - 1 ) )
1804 return VLC_EGENERIC;
1807 if( p_stream->p_es )
1808 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_stream->p_es, i_date );
1813 while( p_stream->i_idxposc < p_stream->i_idxnb &&
1814 !( p_stream->p_index[p_stream->i_idxposc].i_flags &
1817 if( AVI_StreamChunkSet( p_demux,
1819 p_stream->i_idxposc + 1 ) )
1821 return VLC_EGENERIC;
1830 if( AVI_StreamBytesSet( p_demux,
1832 AVI_PTSToByte( p_stream, i_date ) ) )
1834 return VLC_EGENERIC;
1841 /****************************************************************************
1842 * Return true if it's a key frame
1843 ****************************************************************************/
1844 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
1850 * startcode: 0x00000100 32bits
1851 * framenumber ? 5bits
1852 * piture type 0(I),1(P) 2bits
1854 if( GetDWBE( p_byte ) != 0x00000100 )
1856 /* it's not an msmpegv1 stream, strange...*/
1857 return AVIIF_KEYFRAME;
1859 return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
1862 case FOURCC_DIV3: /* wmv1 also */
1864 * picture type 0(I),1(P) 2bits
1866 return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
1868 /* we should find first occurrence of 0x000001b6 (32bits)
1869 * startcode: 0x000001b6 32bits
1870 * piture type 0(I),1(P) 2bits
1872 if( GetDWBE( p_byte ) != 0x000001b6 )
1874 /* not true , need to find the first VOP header */
1875 return AVIIF_KEYFRAME;
1877 return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
1880 /* I can't do it, so say yes */
1881 return AVIIF_KEYFRAME;
1885 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
1890 wf_tag_to_fourcc( i_codec, &i_codec, NULL );
1894 /* XXX DIV1 <- msmpeg4v1, DIV2 <- msmpeg4v2, DIV3 <- msmpeg4v3, mp4v for mpeg4 */
1898 return VLC_FOURCC('m','r','l','e');
1947 return VLC_FOURCC( 'u', 'n', 'd', 'f' );
1951 /****************************************************************************
1953 ****************************************************************************/
1954 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
1955 unsigned int *pi_number, unsigned int *pi_type )
1957 #define SET_PTR( p, v ) if( p ) *(p) = (v);
1960 c1 = ((uint8_t *)&i_id)[0];
1961 c2 = ((uint8_t *)&i_id)[1];
1963 if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
1965 SET_PTR( pi_number, 100 ); /* > max stream number */
1966 SET_PTR( pi_type, UNKNOWN_ES );
1970 SET_PTR( pi_number, (c1 - '0') * 10 + (c2 - '0' ) );
1971 switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
1974 SET_PTR( pi_type, AUDIO_ES );
1978 SET_PTR( pi_type, VIDEO_ES );
1981 SET_PTR( pi_type, UNKNOWN_ES );
1988 /****************************************************************************
1990 ****************************************************************************/
1991 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
1993 const uint8_t *p_peek;
1995 if( stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
1997 return VLC_EGENERIC;
1999 p_pk->i_fourcc = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
2000 p_pk->i_size = GetDWLE( p_peek + 4 );
2001 p_pk->i_pos = stream_Tell( p_demux->s );
2002 if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
2004 p_pk->i_type = VLC_FOURCC( p_peek[8], p_peek[9],
2005 p_peek[10], p_peek[11] );
2012 memcpy( p_pk->i_peek, p_peek + 8, 8 );
2014 AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
2018 static int AVI_PacketNext( demux_t *p_demux )
2020 avi_packet_t avi_ck;
2023 if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2025 return VLC_EGENERIC;
2028 if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2029 ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2033 else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2034 avi_ck.i_type == AVIFOURCC_AVIX )
2040 i_skip = __EVEN( avi_ck.i_size ) + 8;
2043 if( stream_Read( p_demux->s, NULL, i_skip ) != i_skip )
2045 return VLC_EGENERIC;
2050 static int AVI_PacketRead( demux_t *p_demux,
2052 block_t **pp_frame )
2056 i_size = __EVEN( p_pk->i_size + 8 );
2058 if( ( *pp_frame = stream_Block( p_demux->s, i_size ) ) == NULL )
2060 return VLC_EGENERIC;
2062 (*pp_frame)->p_buffer += 8;
2063 (*pp_frame)->i_buffer -= 8;
2065 if( i_size != p_pk->i_size + 8 )
2067 (*pp_frame)->i_buffer--;
2073 static int AVI_PacketSearch( demux_t *p_demux )
2075 demux_sys_t *p_sys = p_demux->p_sys;
2076 avi_packet_t avi_pk;
2081 if( stream_Read( p_demux->s, NULL, 1 ) != 1 )
2083 return VLC_EGENERIC;
2085 AVI_PacketGetHeader( p_demux, &avi_pk );
2086 if( avi_pk.i_stream < p_sys->i_track &&
2087 ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2091 switch( avi_pk.i_fourcc )
2093 case AVIFOURCC_JUNK:
2094 case AVIFOURCC_LIST:
2095 case AVIFOURCC_RIFF:
2096 case AVIFOURCC_idx1:
2100 /* Prevents from eating all the CPU with broken files.
2101 * This value should be low enough so that it doesn't affect the
2102 * reading speed too much (not that we care much anyway because
2103 * this code is called only on broken files). */
2104 if( !(++i_count % 1024) )
2106 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
2109 if( !(i_count % (1024 * 10)) )
2110 msg_Warn( p_demux, "trying to resync..." );
2115 /****************************************************************************
2117 ****************************************************************************/
2118 static void AVI_IndexAddEntry( demux_sys_t *p_sys,
2120 avi_entry_t *p_index)
2122 avi_track_t *tk = p_sys->track[i_stream];
2124 /* Update i_movi_lastchunk_pos */
2125 if( p_sys->i_movi_lastchunk_pos < p_index->i_pos )
2127 p_sys->i_movi_lastchunk_pos = p_index->i_pos;
2131 if( tk->i_idxnb >= tk->i_idxmax )
2133 tk->i_idxmax += 16384;
2134 tk->p_index = realloc( tk->p_index,
2135 tk->i_idxmax * sizeof( avi_entry_t ) );
2136 if( tk->p_index == NULL )
2141 /* calculate cumulate length */
2142 if( tk->i_idxnb > 0 )
2144 p_index->i_lengthtotal =
2145 tk->p_index[tk->i_idxnb - 1].i_length +
2146 tk->p_index[tk->i_idxnb - 1].i_lengthtotal;
2150 p_index->i_lengthtotal = 0;
2153 tk->p_index[tk->i_idxnb++] = *p_index;
2156 static int AVI_IndexLoad_idx1( demux_t *p_demux )
2158 demux_sys_t *p_sys = p_demux->p_sys;
2160 avi_chunk_list_t *p_riff;
2161 avi_chunk_list_t *p_movi;
2162 avi_chunk_idx1_t *p_idx1;
2164 unsigned int i_stream;
2165 unsigned int i_index;
2171 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2172 p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2173 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2177 msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2178 return VLC_EGENERIC;
2181 /* *** calculate offset *** */
2182 /* Well, avi is __SHIT__ so test more than one entry
2183 * (needed for some avi files) */
2185 for( i = 0; i < __MIN( p_idx1->i_entry_count, 10 ); i++ )
2187 if( p_idx1->entry[i].i_pos < p_movi->i_chunk_pos )
2189 i_offset = p_movi->i_chunk_pos + 8;
2194 /* Reset b_keyset */
2195 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2196 b_keyset[i_stream] = false;
2198 for( i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2202 AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2205 if( i_stream < p_sys->i_track &&
2206 i_cat == p_sys->track[i_stream]->i_cat )
2209 index.i_id = p_idx1->entry[i_index].i_fourcc;
2211 p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2212 index.i_pos = p_idx1->entry[i_index].i_pos + i_offset;
2213 index.i_length = p_idx1->entry[i_index].i_length;
2214 AVI_IndexAddEntry( p_sys, i_stream, &index );
2216 if( index.i_flags&AVIIF_KEYFRAME )
2217 b_keyset[i_stream] = true;
2221 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2223 if( !b_keyset[i_stream] )
2225 avi_track_t *tk = p_sys->track[i_stream];
2227 msg_Dbg( p_demux, "no key frame set for track %d", i_stream );
2228 for( i_index = 0; i_index < tk->i_idxnb; i_index++ )
2229 tk->p_index[i_index].i_flags |= AVIIF_KEYFRAME;
2235 static void __Parse_indx( demux_t *p_demux,
2237 avi_chunk_indx_t *p_indx )
2239 demux_sys_t *p_sys = p_demux->p_sys;
2243 msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2244 if( p_indx->i_indexsubtype == 0 )
2246 for( i = 0; i < p_indx->i_entriesinuse; i++ )
2248 index.i_id = p_indx->i_id;
2249 index.i_flags = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2250 index.i_pos = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2251 index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2253 AVI_IndexAddEntry( p_sys, i_stream, &index );
2256 else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2258 for( i = 0; i < p_indx->i_entriesinuse; i++ )
2260 index.i_id = p_indx->i_id;
2261 index.i_flags = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2262 index.i_pos = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2263 index.i_length = p_indx->idx.field[i].i_size;
2265 AVI_IndexAddEntry( p_sys, i_stream, &index );
2270 msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2274 static void AVI_IndexLoad_indx( demux_t *p_demux )
2276 demux_sys_t *p_sys = p_demux->p_sys;
2277 unsigned int i_stream;
2280 avi_chunk_list_t *p_riff;
2281 avi_chunk_list_t *p_hdrl;
2283 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2284 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2286 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2288 avi_chunk_list_t *p_strl;
2289 avi_chunk_indx_t *p_indx;
2291 #define p_stream p_sys->track[i_stream]
2292 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2293 p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2297 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2302 if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2304 __Parse_indx( p_demux, i_stream, p_indx );
2306 else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2309 for( i = 0; i < p_indx->i_entriesinuse; i++ )
2311 if( stream_Seek( p_demux->s, p_indx->idx.super[i].i_offset )||
2312 AVI_ChunkRead( p_demux->s, &ck_sub, NULL ) )
2316 __Parse_indx( p_demux, i_stream, &ck_sub.indx );
2321 msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2327 static void AVI_IndexLoad( demux_t *p_demux )
2329 demux_sys_t *p_sys = p_demux->p_sys;
2330 unsigned int i_stream;
2332 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2334 p_sys->track[i_stream]->i_idxnb = 0;
2335 p_sys->track[i_stream]->i_idxmax = 0;
2336 p_sys->track[i_stream]->p_index = NULL;
2341 AVI_IndexLoad_indx( p_demux );
2343 else if( AVI_IndexLoad_idx1( p_demux ) )
2345 /* try indx if idx1 failed as some "normal" file have indx too */
2346 AVI_IndexLoad_indx( p_demux );
2349 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2351 msg_Dbg( p_demux, "stream[%d] created %d index entries",
2352 i_stream, p_sys->track[i_stream]->i_idxnb );
2356 static void AVI_IndexCreate( demux_t *p_demux )
2358 demux_sys_t *p_sys = p_demux->p_sys;
2360 avi_chunk_list_t *p_riff;
2361 avi_chunk_list_t *p_movi;
2363 unsigned int i_stream;
2366 mtime_t i_dialog_update;
2369 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2370 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2374 msg_Err( p_demux, "cannot find p_movi" );
2378 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2380 p_sys->track[i_stream]->i_idxnb = 0;
2381 p_sys->track[i_stream]->i_idxmax = 0;
2382 p_sys->track[i_stream]->p_index = NULL;
2384 i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2385 stream_Size( p_demux->s ) );
2387 stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2388 msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2391 /* Only show dialog if AVI is > 10MB */
2393 i_dialog_update = mdate();
2394 if( stream_Size( p_demux->s ) > 10000000 )
2395 i_dialog_id = intf_IntfProgress( p_demux, _("Fixing AVI Index..."), 0.0 );
2401 if( !vlc_object_alive (p_demux) )
2404 /* Don't update/check dialog too often */
2405 if( i_dialog_id > 0 && mdate() - i_dialog_update > 100000 )
2407 if( intf_ProgressIsCancelled( p_demux, i_dialog_id ) )
2410 double f_pos = 100.0 * stream_Tell( p_demux->s ) /
2411 stream_Size( p_demux->s );
2412 intf_ProgressUpdate( p_demux, i_dialog_id,
2413 _( "Fixing AVI Index..." ), f_pos, -1 );
2415 i_dialog_update = mdate();
2418 if( AVI_PacketGetHeader( p_demux, &pk ) )
2421 if( pk.i_stream < p_sys->i_track &&
2422 pk.i_cat == p_sys->track[pk.i_stream]->i_cat )
2425 index.i_id = pk.i_fourcc;
2427 AVI_GetKeyFlag(p_sys->track[pk.i_stream]->i_codec, pk.i_peek);
2428 index.i_pos = pk.i_pos;
2429 index.i_length = pk.i_size;
2430 AVI_IndexAddEntry( p_sys, pk.i_stream, &index );
2434 switch( pk.i_fourcc )
2436 case AVIFOURCC_idx1:
2439 avi_chunk_list_t *p_sysx;
2440 p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2441 AVIFOURCC_RIFF, 1 );
2443 msg_Dbg( p_demux, "looking for new RIFF chunk" );
2444 if( stream_Seek( p_demux->s, p_sysx->i_chunk_pos + 24 ) )
2450 case AVIFOURCC_RIFF:
2451 msg_Dbg( p_demux, "new RIFF chunk found" );
2455 case AVIFOURCC_JUNK:
2459 msg_Warn( p_demux, "need resync, probably broken avi" );
2460 if( AVI_PacketSearch( p_demux ) )
2462 msg_Warn( p_demux, "lost sync, abord index creation" );
2468 if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2469 AVI_PacketNext( p_demux ) )
2476 if( i_dialog_id > 0 )
2477 intf_UserHide( p_demux, i_dialog_id );
2479 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2481 msg_Dbg( p_demux, "stream[%d] creating %d index entries",
2482 i_stream, p_sys->track[i_stream]->i_idxnb );
2486 /*****************************************************************************
2488 *****************************************************************************/
2489 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
2491 demux_sys_t *p_sys = p_demux->p_sys;
2495 for( i = 0; i < p_sys->i_track; i++ )
2497 avi_track_t *tk = p_sys->track[i];
2498 if( tk->i_idxposc >= tk->i_idxnb )
2500 tk->b_activated = false;
2501 if( tk->p_es ) es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2511 /****************************************************************************
2512 * AVI_MovieGetLength give max streams length in second
2513 ****************************************************************************/
2514 static mtime_t AVI_MovieGetLength( demux_t *p_demux )
2516 demux_sys_t *p_sys = p_demux->p_sys;
2517 mtime_t i_maxlength = 0;
2520 for( i = 0; i < p_sys->i_track; i++ )
2522 avi_track_t *tk = p_sys->track[i];
2525 /* fix length for each stream */
2526 if( tk->i_idxnb < 1 || !tk->p_index )
2531 if( tk->i_samplesize )
2533 i_length = AVI_GetDPTS( tk,
2534 tk->p_index[tk->i_idxnb-1].i_lengthtotal +
2535 tk->p_index[tk->i_idxnb-1].i_length );
2539 i_length = AVI_GetDPTS( tk, tk->i_idxnb );
2541 i_length /= (mtime_t)1000000; /* in seconds */
2544 "stream[%d] length:%"PRId64" (based on index)",
2547 i_maxlength = __MAX( i_maxlength, i_length );