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 *****************************************************************************/
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 int pi_index[] = {0,1,2};
60 static const char *ppsz_indexes[] = { N_("Ask"), N_("Always fix"),
64 set_shortname( "AVI" );
65 set_description( _("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, 0 );
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;
171 static inline off_t __EVEN( off_t i )
173 return (i & 1) ? i + 1 : i;
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 * );
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 );
188 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t );
189 static int AVI_GetKeyFlag ( vlc_fourcc_t , uint8_t * );
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 * );
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 * );
200 static mtime_t AVI_MovieGetLength( demux_t * );
202 /*****************************************************************************
204 *****************************************************************************/
205 static int AVI_TrackSeek ( demux_t *, int, mtime_t );
206 static int AVI_TrackStopFinishedStreams( demux_t *);
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)
217 /*****************************************************************************
218 * Open: check file and initializes AVI structures
219 *****************************************************************************/
220 static int Open( vlc_object_t * p_this )
222 demux_t *p_demux = (demux_t *)p_this;
225 bool b_index = false;
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;
233 unsigned int i_track;
234 unsigned int i, i_peeker;
236 const uint8_t *p_peek;
238 /* Is it an avi file ? */
239 if( stream_Peek( p_demux->s, &p_peek, 200 ) < 200 ) return VLC_EGENERIC;
241 for( i_peeker = 0; i_peeker < 188; i_peeker++ )
243 if( !strncmp( (char *)&p_peek[0], "RIFF", 4 ) && !strncmp( (char *)&p_peek[8], "AVI ", 4 ) )
245 if( !strncmp( (char *)&p_peek[0], "ON2 ", 4 ) && !strncmp( (char *)&p_peek[8], "ON2f", 4 ) )
249 if( i_peeker == 188 )
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 ) );
259 p_sys->i_movi_lastchunk_pos = 0;
260 p_sys->b_odml = false;
261 p_sys->b_muxed = false;
266 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_seekable );
268 p_demux->pf_control = Control;
269 p_demux->pf_demux = Demux_Seekable;
271 /* For unseekable stream, automaticaly use Demux_UnSeekable */
272 if( !p_sys->b_seekable || config_GetInt( p_demux, "avi-interleaved" ) )
274 p_demux->pf_demux = Demux_UnSeekable;
279 stream_Read( p_demux->s, NULL, i_peeker );
282 if( AVI_ChunkReadRoot( p_demux->s, &p_sys->ck_root ) )
284 msg_Err( p_demux, "avi module discarded (invalid file)" );
288 if( AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF ) > 1 )
290 unsigned int i_count =
291 AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF );
293 msg_Warn( p_demux, "multiple riff -> OpenDML ?" );
294 for( i = 1; i < i_count; i++ )
296 avi_chunk_list_t *p_sysx;
298 p_sysx = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, i );
299 if( p_sysx->i_type == AVIFOURCC_AVIX )
301 msg_Warn( p_demux, "detected OpenDML file" );
302 p_sys->b_odml = true;
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 );
312 if( !p_hdrl || !p_movi )
314 msg_Err( p_demux, "avi module discarded (invalid file)" );
318 if( !( p_avih = AVI_ChunkFind( p_hdrl, AVIFOURCC_avih, 0 ) ) )
320 msg_Err( p_demux, "cannot find avih chunk" );
323 i_track = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
324 if( p_avih->i_streams != i_track )
327 "found %d stream but %d are declared",
328 i_track, p_avih->i_streams );
332 msg_Err( p_demux, "no stream defined!" );
336 /* print information on streams */
337 msg_Dbg( p_demux, "AVIH: %d stream, flags %s%s%s%s ",
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() ) )
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 );
354 /* now read info on each stream and create ES */
355 for( i = 0 ; i < i_track; i++ )
357 avi_track_t *tk = malloc( sizeof( avi_track_t ) );
360 msg_Err( p_demux, "Out of memory" );
364 avi_chunk_list_t *p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
365 avi_chunk_strh_t *p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
366 avi_chunk_STRING_t *p_strn = AVI_ChunkFind( p_strl, AVIFOURCC_strn, 0 );
367 avi_chunk_strf_auds_t *p_auds = NULL;
368 avi_chunk_strf_vids_t *p_vids = NULL;
371 memset( tk, 0, sizeof( avi_track_t ) );
373 p_vids = (avi_chunk_strf_vids_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
374 p_auds = (avi_chunk_strf_auds_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
376 if( p_strl == NULL || p_strh == NULL || p_auds == NULL || p_vids == NULL )
378 msg_Warn( p_demux, "stream[%d] incomplete", i );
382 tk->i_rate = p_strh->i_rate;
383 tk->i_scale = p_strh->i_scale;
384 tk->i_samplesize = p_strh->i_samplesize;
385 msg_Dbg( p_demux, "stream[%d] rate:%d scale:%d samplesize:%d",
386 i, tk->i_rate, tk->i_scale, tk->i_samplesize );
388 switch( p_strh->i_type )
390 case( AVIFOURCC_auds ):
391 tk->i_cat = AUDIO_ES;
392 tk->i_codec = AVI_FourccGetCodec( AUDIO_ES,
393 p_auds->p_wf->wFormatTag );
394 if( tk->i_codec == VLC_FOURCC( 'v', 'o', 'r', 'b' ) )
395 tk->i_blocksize = 0; /* fix vorbis VBR decoding */
396 else if( ( tk->i_blocksize = p_auds->p_wf->nBlockAlign ) == 0 )
398 if( p_auds->p_wf->wFormatTag == 1 )
400 tk->i_blocksize = p_auds->p_wf->nChannels * (p_auds->p_wf->wBitsPerSample/8);
407 es_format_Init( &fmt, AUDIO_ES, tk->i_codec );
409 fmt.audio.i_channels = p_auds->p_wf->nChannels;
410 fmt.audio.i_rate = p_auds->p_wf->nSamplesPerSec;
411 fmt.i_bitrate = p_auds->p_wf->nAvgBytesPerSec*8;
412 fmt.audio.i_blockalign = p_auds->p_wf->nBlockAlign;
413 fmt.audio.i_bitspersample = p_auds->p_wf->wBitsPerSample;
414 fmt.b_packetized = !tk->i_blocksize;
417 "stream[%d] audio(0x%x) %d channels %dHz %dbits",
418 i, p_auds->p_wf->wFormatTag, p_auds->p_wf->nChannels,
419 p_auds->p_wf->nSamplesPerSec,
420 p_auds->p_wf->wBitsPerSample );
422 fmt.i_extra = __MIN( p_auds->p_wf->cbSize,
423 p_auds->i_chunk_size - sizeof(WAVEFORMATEX) );
424 fmt.p_extra = tk->p_extra = malloc( fmt.i_extra );
425 if( !fmt.p_extra ) goto error;
426 memcpy( fmt.p_extra, &p_auds->p_wf[1], fmt.i_extra );
428 /* Rewrite the vorbis headers from Xiph-like format
429 * to VLC internal format
432 * - 1st byte == N, is the number of packets - 1
433 * - Following bytes are the size of the N first packets:
434 * while( *p == 0xFF ) { size += 0xFF; p++ } size += *p;
435 * (the size of the last packet is the size of remaining
436 * data in the buffer)
437 * - Finally, all the packets concatenated
440 * - Size of the packet on 16 bits (big endian) FIXME: should be 32 bits to be safe
441 * - The packet itself
442 * - Size of the next packet, and so on ...
445 if( tk->i_codec == VLC_FOURCC( 'v', 'o', 'r', 'b' ) )
447 uint8_t *p_extra = fmt.p_extra;
448 size_t i_extra = fmt.i_extra;
450 if( i_extra <= 1 ) break;
451 if( *p_extra++ != 2 ) break; /* 3 packets - 1 = 2 */
454 size_t i_identifier_len = 0;
455 while( *p_extra == 0xFF )
457 i_identifier_len += 0xFF;
459 if( --i_extra <= 1 ) break;
461 i_identifier_len += *p_extra++;
462 if( i_identifier_len > --i_extra ) break;
464 size_t i_comment_len = 0;
465 while( *p_extra == 0xFF )
467 i_comment_len += 0xFF;
469 if( --i_extra <= 1 ) break;
471 i_comment_len += *p_extra++;
472 if( i_comment_len > --i_extra ) break;
473 size_t i_cookbook_len = i_extra;
475 size_t i_headers_size = 3 * 2 + i_identifier_len +
476 i_comment_len + i_cookbook_len;
477 uint8_t *p_out = malloc( i_headers_size );
478 if( !p_out ) goto error;
480 fmt.p_extra = tk->p_extra = p_out;
481 fmt.i_extra = i_headers_size;
482 #define copy_packet( len ) \
483 *p_out++ = len >> 8; \
484 *p_out++ = len & 0xFF; \
485 memcpy( p_out, p_extra, len ); \
488 copy_packet( i_identifier_len );
489 copy_packet( i_comment_len );
490 copy_packet( i_cookbook_len );
496 case( AVIFOURCC_vids ):
497 tk->i_cat = VIDEO_ES;
498 tk->i_codec = AVI_FourccGetCodec( VIDEO_ES,
499 p_vids->p_bih->biCompression );
500 if( p_vids->p_bih->biCompression == 0x00 )
502 switch( p_vids->p_bih->biBitCount )
505 tk->i_codec = VLC_FOURCC('R','V','3','2');
508 tk->i_codec = VLC_FOURCC('R','V','2','4');
511 /* tk->i_codec = VLC_FOURCC('R','V','1','6');*/
514 tk->i_codec = VLC_FOURCC('R','V','1','5');
517 tk->i_codec = VLC_FOURCC( 'Y', 'V', 'U', '9' ); /* <- TODO check that */
520 tk->i_codec = VLC_FOURCC('Y','8','0','0');
523 es_format_Init( &fmt, VIDEO_ES, tk->i_codec );
525 if( p_vids->p_bih->biBitCount == 24 )
527 /* This is in BGR format */
528 fmt.video.i_bmask = 0x00ff0000;
529 fmt.video.i_gmask = 0x0000ff00;
530 fmt.video.i_rmask = 0x000000ff;
535 es_format_Init( &fmt, VIDEO_ES, p_vids->p_bih->biCompression );
536 if( tk->i_codec == FOURCC_mp4v &&
537 !strncasecmp( (char*)&p_strh->i_handler, "XVID", 4 ) )
539 fmt.i_codec = VLC_FOURCC( 'X', 'V', 'I', 'D' );
542 tk->i_samplesize = 0;
543 fmt.video.i_width = p_vids->p_bih->biWidth;
544 fmt.video.i_height = p_vids->p_bih->biHeight;
545 fmt.video.i_bits_per_pixel = p_vids->p_bih->biBitCount;
546 fmt.video.i_frame_rate = tk->i_rate;
547 fmt.video.i_frame_rate_base = tk->i_scale;
549 __MIN( p_vids->p_bih->biSize - sizeof( BITMAPINFOHEADER ),
550 p_vids->i_chunk_size - sizeof(BITMAPINFOHEADER) );
551 fmt.p_extra = &p_vids->p_bih[1];
552 msg_Dbg( p_demux, "stream[%d] video(%4.4s) %dx%d %dbpp %ffps",
553 i, (char*)&p_vids->p_bih->biCompression,
554 p_vids->p_bih->biWidth,
555 p_vids->p_bih->biHeight,
556 p_vids->p_bih->biBitCount,
557 (float)tk->i_rate/(float)tk->i_scale );
559 if( p_vids->p_bih->biCompression == 0x00 )
561 /* RGB DIB are coded from bottom to top */
563 (unsigned int)(-(int)p_vids->p_bih->biHeight);
566 /* Extract palette from extradata if bpp <= 8
567 * (assumes that extradata contains only palette but appears
568 * to be true for all palettized codecs we support) */
569 if( fmt.i_extra && fmt.video.i_bits_per_pixel <= 8 &&
570 fmt.video.i_bits_per_pixel > 0 )
574 fmt.video.p_palette = calloc( sizeof(video_palette_t), 1 );
575 fmt.video.p_palette->i_entries = 1;
577 /* Apparently this is necessary. But why ? */
579 p_vids->i_chunk_size - sizeof(BITMAPINFOHEADER);
580 for( i = 0; i < __MIN(fmt.i_extra/4, 256); i++ )
582 ((uint32_t *)&fmt.video.p_palette->palette[0][0])[i] =
583 GetDWLE((uint32_t*)fmt.p_extra + i);
588 case( AVIFOURCC_txts):
590 tk->i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
591 msg_Dbg( p_demux, "stream[%d] subtitles", i );
592 es_format_Init( &fmt, SPU_ES, tk->i_codec );
595 case( AVIFOURCC_iavs):
596 case( AVIFOURCC_ivas):
597 p_sys->b_muxed = true;
598 msg_Dbg( p_demux, "stream[%d] iavs with handler %4.4s", i, (char *)&p_strh->i_handler );
599 if( p_strh->i_handler == FOURCC_dvsd ||
600 p_strh->i_handler == FOURCC_dvhd ||
601 p_strh->i_handler == FOURCC_dvsl ||
602 p_strh->i_handler == FOURCC_dv25 ||
603 p_strh->i_handler == FOURCC_dv50 )
605 tk->p_out_muxed = stream_DemuxNew( p_demux, (char *)"rawdv", p_demux->out );
606 if( !tk->p_out_muxed )
607 msg_Err( p_demux, "could not load the DV parser" );
613 case( AVIFOURCC_mids):
614 msg_Dbg( p_demux, "stream[%d] midi is UNSUPPORTED", i );
617 msg_Warn( p_demux, "stream[%d] unknown type %4.4s", i, (char *)&p_strh->i_type );
623 /* The charset of p_strn is undefined */
624 EnsureUTF8( p_strn->p_str );
625 fmt.psz_description = strdup( p_strn->p_str );
627 if( tk->p_out_muxed == NULL )
628 tk->p_es = es_out_Add( p_demux->out, &fmt );
629 TAB_APPEND( p_sys->i_track, p_sys->track, tk );
632 if( p_sys->i_track <= 0 )
634 msg_Err( p_demux, "no valid track" );
638 i_do_index = config_GetInt( p_demux, "avi-index" );
639 if( i_do_index == 1 ) /* Always fix */
642 if( p_sys->b_seekable )
644 AVI_IndexCreate( p_demux );
648 msg_Warn( p_demux, "cannot create index (unseekable stream)" );
649 AVI_IndexLoad( p_demux );
654 AVI_IndexLoad( p_demux );
657 /* *** movie length in sec *** */
658 p_sys->i_length = AVI_MovieGetLength( p_demux );
659 if( p_sys->i_length < (mtime_t)p_avih->i_totalframes *
660 (mtime_t)p_avih->i_microsecperframe /
663 msg_Warn( p_demux, "broken or missing index, 'seek' will be "
664 "axproximative or will have strange behaviour" );
665 if( i_do_index == 0 && !b_index )
668 i_create = intf_UserYesNo( p_demux, _("AVI Index") ,
669 _( "This AVI file is broken. Seeking will not "
670 "work correctly.\nDo you want to "
671 "try to repair it?\n\nThis might take a long time." ),
672 _( "Repair" ), _( "Don't repair" ), _( "Cancel") );
673 if( i_create == DIALOG_OK_YES )
676 msg_Dbg( p_demux, "Fixing AVI index" );
679 else if( i_create == DIALOG_CANCELLED )
682 vlc_object_kill( p_demux->p_parent );
688 /* fix some BeOS MediaKit generated file */
689 for( i = 0 ; i < p_sys->i_track; i++ )
691 avi_track_t *tk = p_sys->track[i];
692 avi_chunk_list_t *p_strl;
693 avi_chunk_strh_t *p_strh;
694 avi_chunk_strf_auds_t *p_auds;
696 if( tk->i_cat != AUDIO_ES )
700 if( tk->i_idxnb < 1 ||
702 tk->i_samplesize != 0 )
706 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
707 p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
708 p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
710 if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
711 (unsigned int)tk->i_rate == p_auds->p_wf->nSamplesPerSec )
713 int64_t i_track_length =
714 tk->p_index[tk->i_idxnb-1].i_length +
715 tk->p_index[tk->i_idxnb-1].i_lengthtotal;
716 mtime_t i_length = (mtime_t)p_avih->i_totalframes *
717 (mtime_t)p_avih->i_microsecperframe;
721 msg_Warn( p_demux, "track[%d] cannot be fixed (BeOS MediaKit generated)", i );
724 tk->i_samplesize = 1;
725 tk->i_rate = i_track_length * (int64_t)1000000/ i_length;
726 msg_Warn( p_demux, "track[%d] fixed with rate=%d scale=%d (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
730 if( p_sys->b_seekable )
732 /* we have read all chunk so go back to movi */
733 stream_Seek( p_demux->s, p_movi->i_chunk_pos );
735 /* Skip movi header */
736 stream_Read( p_demux->s, NULL, 12 );
738 p_sys->i_movi_begin = p_movi->i_chunk_pos;
744 vlc_meta_Delete( p_sys->meta );
746 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
751 /*****************************************************************************
752 * Close: frees unused data
753 *****************************************************************************/
754 static void Close ( vlc_object_t * p_this )
756 demux_t * p_demux = (demux_t *)p_this;
758 demux_sys_t *p_sys = p_demux->p_sys ;
760 for( i = 0; i < p_sys->i_track; i++ )
762 if( p_sys->track[i] )
764 if( p_sys->track[i]->p_out_muxed )
765 stream_DemuxDelete( p_sys->track[i]->p_out_muxed );
766 free( p_sys->track[i]->p_index );
767 free( p_sys->track[i]->p_extra );
768 free( p_sys->track[i] );
771 free( p_sys->track );
772 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
773 vlc_meta_Delete( p_sys->meta );
778 /*****************************************************************************
779 * Demux_Seekable: reads and demuxes data packets for stream seekable
780 *****************************************************************************
781 * AVIDemux: reads and demuxes data packets
782 *****************************************************************************
783 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
784 *****************************************************************************/
791 off_t i_posf; /* where we will read :
792 if i_idxposb == 0 : begining of chunk (+8 to acces data)
793 else : point on data directly */
794 } avi_track_toread_t;
796 static int Demux_Seekable( demux_t *p_demux )
798 demux_sys_t *p_sys = p_demux->p_sys;
800 unsigned int i_track_count = 0;
801 unsigned int i_track;
803 /* cannot be more than 100 stream (dcXX or wbXX) */
804 avi_track_toread_t toread[100];
807 /* detect new selected/unselected streams */
808 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
810 avi_track_t *tk = p_sys->track[i_track];
813 if( p_sys->b_muxed && tk->p_out_muxed )
816 tk->b_activated = true;
820 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
821 if( b && !tk->b_activated )
823 if( p_sys->b_seekable)
825 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
827 tk->b_activated = true;
829 else if( !b && tk->b_activated )
831 tk->b_activated = false;
839 if( i_track_count <= 0 )
841 int64_t i_length = p_sys->i_length * (mtime_t)1000000;
843 p_sys->i_time += 25*1000; /* read 25ms */
846 if( p_sys->i_time >= i_length )
850 msg_Warn( p_demux, "no track selected, exiting..." );
854 /* wait for the good time */
855 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
856 p_sys->i_time += 25*1000; /* read 25ms */
859 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
861 avi_track_t *tk = p_sys->track[i_track];
864 toread[i_track].b_ok = tk->b_activated;
865 if( tk->i_idxposc < tk->i_idxnb )
867 toread[i_track].i_posf = tk->p_index[tk->i_idxposc].i_pos;
868 if( tk->i_idxposb > 0 )
870 toread[i_track].i_posf += 8 + tk->i_idxposb;
875 toread[i_track].i_posf = -1;
878 i_dpts = p_sys->i_time - AVI_GetPTS( tk );
880 if( tk->i_samplesize )
882 toread[i_track].i_toread = AVI_PTSToByte( tk, __ABS( i_dpts ) );
886 toread[i_track].i_toread = AVI_PTSToChunk( tk, __ABS( i_dpts ) );
891 toread[i_track].i_toread *= -1;
906 /* search for first chunk to be read */
907 for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
909 if( !toread[i].b_ok ||
910 AVI_GetDPTS( p_sys->track[i],
911 toread[i].i_toread ) <= -25 * 1000 )
916 if( toread[i].i_toread > 0 )
918 b_done = false; /* not yet finished */
920 if( toread[i].i_posf > 0 )
922 if( i_pos == -1 || i_pos > toread[i].i_posf )
925 i_pos = toread[i].i_posf;
937 int i_loop_count = 0;
939 /* no valid index, we will parse directly the stream
940 * in case we fail we will disable all finished stream */
941 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
943 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
944 if( AVI_PacketNext( p_demux ) )
946 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
951 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
958 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
961 "cannot get packet header, track disabled" );
962 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
964 if( avi_pk.i_stream >= p_sys->i_track ||
965 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
967 if( AVI_PacketNext( p_demux ) )
970 "cannot skip packet, track disabled" );
971 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
974 /* Prevents from eating all the CPU with broken files.
975 * This value should be low enough so that it doesn't
976 * affect the reading speed too much. */
977 if( !(++i_loop_count % 1024) )
979 if( p_demux->b_die ) return -1;
982 if( !(i_loop_count % (1024 * 10)) )
984 "don't seem to find any data..." );
990 /* add this chunk to the index */
993 index.i_id = avi_pk.i_fourcc;
995 AVI_GetKeyFlag(p_sys->track[avi_pk.i_stream]->i_codec,
997 index.i_pos = avi_pk.i_pos;
998 index.i_length = avi_pk.i_size;
999 AVI_IndexAddEntry( p_sys, avi_pk.i_stream, &index );
1001 i_track = avi_pk.i_stream;
1002 tk = p_sys->track[i_track];
1003 /* do we will read this data ? */
1004 if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -25*1000 )
1010 if( AVI_PacketNext( p_demux ) )
1013 "cannot skip packet, track disabled" );
1014 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1023 stream_Seek( p_demux->s, i_pos );
1026 /* Set the track to use */
1027 tk = p_sys->track[i_track];
1029 /* read thoses data */
1030 if( tk->i_samplesize )
1032 unsigned int i_toread;
1034 if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1036 if( tk->i_samplesize > 1 )
1038 i_toread = tk->i_samplesize;
1042 i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1043 i_toread = __MAX( i_toread, 100 );
1046 i_size = __MIN( tk->p_index[tk->i_idxposc].i_length -
1052 i_size = tk->p_index[tk->i_idxposc].i_length;
1055 if( tk->i_idxposb == 0 )
1057 i_size += 8; /* need to read and skip header */
1060 if( ( p_frame = stream_Block( p_demux->s, __EVEN( i_size ) ) )==NULL )
1062 msg_Warn( p_demux, "failed reading data" );
1063 tk->b_activated = false;
1064 toread[i_track].b_ok = false;
1067 if( i_size % 2 ) /* read was padded on word boundary */
1069 p_frame->i_buffer--;
1072 if( tk->i_idxposb == 0 )
1074 p_frame->p_buffer += 8;
1075 p_frame->i_buffer -= 8;
1077 p_frame->i_pts = AVI_GetPTS( tk ) + 1;
1078 if( tk->p_index[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1080 p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1084 p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1088 if( tk->i_samplesize )
1090 if( tk->i_idxposb == 0 )
1094 toread[i_track].i_toread -= i_size;
1095 tk->i_idxposb += i_size;
1096 if( tk->i_idxposb >=
1097 tk->p_index[tk->i_idxposc].i_length )
1105 int i_length = tk->p_index[tk->i_idxposc].i_length;
1108 if( tk->i_cat == AUDIO_ES )
1110 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1112 toread[i_track].i_toread--;
1115 if( tk->i_idxposc < tk->i_idxnb)
1117 toread[i_track].i_posf =
1118 tk->p_index[tk->i_idxposc].i_pos;
1119 if( tk->i_idxposb > 0 )
1121 toread[i_track].i_posf += 8 + tk->i_idxposb;
1127 toread[i_track].i_posf = -1;
1130 b_stream = true; /* at least one read succeed */
1132 if( tk->i_cat != VIDEO_ES )
1133 p_frame->i_dts = p_frame->i_pts;
1136 p_frame->i_dts = p_frame->i_pts;
1140 //p_pes->i_rate = p_demux->stream.control.i_rate;
1141 if( tk->p_out_muxed )
1142 stream_DemuxSend( tk->p_out_muxed, p_frame );
1144 es_out_Send( p_demux->out, tk->p_es, p_frame );
1149 /*****************************************************************************
1150 * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1151 *****************************************************************************
1152 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1153 *****************************************************************************/
1154 static int Demux_UnSeekable( demux_t *p_demux )
1156 demux_sys_t *p_sys = p_demux->p_sys;
1157 avi_track_t *p_stream_master = NULL;
1158 unsigned int i_stream;
1159 unsigned int i_packet;
1161 if( p_sys->b_muxed )
1163 msg_Err( p_demux, "Can not yet process muxed avi substreams without seeking" );
1164 return VLC_EGENERIC;
1167 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
1169 /* *** find master stream for data packet skipping algo *** */
1170 /* *** -> first video, if any, or first audio ES *** */
1171 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1173 avi_track_t *tk = p_sys->track[i_stream];
1176 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1178 if( b && tk->i_cat == VIDEO_ES )
1180 p_stream_master = tk;
1184 p_stream_master = tk;
1188 if( !p_stream_master )
1190 msg_Warn( p_demux, "no more stream selected" );
1194 p_sys->i_time = AVI_GetPTS( p_stream_master );
1196 for( i_packet = 0; i_packet < 10; i_packet++)
1198 #define p_stream p_sys->track[avi_pk.i_stream]
1200 avi_packet_t avi_pk;
1202 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1207 if( avi_pk.i_stream >= p_sys->i_track ||
1208 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1210 /* we haven't found an audio or video packet:
1211 * - we have seek, found first next packet
1212 * - others packets could be found, skip them
1214 switch( avi_pk.i_fourcc )
1216 case AVIFOURCC_JUNK:
1217 case AVIFOURCC_LIST:
1218 case AVIFOURCC_RIFF:
1219 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1220 case AVIFOURCC_idx1:
1223 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1225 return( 0 ); /* eof */
1228 "seems to have lost position, resync" );
1229 if( AVI_PacketSearch( p_demux ) )
1231 msg_Err( p_demux, "resync failed" );
1238 /* check for time */
1239 if( __ABS( AVI_GetPTS( p_stream ) -
1240 AVI_GetPTS( p_stream_master ) )< 600*1000 )
1242 /* load it and send to decoder */
1244 if( AVI_PacketRead( p_demux, &avi_pk, &p_frame ) || p_frame == NULL )
1248 p_frame->i_pts = AVI_GetPTS( p_stream ) + 1;
1250 if( avi_pk.i_cat != VIDEO_ES )
1251 p_frame->i_dts = p_frame->i_pts;
1254 p_frame->i_dts = p_frame->i_pts;
1258 //p_pes->i_rate = p_demux->stream.control.i_rate;
1259 es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1263 if( AVI_PacketNext( p_demux ) )
1269 /* *** update stream time position *** */
1270 if( p_stream->i_samplesize )
1272 p_stream->i_idxposb += avi_pk.i_size;
1276 if( p_stream->i_cat == AUDIO_ES )
1278 p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1280 p_stream->i_idxposc++;
1290 /*****************************************************************************
1291 * Seek: goto to i_date or i_percent
1292 *****************************************************************************/
1293 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1296 demux_sys_t *p_sys = p_demux->p_sys;
1297 unsigned int i_stream;
1298 msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1299 i_date / 1000000, i_percent );
1301 if( p_sys->b_seekable )
1303 if( !p_sys->i_length )
1305 avi_track_t *p_stream;
1308 /* use i_percent to create a true i_date */
1309 msg_Warn( p_demux, "seeking without index at %d%%"
1310 " only works for interleaved files", i_percent );
1311 if( i_percent >= 100 )
1313 msg_Warn( p_demux, "cannot seek so far !" );
1314 return VLC_EGENERIC;
1316 i_percent = __MAX( i_percent, 0 );
1318 /* try to find chunk that is at i_percent or the file */
1319 i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1320 p_sys->i_movi_begin );
1321 /* search first selected stream */
1322 for( i_stream = 0, p_stream = NULL;
1323 i_stream < p_sys->i_track; i_stream++ )
1325 p_stream = p_sys->track[i_stream];
1326 if( p_stream->b_activated )
1331 if( !p_stream || !p_stream->b_activated )
1333 msg_Warn( p_demux, "cannot find any selected stream" );
1334 return VLC_EGENERIC;
1337 /* be sure that the index exist */
1338 if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1340 msg_Warn( p_demux, "cannot seek" );
1341 return VLC_EGENERIC;
1344 while( i_pos >= p_stream->p_index[p_stream->i_idxposc].i_pos +
1345 p_stream->p_index[p_stream->i_idxposc].i_length + 8 )
1347 /* search after i_idxposc */
1348 if( AVI_StreamChunkSet( p_demux,
1349 i_stream, p_stream->i_idxposc + 1 ) )
1351 msg_Warn( p_demux, "cannot seek" );
1352 return VLC_EGENERIC;
1356 i_date = AVI_GetPTS( p_stream );
1357 /* TODO better support for i_samplesize != 0 */
1358 msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1362 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1364 avi_track_t *p_stream = p_sys->track[i_stream];
1366 if( !p_stream->b_activated )
1369 AVI_TrackSeek( p_demux, i_stream, i_date );
1371 p_sys->i_time = i_date;
1372 msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /1000000 );
1377 msg_Err( p_demux, "shouldn't yet be executed" );
1378 return VLC_EGENERIC;
1382 /*****************************************************************************
1384 *****************************************************************************/
1385 static double ControlGetPosition( demux_t *p_demux )
1387 demux_sys_t *p_sys = p_demux->p_sys;
1389 if( p_sys->i_length > 0 )
1391 return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)1000000 );
1393 else if( stream_Size( p_demux->s ) > 0 )
1399 /* search the more advanced selected es */
1400 for( i = 0; i < p_sys->i_track; i++ )
1402 avi_track_t *tk = p_sys->track[i];
1403 if( tk->b_activated && tk->i_idxposc < tk->i_idxnb )
1405 i_tmp = tk->p_index[tk->i_idxposc].i_pos +
1406 tk->p_index[tk->i_idxposc].i_length + 8;
1413 return (double)i64 / stream_Size( p_demux->s );
1418 static int Control( demux_t *p_demux, int i_query, va_list args )
1420 demux_sys_t *p_sys = p_demux->p_sys;
1428 case DEMUX_GET_POSITION:
1429 pf = (double*)va_arg( args, double * );
1430 *pf = ControlGetPosition( p_demux );
1432 case DEMUX_SET_POSITION:
1433 f = (double)va_arg( args, double );
1434 if( p_sys->b_seekable )
1436 i64 = (mtime_t)(1000000.0 * p_sys->i_length * f );
1437 return Seek( p_demux, i64, (int)(f * 100) );
1441 int64_t i_pos = stream_Size( p_demux->s ) * f;
1442 return stream_Seek( p_demux->s, i_pos );
1445 case DEMUX_GET_TIME:
1446 pi64 = (int64_t*)va_arg( args, int64_t * );
1447 *pi64 = p_sys->i_time;
1450 case DEMUX_SET_TIME:
1454 i64 = (int64_t)va_arg( args, int64_t );
1455 if( p_sys->i_length > 0 )
1457 i_percent = 100 * i64 / (p_sys->i_length*1000000);
1459 else if( p_sys->i_time > 0 )
1461 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1462 (double)i64 / (double)p_sys->i_time );
1464 return Seek( p_demux, i64, i_percent );
1466 case DEMUX_GET_LENGTH:
1467 pi64 = (int64_t*)va_arg( args, int64_t * );
1468 *pi64 = p_sys->i_length * (mtime_t)1000000;
1472 pf = (double*)va_arg( args, double * );
1474 for( i = 0; i < (int)p_sys->i_track; i++ )
1476 avi_track_t *tk = p_sys->track[i];
1477 if( tk->i_cat == VIDEO_ES && tk->i_scale > 0)
1479 *pf = (float)tk->i_rate / (float)tk->i_scale;
1484 case DEMUX_GET_META:
1485 p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1486 vlc_meta_Merge( p_meta, p_sys->meta );
1490 return VLC_EGENERIC;
1494 /*****************************************************************************
1495 * Function to convert pts to chunk or byte
1496 *****************************************************************************/
1498 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1503 return (mtime_t)((int64_t)i_pts *
1504 (int64_t)tk->i_rate /
1505 (int64_t)tk->i_scale /
1508 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1510 if( !tk->i_scale || !tk->i_samplesize )
1513 return (mtime_t)((int64_t)i_pts *
1514 (int64_t)tk->i_rate /
1515 (int64_t)tk->i_scale /
1517 (int64_t)tk->i_samplesize );
1520 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1527 i_dpts = (mtime_t)( (int64_t)1000000 *
1529 (int64_t)tk->i_scale /
1530 (int64_t)tk->i_rate );
1532 if( tk->i_samplesize )
1534 return i_dpts / tk->i_samplesize;
1539 static mtime_t AVI_GetPTS( avi_track_t *tk )
1541 if( tk->i_samplesize )
1543 int64_t i_count = 0;
1545 /* we need a valid entry we will emulate one */
1546 if( tk->i_idxposc == tk->i_idxnb )
1550 /* use the last entry */
1551 i_count = tk->p_index[tk->i_idxnb - 1].i_lengthtotal
1552 + tk->p_index[tk->i_idxnb - 1].i_length;
1557 i_count = tk->p_index[tk->i_idxposc].i_lengthtotal;
1559 return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1563 if( tk->i_cat == AUDIO_ES )
1565 return AVI_GetDPTS( tk, tk->i_blockno );
1569 return AVI_GetDPTS( tk, tk->i_idxposc );
1574 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1576 demux_sys_t *p_sys = p_demux->p_sys;
1577 avi_packet_t avi_pk;
1578 int i_loop_count = 0;
1580 /* find first chunk of i_stream that isn't in index */
1582 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1584 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1585 if( AVI_PacketNext( p_demux ) )
1587 return VLC_EGENERIC;
1592 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1597 if( p_demux->b_die ) return VLC_EGENERIC;
1599 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1601 msg_Warn( p_demux, "cannot get packet header" );
1602 return VLC_EGENERIC;
1604 if( avi_pk.i_stream >= p_sys->i_track ||
1605 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1607 if( AVI_PacketNext( p_demux ) )
1609 return VLC_EGENERIC;
1612 /* Prevents from eating all the CPU with broken files.
1613 * This value should be low enough so that it doesn't
1614 * affect the reading speed too much. */
1615 if( !(++i_loop_count % 1024) )
1617 if( p_demux->b_die ) return VLC_EGENERIC;
1620 if( !(i_loop_count % (1024 * 10)) )
1621 msg_Warn( p_demux, "don't seem to find any data..." );
1626 /* add this chunk to the index */
1629 index.i_id = avi_pk.i_fourcc;
1631 AVI_GetKeyFlag(p_sys->track[avi_pk.i_stream]->i_codec,
1633 index.i_pos = avi_pk.i_pos;
1634 index.i_length = avi_pk.i_size;
1635 AVI_IndexAddEntry( p_sys, avi_pk.i_stream, &index );
1637 if( avi_pk.i_stream == i_stream )
1642 if( AVI_PacketNext( p_demux ) )
1644 return VLC_EGENERIC;
1650 /* be sure that i_ck will be a valid index entry */
1651 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1654 demux_sys_t *p_sys = p_demux->p_sys;
1655 avi_track_t *p_stream = p_sys->track[i_stream];
1657 p_stream->i_idxposc = i_ck;
1658 p_stream->i_idxposb = 0;
1660 if( i_ck >= p_stream->i_idxnb )
1662 p_stream->i_idxposc = p_stream->i_idxnb - 1;
1665 p_stream->i_idxposc++;
1666 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1668 return VLC_EGENERIC;
1671 } while( p_stream->i_idxposc < i_ck );
1677 /* XXX FIXME up to now, we assume that all chunk are one after one */
1678 static int AVI_StreamBytesSet( demux_t *p_demux,
1679 unsigned int i_stream,
1682 demux_sys_t *p_sys = p_demux->p_sys;
1683 avi_track_t *p_stream = p_sys->track[i_stream];
1685 if( ( p_stream->i_idxnb > 0 )
1686 &&( i_byte < p_stream->p_index[p_stream->i_idxnb - 1].i_lengthtotal +
1687 p_stream->p_index[p_stream->i_idxnb - 1].i_length ) )
1689 /* index is valid to find the ck */
1690 /* uses dichototmie to be fast enougth */
1691 int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->i_idxnb - 1 );
1692 int i_idxmax = p_stream->i_idxnb;
1696 if( p_stream->p_index[i_idxposc].i_lengthtotal > i_byte )
1698 i_idxmax = i_idxposc ;
1699 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1703 if( p_stream->p_index[i_idxposc].i_lengthtotal +
1704 p_stream->p_index[i_idxposc].i_length <= i_byte)
1706 i_idxmin = i_idxposc ;
1707 i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1711 p_stream->i_idxposc = i_idxposc;
1712 p_stream->i_idxposb = i_byte -
1713 p_stream->p_index[i_idxposc].i_lengthtotal;
1722 p_stream->i_idxposc = p_stream->i_idxnb - 1;
1723 p_stream->i_idxposb = 0;
1726 p_stream->i_idxposc++;
1727 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1729 return VLC_EGENERIC;
1732 } while( p_stream->p_index[p_stream->i_idxposc].i_lengthtotal +
1733 p_stream->p_index[p_stream->i_idxposc].i_length <= i_byte );
1735 p_stream->i_idxposb = i_byte -
1736 p_stream->p_index[p_stream->i_idxposc].i_lengthtotal;
1741 static int AVI_TrackSeek( demux_t *p_demux,
1745 demux_sys_t *p_sys = p_demux->p_sys;
1746 avi_track_t *tk = p_sys->track[i_stream];
1748 #define p_stream p_sys->track[i_stream]
1751 i_oldpts = AVI_GetPTS( p_stream );
1753 if( !p_stream->i_samplesize )
1755 if( AVI_StreamChunkSet( p_demux,
1757 AVI_PTSToChunk( p_stream, i_date ) ) )
1759 return VLC_EGENERIC;
1762 if( p_stream->i_cat == AUDIO_ES )
1766 for( i = 0; i < tk->i_idxposc; i++ )
1768 if( tk->i_blocksize > 0 )
1770 tk->i_blockno += ( tk->p_index[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
1780 "old:%"PRId64" %s new %"PRId64,
1782 i_oldpts > i_date ? ">" : "<",
1785 if( p_stream->i_cat == VIDEO_ES )
1787 /* search key frame */
1788 //if( i_date < i_oldpts || 1 )
1790 while( p_stream->i_idxposc > 0 &&
1791 !( p_stream->p_index[p_stream->i_idxposc].i_flags &
1794 if( AVI_StreamChunkSet( p_demux,
1796 p_stream->i_idxposc - 1 ) )
1798 return VLC_EGENERIC;
1801 if( p_stream->p_es )
1802 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, p_stream->p_es, i_date );
1807 while( p_stream->i_idxposc < p_stream->i_idxnb &&
1808 !( p_stream->p_index[p_stream->i_idxposc].i_flags &
1811 if( AVI_StreamChunkSet( p_demux,
1813 p_stream->i_idxposc + 1 ) )
1815 return VLC_EGENERIC;
1824 if( AVI_StreamBytesSet( p_demux,
1826 AVI_PTSToByte( p_stream, i_date ) ) )
1828 return VLC_EGENERIC;
1835 /****************************************************************************
1836 * Return true if it's a key frame
1837 ****************************************************************************/
1838 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
1844 * startcode: 0x00000100 32bits
1845 * framenumber ? 5bits
1846 * piture type 0(I),1(P) 2bits
1848 if( GetDWBE( p_byte ) != 0x00000100 )
1850 /* it's not an msmpegv1 stream, strange...*/
1851 return AVIIF_KEYFRAME;
1853 return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
1856 case FOURCC_DIV3: /* wmv1 also */
1858 * picture type 0(I),1(P) 2bits
1860 return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
1862 /* we should find first occurrence of 0x000001b6 (32bits)
1863 * startcode: 0x000001b6 32bits
1864 * piture type 0(I),1(P) 2bits
1866 if( GetDWBE( p_byte ) != 0x000001b6 )
1868 /* not true , need to find the first VOP header */
1869 return AVIIF_KEYFRAME;
1871 return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
1874 /* I can't do it, so say yes */
1875 return AVIIF_KEYFRAME;
1879 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
1884 wf_tag_to_fourcc( i_codec, &i_codec, NULL );
1888 /* XXX DIV1 <- msmpeg4v1, DIV2 <- msmpeg4v2, DIV3 <- msmpeg4v3, mp4v for mpeg4 */
1892 return VLC_FOURCC('m','r','l','e');
1941 return VLC_FOURCC( 'u', 'n', 'd', 'f' );
1945 /****************************************************************************
1947 ****************************************************************************/
1948 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
1949 unsigned int *pi_number, unsigned int *pi_type )
1951 #define SET_PTR( p, v ) if( p ) *(p) = (v);
1954 c1 = ((uint8_t *)&i_id)[0];
1955 c2 = ((uint8_t *)&i_id)[1];
1957 if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
1959 SET_PTR( pi_number, 100 ); /* > max stream number */
1960 SET_PTR( pi_type, UNKNOWN_ES );
1964 SET_PTR( pi_number, (c1 - '0') * 10 + (c2 - '0' ) );
1965 switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
1968 SET_PTR( pi_type, AUDIO_ES );
1972 SET_PTR( pi_type, VIDEO_ES );
1975 SET_PTR( pi_type, UNKNOWN_ES );
1982 /****************************************************************************
1984 ****************************************************************************/
1985 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
1987 const uint8_t *p_peek;
1989 if( stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
1991 return VLC_EGENERIC;
1993 p_pk->i_fourcc = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
1994 p_pk->i_size = GetDWLE( p_peek + 4 );
1995 p_pk->i_pos = stream_Tell( p_demux->s );
1996 if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
1998 p_pk->i_type = VLC_FOURCC( p_peek[8], p_peek[9],
1999 p_peek[10], p_peek[11] );
2006 memcpy( p_pk->i_peek, p_peek + 8, 8 );
2008 AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
2012 static int AVI_PacketNext( demux_t *p_demux )
2014 avi_packet_t avi_ck;
2017 if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2019 return VLC_EGENERIC;
2022 if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2023 ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2027 else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2028 avi_ck.i_type == AVIFOURCC_AVIX )
2034 i_skip = __EVEN( avi_ck.i_size ) + 8;
2037 if( stream_Read( p_demux->s, NULL, i_skip ) != i_skip )
2039 return VLC_EGENERIC;
2044 static int AVI_PacketRead( demux_t *p_demux,
2046 block_t **pp_frame )
2050 i_size = __EVEN( p_pk->i_size + 8 );
2052 if( ( *pp_frame = stream_Block( p_demux->s, i_size ) ) == NULL )
2054 return VLC_EGENERIC;
2056 (*pp_frame)->p_buffer += 8;
2057 (*pp_frame)->i_buffer -= 8;
2059 if( i_size != p_pk->i_size + 8 )
2061 (*pp_frame)->i_buffer--;
2067 static int AVI_PacketSearch( demux_t *p_demux )
2069 demux_sys_t *p_sys = p_demux->p_sys;
2070 avi_packet_t avi_pk;
2075 if( stream_Read( p_demux->s, NULL, 1 ) != 1 )
2077 return VLC_EGENERIC;
2079 AVI_PacketGetHeader( p_demux, &avi_pk );
2080 if( avi_pk.i_stream < p_sys->i_track &&
2081 ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2085 switch( avi_pk.i_fourcc )
2087 case AVIFOURCC_JUNK:
2088 case AVIFOURCC_LIST:
2089 case AVIFOURCC_RIFF:
2090 case AVIFOURCC_idx1:
2094 /* Prevents from eating all the CPU with broken files.
2095 * This value should be low enough so that it doesn't affect the
2096 * reading speed too much (not that we care much anyway because
2097 * this code is called only on broken files). */
2098 if( !(++i_count % 1024) )
2100 if( p_demux->b_die ) return VLC_EGENERIC;
2103 if( !(i_count % (1024 * 10)) )
2104 msg_Warn( p_demux, "trying to resync..." );
2109 /****************************************************************************
2111 ****************************************************************************/
2112 static void AVI_IndexAddEntry( demux_sys_t *p_sys,
2114 avi_entry_t *p_index)
2116 avi_track_t *tk = p_sys->track[i_stream];
2118 /* Update i_movi_lastchunk_pos */
2119 if( p_sys->i_movi_lastchunk_pos < p_index->i_pos )
2121 p_sys->i_movi_lastchunk_pos = p_index->i_pos;
2125 if( tk->i_idxnb >= tk->i_idxmax )
2127 tk->i_idxmax += 16384;
2128 tk->p_index = realloc( tk->p_index,
2129 tk->i_idxmax * sizeof( avi_entry_t ) );
2130 if( tk->p_index == NULL )
2135 /* calculate cumulate length */
2136 if( tk->i_idxnb > 0 )
2138 p_index->i_lengthtotal =
2139 tk->p_index[tk->i_idxnb - 1].i_length +
2140 tk->p_index[tk->i_idxnb - 1].i_lengthtotal;
2144 p_index->i_lengthtotal = 0;
2147 tk->p_index[tk->i_idxnb++] = *p_index;
2150 static int AVI_IndexLoad_idx1( demux_t *p_demux )
2152 demux_sys_t *p_sys = p_demux->p_sys;
2154 avi_chunk_list_t *p_riff;
2155 avi_chunk_list_t *p_movi;
2156 avi_chunk_idx1_t *p_idx1;
2158 unsigned int i_stream;
2159 unsigned int i_index;
2165 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2166 p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2167 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2171 msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2172 return VLC_EGENERIC;
2175 /* *** calculate offset *** */
2176 /* Well, avi is __SHIT__ so test more than one entry
2177 * (needed for some avi files) */
2179 for( i = 0; i < __MIN( p_idx1->i_entry_count, 10 ); i++ )
2181 if( p_idx1->entry[i].i_pos < p_movi->i_chunk_pos )
2183 i_offset = p_movi->i_chunk_pos + 8;
2188 /* Reset b_keyset */
2189 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2190 b_keyset[i_stream] = false;
2192 for( i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2196 AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2199 if( i_stream < p_sys->i_track &&
2200 i_cat == p_sys->track[i_stream]->i_cat )
2203 index.i_id = p_idx1->entry[i_index].i_fourcc;
2205 p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2206 index.i_pos = p_idx1->entry[i_index].i_pos + i_offset;
2207 index.i_length = p_idx1->entry[i_index].i_length;
2208 AVI_IndexAddEntry( p_sys, i_stream, &index );
2210 if( index.i_flags&AVIIF_KEYFRAME )
2211 b_keyset[i_stream] = true;
2215 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2217 if( !b_keyset[i_stream] )
2219 avi_track_t *tk = p_sys->track[i_stream];
2221 msg_Dbg( p_demux, "no key frame set for track %d", i_stream );
2222 for( i_index = 0; i_index < tk->i_idxnb; i_index++ )
2223 tk->p_index[i_index].i_flags |= AVIIF_KEYFRAME;
2229 static void __Parse_indx( demux_t *p_demux,
2231 avi_chunk_indx_t *p_indx )
2233 demux_sys_t *p_sys = p_demux->p_sys;
2237 msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2238 if( p_indx->i_indexsubtype == 0 )
2240 for( i = 0; i < p_indx->i_entriesinuse; i++ )
2242 index.i_id = p_indx->i_id;
2243 index.i_flags = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2244 index.i_pos = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2245 index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2247 AVI_IndexAddEntry( p_sys, i_stream, &index );
2250 else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2252 for( i = 0; i < p_indx->i_entriesinuse; i++ )
2254 index.i_id = p_indx->i_id;
2255 index.i_flags = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2256 index.i_pos = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2257 index.i_length = p_indx->idx.field[i].i_size;
2259 AVI_IndexAddEntry( p_sys, i_stream, &index );
2264 msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2268 static void AVI_IndexLoad_indx( demux_t *p_demux )
2270 demux_sys_t *p_sys = p_demux->p_sys;
2271 unsigned int i_stream;
2274 avi_chunk_list_t *p_riff;
2275 avi_chunk_list_t *p_hdrl;
2277 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2278 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2280 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2282 avi_chunk_list_t *p_strl;
2283 avi_chunk_indx_t *p_indx;
2285 #define p_stream p_sys->track[i_stream]
2286 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2287 p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2291 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2296 if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2298 __Parse_indx( p_demux, i_stream, p_indx );
2300 else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2303 for( i = 0; i < p_indx->i_entriesinuse; i++ )
2305 if( stream_Seek( p_demux->s, p_indx->idx.super[i].i_offset )||
2306 AVI_ChunkRead( p_demux->s, &ck_sub, NULL ) )
2310 __Parse_indx( p_demux, i_stream, &ck_sub.indx );
2315 msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2321 static void AVI_IndexLoad( demux_t *p_demux )
2323 demux_sys_t *p_sys = p_demux->p_sys;
2324 unsigned int i_stream;
2326 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2328 p_sys->track[i_stream]->i_idxnb = 0;
2329 p_sys->track[i_stream]->i_idxmax = 0;
2330 p_sys->track[i_stream]->p_index = NULL;
2335 AVI_IndexLoad_indx( p_demux );
2337 else if( AVI_IndexLoad_idx1( p_demux ) )
2339 /* try indx if idx1 failed as some "normal" file have indx too */
2340 AVI_IndexLoad_indx( p_demux );
2343 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2345 msg_Dbg( p_demux, "stream[%d] created %d index entries",
2346 i_stream, p_sys->track[i_stream]->i_idxnb );
2350 static void AVI_IndexCreate( demux_t *p_demux )
2352 demux_sys_t *p_sys = p_demux->p_sys;
2354 avi_chunk_list_t *p_riff;
2355 avi_chunk_list_t *p_movi;
2357 unsigned int i_stream;
2360 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2361 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2365 msg_Err( p_demux, "cannot find p_movi" );
2369 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2371 p_sys->track[i_stream]->i_idxnb = 0;
2372 p_sys->track[i_stream]->i_idxmax = 0;
2373 p_sys->track[i_stream]->p_index = NULL;
2375 i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2376 stream_Size( p_demux->s ) );
2378 stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2379 msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2382 /* Only show dialog if AVI is > 10MB */
2383 p_demux->p_sys->i_dialog_id = -1;
2384 if( stream_Size( p_demux->s ) > 10000000 )
2386 p_demux->p_sys->i_dialog_id = intf_IntfProgress( p_demux,
2387 _( "Fixing AVI Index..." ),
2389 p_demux->p_sys->last_update = mdate();
2396 if( p_demux->b_die )
2401 /* Don't update dialog too often */
2402 if( p_demux->p_sys->i_dialog_id > 0 &&
2403 mdate() - p_demux->p_sys->last_update > 100000 )
2405 int64_t i_pos = stream_Tell( p_demux->s )* 100 /
2406 stream_Size( p_demux->s );
2407 float f_pos = (float)i_pos;
2408 p_demux->p_sys->last_update = mdate();
2409 intf_ProgressUpdate( p_demux, p_demux->p_sys->i_dialog_id,
2410 _( "Fixing AVI Index..." ), f_pos, -1 );
2413 if( AVI_PacketGetHeader( p_demux, &pk ) )
2417 if( pk.i_stream < p_sys->i_track &&
2418 pk.i_cat == p_sys->track[pk.i_stream]->i_cat )
2421 index.i_id = pk.i_fourcc;
2423 AVI_GetKeyFlag(p_sys->track[pk.i_stream]->i_codec, pk.i_peek);
2424 index.i_pos = pk.i_pos;
2425 index.i_length = pk.i_size;
2426 AVI_IndexAddEntry( p_sys, pk.i_stream, &index );
2430 switch( pk.i_fourcc )
2432 case AVIFOURCC_idx1:
2435 avi_chunk_list_t *p_sysx;
2436 p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2437 AVIFOURCC_RIFF, 1 );
2439 msg_Dbg( p_demux, "looking for new RIFF chunk" );
2440 if( stream_Seek( p_demux->s, p_sysx->i_chunk_pos + 24))
2447 case AVIFOURCC_RIFF:
2448 msg_Dbg( p_demux, "new RIFF chunk found" );
2450 case AVIFOURCC_JUNK:
2453 msg_Warn( p_demux, "need resync, probably broken avi" );
2454 if( AVI_PacketSearch( p_demux ) )
2456 msg_Warn( p_demux, "lost sync, abord index creation" );
2462 if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2463 AVI_PacketNext( p_demux ) )
2470 if( p_demux->p_sys->i_dialog_id > 0 )
2472 intf_UserHide( p_demux, p_demux->p_sys->i_dialog_id );
2475 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2478 "stream[%d] creating %d index entries",
2480 p_sys->track[i_stream]->i_idxnb );
2484 /*****************************************************************************
2486 *****************************************************************************/
2487 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
2489 demux_sys_t *p_sys = p_demux->p_sys;
2493 for( i = 0; i < p_sys->i_track; i++ )
2495 avi_track_t *tk = p_sys->track[i];
2496 if( tk->i_idxposc >= tk->i_idxnb )
2498 tk->b_activated = false;
2499 if( tk->p_es ) es_out_Control( p_demux->out, ES_OUT_SET_ES_STATE, tk->p_es, false );
2509 /****************************************************************************
2510 * AVI_MovieGetLength give max streams length in second
2511 ****************************************************************************/
2512 static mtime_t AVI_MovieGetLength( demux_t *p_demux )
2514 demux_sys_t *p_sys = p_demux->p_sys;
2515 mtime_t i_maxlength = 0;
2518 for( i = 0; i < p_sys->i_track; i++ )
2520 avi_track_t *tk = p_sys->track[i];
2523 /* fix length for each stream */
2524 if( tk->i_idxnb < 1 || !tk->p_index )
2529 if( tk->i_samplesize )
2531 i_length = AVI_GetDPTS( tk,
2532 tk->p_index[tk->i_idxnb-1].i_lengthtotal +
2533 tk->p_index[tk->i_idxnb-1].i_length );
2537 i_length = AVI_GetDPTS( tk, tk->i_idxnb );
2539 i_length /= (mtime_t)1000000; /* in seconds */
2542 "stream[%d] length:%"PRId64" (based on index)",
2545 i_maxlength = __MAX( i_maxlength, i_length );