1 /*****************************************************************************
2 * avi.c : AVI file Stream input module for vlc
3 *****************************************************************************
4 * Copyright (C) 2001-2009 VLC authors and VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
9 * This program is free software; you can redistribute it and/or modify it
10 * under the terms of the GNU Lesser General Public License as published by
11 * the Free Software Foundation; either version 2.1 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public License
20 * along with this program; if not, write to the Free Software Foundation,
21 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
22 *****************************************************************************/
24 /*****************************************************************************
26 *****************************************************************************/
34 #include <vlc_common.h>
35 #include <vlc_plugin.h>
36 #include <vlc_demux.h>
37 #include <vlc_input.h>
39 #include <vlc_dialog.h>
42 #include <vlc_codecs.h>
43 #include <vlc_charset.h>
44 #include <vlc_memory.h>
49 /*****************************************************************************
51 *****************************************************************************/
53 #define INTERLEAVE_TEXT N_("Force interleaved method" )
55 #define INDEX_TEXT N_("Force index creation")
56 #define INDEX_LONGTEXT N_( \
57 "Recreate a index for the AVI file. Use this if your AVI file is damaged "\
58 "or incomplete (not seekable)." )
60 #define BI_RAWRGB 0x00
61 #define BI_RGBBITFIELDS 0x03
63 static int Open ( vlc_object_t * );
64 static void Close( vlc_object_t * );
66 static const int pi_index[] = {0,1,2,3};
68 static const char *const ppsz_indexes[] = { N_("Ask for action"),
71 N_("Fix when necessary")};
74 set_shortname( "AVI" )
75 set_description( N_("AVI demuxer") )
76 set_capability( "demux", 212 )
77 set_category( CAT_INPUT )
78 set_subcategory( SUBCAT_INPUT_DEMUX )
80 add_bool( "avi-interleaved", false,
81 INTERLEAVE_TEXT, INTERLEAVE_TEXT, true )
82 add_integer( "avi-index", 0,
83 INDEX_TEXT, INDEX_LONGTEXT, false )
84 change_integer_list( pi_index, ppsz_indexes )
86 set_callbacks( Open, Close )
89 /*****************************************************************************
91 *****************************************************************************/
92 static int Control ( demux_t *, int, va_list );
93 static int Seek ( demux_t *, mtime_t, int );
94 static int Demux_Seekable ( demux_t * );
95 static int Demux_UnSeekable( demux_t * );
97 static char *FromACP( const char *str )
99 return FromCharset(vlc_pgettext("GetACP", "CP1252"), str, strlen(str));
102 #define IGNORE_ES NAV_ES
106 vlc_fourcc_t i_fourcc;
109 vlc_fourcc_t i_type; /* only for AVIFOURCC_LIST */
111 uint8_t i_peek[8]; /* first 8 bytes */
113 unsigned int i_stream;
124 int64_t i_lengthtotal;
132 avi_entry_t *p_entry;
135 static void avi_index_Init( avi_index_t * );
136 static void avi_index_Clean( avi_index_t * );
137 static void avi_index_Append( avi_index_t *, off_t *, avi_entry_t * );
144 unsigned int i_cat; /* AUDIO_ES, VIDEO_ES */
145 vlc_fourcc_t i_codec;
149 unsigned int i_samplesize;
151 unsigned int i_width_bytes;
157 es_out_id_t *p_es_dv_audio;
162 unsigned int i_idxposc; /* numero of chunk */
163 unsigned int i_idxposb; /* byte in the current chunk */
165 /* For VBR audio only */
166 unsigned int i_blockno;
167 unsigned int i_blocksize;
178 bool b_indexloaded; /* if we read indexes from end of file before starting */
179 uint32_t i_avih_flags;
185 off_t i_movi_lastchunk_pos; /* XXX position of last valid chunk */
187 /* number of streams and information */
188 unsigned int i_track;
194 unsigned int i_attachment;
195 input_attachment_t **attachment;
198 static inline off_t __EVEN( off_t i )
200 return (i & 1) ? i + 1 : i;
203 static mtime_t AVI_PTSToChunk( avi_track_t *, mtime_t i_pts );
204 static mtime_t AVI_PTSToByte ( avi_track_t *, mtime_t i_pts );
205 static mtime_t AVI_GetDPTS ( avi_track_t *, int64_t i_count );
206 static mtime_t AVI_GetPTS ( avi_track_t * );
209 static int AVI_StreamChunkFind( demux_t *, unsigned int i_stream );
210 static int AVI_StreamChunkSet ( demux_t *,
211 unsigned int i_stream, unsigned int i_ck );
212 static int AVI_StreamBytesSet ( demux_t *,
213 unsigned int i_stream, off_t i_byte );
215 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t );
216 static int AVI_GetKeyFlag ( vlc_fourcc_t , uint8_t * );
218 static int AVI_PacketGetHeader( demux_t *, avi_packet_t *p_pk );
219 static int AVI_PacketNext ( demux_t * );
220 static int AVI_PacketRead ( demux_t *, avi_packet_t *, block_t **);
221 static int AVI_PacketSearch ( demux_t * );
223 static void AVI_IndexLoad ( demux_t * );
224 static void AVI_IndexCreate ( demux_t * );
226 static void AVI_ExtractSubtitle( demux_t *, unsigned int i_stream, avi_chunk_list_t *, avi_chunk_STRING_t * );
228 static void AVI_DvHandleAudio( demux_t *, avi_track_t *, block_t * );
230 static mtime_t AVI_MovieGetLength( demux_t * );
232 static void AVI_MetaLoad( demux_t *, avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih );
234 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
235 const int i_header, const int i_size );
237 /*****************************************************************************
239 *****************************************************************************/
240 static int AVI_TrackSeek ( demux_t *, int, mtime_t );
241 static int AVI_TrackStopFinishedStreams( demux_t *);
244 - For VBR mp3 stream:
245 count blocks by rounded-up chunksizes instead of chunks
246 we need full emulation of dshow avi demuxer bugs :(
247 fixes silly nandub-style a-v delaying in avi with vbr mp3...
248 (from mplayer 2002/08/02)
252 /*****************************************************************************
253 * Open: check file and initializes AVI structures
254 *****************************************************************************/
255 static int Open( vlc_object_t * p_this )
257 demux_t *p_demux = (demux_t *)p_this;
260 bool b_index = false, b_aborted = false;
263 avi_chunk_list_t *p_riff;
264 avi_chunk_list_t *p_hdrl, *p_movi;
265 avi_chunk_avih_t *p_avih;
267 unsigned int i_track;
268 unsigned int i, i_peeker;
270 const uint8_t *p_peek;
272 /* Is it an avi file ? */
273 if( stream_Peek( p_demux->s, &p_peek, 200 ) < 200 ) return VLC_EGENERIC;
275 for( i_peeker = 0; i_peeker < 188; i_peeker++ )
277 if( !strncmp( (char *)&p_peek[0], "RIFF", 4 ) && !strncmp( (char *)&p_peek[8], "AVI ", 4 ) )
279 if( !strncmp( (char *)&p_peek[0], "ON2 ", 4 ) && !strncmp( (char *)&p_peek[8], "ON2f", 4 ) )
283 if( i_peeker == 188 )
288 /* Initialize input structures. */
289 p_sys = p_demux->p_sys = calloc( 1, sizeof(demux_sys_t) );
290 p_sys->b_odml = false;
293 TAB_INIT(p_sys->i_attachment, p_sys->attachment);
295 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &p_sys->b_fastseekable );
296 stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
298 p_demux->pf_control = Control;
299 p_demux->pf_demux = Demux_Seekable;
301 /* For unseekable stream, automatically use Demux_UnSeekable */
302 if( !p_sys->b_seekable
303 || var_InheritBool( p_demux, "avi-interleaved" ) )
305 p_demux->pf_demux = Demux_UnSeekable;
310 stream_Read( p_demux->s, NULL, i_peeker );
313 if( AVI_ChunkReadRoot( p_demux->s, &p_sys->ck_root ) )
315 msg_Err( p_demux, "avi module discarded (invalid file)" );
320 if( AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF ) > 1 )
322 unsigned int i_count =
323 AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF );
325 msg_Warn( p_demux, "multiple riff -> OpenDML ?" );
326 for( i = 1; i < i_count; i++ )
328 avi_chunk_list_t *p_sysx;
330 p_sysx = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, i );
331 if( p_sysx->i_type == AVIFOURCC_AVIX )
333 msg_Warn( p_demux, "detected OpenDML file" );
334 p_sys->b_odml = true;
340 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
341 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
342 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0 );
344 p_movi = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_movi, 0 );
346 if( !p_hdrl || !p_movi )
348 msg_Err( p_demux, "invalid file: cannot find hdrl or movi chunks" );
352 if( !( p_avih = AVI_ChunkFind( p_hdrl, AVIFOURCC_avih, 0 ) ) )
354 msg_Err( p_demux, "invalid file: cannot find avih chunk" );
357 i_track = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
358 if( p_avih->i_streams != i_track )
361 "found %d stream but %d are declared",
362 i_track, p_avih->i_streams );
366 msg_Err( p_demux, "no stream defined!" );
370 /* print information on streams */
371 msg_Dbg( p_demux, "AVIH: %d stream, flags %s%s%s%s ",
373 p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
374 p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
375 p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
376 p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
378 AVI_MetaLoad( p_demux, p_riff, p_avih );
379 p_sys->i_avih_flags = p_avih->i_flags;
381 /* now read info on each stream and create ES */
382 for( i = 0 ; i < i_track; i++ )
384 avi_track_t *tk = calloc( 1, sizeof( avi_track_t ) );
385 if( unlikely( !tk ) )
388 avi_chunk_list_t *p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
389 avi_chunk_strh_t *p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
390 avi_chunk_STRING_t *p_strn = AVI_ChunkFind( p_strl, AVIFOURCC_strn, 0 );
391 avi_chunk_strf_auds_t *p_auds = NULL;
392 avi_chunk_strf_vids_t *p_vids = NULL;
396 tk->b_activated = true;
398 p_vids = (avi_chunk_strf_vids_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
399 p_auds = (avi_chunk_strf_auds_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
401 if( p_strl == NULL || p_strh == NULL || p_auds == NULL || p_vids == NULL )
403 msg_Warn( p_demux, "stream[%d] incomplete", i );
408 tk->i_rate = p_strh->i_rate;
409 tk->i_scale = p_strh->i_scale;
410 tk->i_samplesize = p_strh->i_samplesize;
411 msg_Dbg( p_demux, "stream[%d] rate:%d scale:%d samplesize:%d",
412 i, tk->i_rate, tk->i_scale, tk->i_samplesize );
414 switch( p_strh->i_type )
416 case( AVIFOURCC_auds ):
417 tk->i_cat = AUDIO_ES;
418 if( p_auds->p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
419 p_auds->p_wf->cbSize >= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) )
421 WAVEFORMATEXTENSIBLE *p_wfe = (WAVEFORMATEXTENSIBLE *)p_auds->p_wf;
422 tk->i_codec = AVI_FourccGetCodec( AUDIO_ES,
423 p_wfe->SubFormat.Data1 );
426 tk->i_codec = AVI_FourccGetCodec( AUDIO_ES,
427 p_auds->p_wf->wFormatTag );
429 tk->i_blocksize = p_auds->p_wf->nBlockAlign;
430 if( tk->i_blocksize == 0 )
432 if( p_auds->p_wf->wFormatTag == 1 )
433 tk->i_blocksize = p_auds->p_wf->nChannels * (p_auds->p_wf->wBitsPerSample/8);
437 else if( tk->i_samplesize != 0 && tk->i_samplesize != tk->i_blocksize )
439 msg_Warn( p_demux, "track[%d] samplesize=%d and blocksize=%d are not equal."
440 "Using blocksize as a workaround.",
441 i, tk->i_samplesize, tk->i_blocksize );
442 tk->i_samplesize = tk->i_blocksize;
445 if( tk->i_codec == VLC_CODEC_VORBIS )
447 tk->i_blocksize = 0; /* fix vorbis VBR decoding */
450 es_format_Init( &fmt, AUDIO_ES, tk->i_codec );
452 fmt.audio.i_channels = p_auds->p_wf->nChannels;
453 fmt.audio.i_rate = p_auds->p_wf->nSamplesPerSec;
454 fmt.i_bitrate = p_auds->p_wf->nAvgBytesPerSec*8;
455 fmt.audio.i_blockalign = p_auds->p_wf->nBlockAlign;
456 fmt.audio.i_bitspersample = p_auds->p_wf->wBitsPerSample;
457 fmt.b_packetized = !tk->i_blocksize;
460 "stream[%d] audio(0x%x - %s) %d channels %dHz %dbits",
461 i, p_auds->p_wf->wFormatTag,vlc_fourcc_GetDescription(AUDIO_ES,tk->i_codec),
462 p_auds->p_wf->nChannels,
463 p_auds->p_wf->nSamplesPerSec,
464 p_auds->p_wf->wBitsPerSample );
466 fmt.i_extra = __MIN( p_auds->p_wf->cbSize,
467 p_auds->i_chunk_size - sizeof(WAVEFORMATEX) );
468 if( fmt.i_extra > 0 )
470 fmt.p_extra = malloc( fmt.i_extra );
471 if( unlikely(fmt.p_extra == NULL) )
476 memcpy( fmt.p_extra, &p_auds->p_wf[1], fmt.i_extra );
480 case( AVIFOURCC_vids ):
482 tk->i_cat = VIDEO_ES;
483 tk->i_codec = AVI_FourccGetCodec( VIDEO_ES,
484 p_vids->p_bih->biCompression );
485 if( p_vids->p_bih->biCompression == VLC_FOURCC( 'D', 'X', 'S', 'B' ) )
487 msg_Dbg( p_demux, "stream[%d] subtitles", i );
488 es_format_Init( &fmt, SPU_ES, p_vids->p_bih->biCompression );
492 else if( p_vids->p_bih->biCompression == BI_RAWRGB )
494 switch( p_vids->p_bih->biBitCount )
497 tk->i_codec = VLC_CODEC_RGB32;
500 tk->i_codec = VLC_CODEC_RGB24;
502 case 16: /* Yes it is RV15 */
504 tk->i_codec = VLC_CODEC_RGB15;
506 case 9: /* <- TODO check that */
507 tk->i_codec = VLC_CODEC_I410;
510 if ( p_vids->p_bih->biClrUsed )
511 tk->i_codec = VLC_CODEC_RGBP;
513 tk->i_codec = VLC_CODEC_GREY;
516 es_format_Init( &fmt, VIDEO_ES, tk->i_codec );
518 switch( tk->i_codec )
520 case VLC_CODEC_RGB24:
521 case VLC_CODEC_RGB32:
522 fmt.video.i_rmask = 0x00ff0000;
523 fmt.video.i_gmask = 0x0000ff00;
524 fmt.video.i_bmask = 0x000000ff;
526 case VLC_CODEC_RGB15:
527 fmt.video.i_rmask = 0x7c00;
528 fmt.video.i_gmask = 0x03e0;
529 fmt.video.i_bmask = 0x001f;
533 const VLC_BITMAPINFO *p_bi = (const VLC_BITMAPINFO *) p_vids->p_bih;
534 fmt.video.p_palette = malloc( sizeof(video_palette_t) );
535 if ( fmt.video.p_palette )
538 for ( uint32_t i=0; i<p_vids->p_bih->biClrUsed; i++ )
540 entry = GetDWBE( &p_bi->bmiColors[i] );
541 fmt.video.p_palette->palette[i][0] = entry >> 24;
542 fmt.video.p_palette->palette[i][1] = (entry >> 16) & 0xFF;
543 fmt.video.p_palette->palette[i][2] = (entry >> 8) & 0xFF;
544 fmt.video.p_palette->palette[i][3] = entry & 0xFF;
546 fmt.video.p_palette->i_entries = p_vids->p_bih->biClrUsed;
554 tk->i_width_bytes = p_vids->p_bih->biWidth * (p_vids->p_bih->biBitCount >> 3);
555 /* RGB DIB are coded from bottom to top */
556 if ( p_vids->p_bih->biHeight < INT32_MAX ) tk->b_flipped = true;
560 es_format_Init( &fmt, VIDEO_ES, p_vids->p_bih->biCompression );
561 if( tk->i_codec == VLC_CODEC_MP4V &&
562 !strncasecmp( (char*)&p_strh->i_handler, "XVID", 4 ) )
565 fmt.i_original_fourcc = VLC_FOURCC( 'X', 'V', 'I', 'D' );
568 tk->i_samplesize = 0;
570 fmt.video.i_width = p_vids->p_bih->biWidth;
571 fmt.video.i_height = p_vids->p_bih->biHeight;
572 fmt.video.i_bits_per_pixel = p_vids->p_bih->biBitCount;
573 fmt.video.i_frame_rate = tk->i_rate;
574 fmt.video.i_frame_rate_base = tk->i_scale;
576 /* Uncompresse Bitmap or YUV, YUV being always topdown */
577 if ( fmt.video.i_height > INT32_MAX )
579 (unsigned int)(-(int)p_vids->p_bih->biHeight);
581 avi_chunk_vprp_t *p_vprp = AVI_ChunkFind( p_strl, AVIFOURCC_vprp, 0 );
584 uint32_t i_frame_aspect_ratio = p_vprp->i_frame_aspect_ratio;
585 if( p_vprp->i_video_format_token >= 1 &&
586 p_vprp->i_video_format_token <= 4 )
587 i_frame_aspect_ratio = 0x00040003;
588 fmt.video.i_sar_num = ((i_frame_aspect_ratio >> 16) & 0xffff) * fmt.video.i_height;
589 fmt.video.i_sar_den = ((i_frame_aspect_ratio >> 0) & 0xffff) * fmt.video.i_width;
591 /* Extradata is the remainder of the chunk less the BIH */
592 fmt.i_extra = p_vids->i_chunk_size - sizeof(VLC_BITMAPINFOHEADER);
593 if( fmt.i_extra > 0 )
595 fmt.p_extra = malloc( fmt.i_extra );
596 if( unlikely(fmt.p_extra == NULL) )
601 memcpy( fmt.p_extra, &p_vids->p_bih[1], fmt.i_extra );
604 msg_Dbg( p_demux, "stream[%d] video(%4.4s) %"PRIu32"x%"PRIu32" %dbpp %ffps",
605 i, (char*)&p_vids->p_bih->biCompression,
606 (uint32_t)p_vids->p_bih->biWidth,
607 (uint32_t)p_vids->p_bih->biHeight,
608 p_vids->p_bih->biBitCount,
609 (float)tk->i_rate/(float)tk->i_scale );
611 /* Extract palette from extradata if bpp <= 8 */
612 if( fmt.video.i_bits_per_pixel > 0 && fmt.video.i_bits_per_pixel <= 8 )
614 /* The palette should not be included in biSize, but come
615 * directly after BITMAPINFORHEADER in the BITMAPINFO structure */
616 if( fmt.i_extra > 0 && fmt.p_extra )
618 const uint8_t *p_pal = fmt.p_extra;
620 fmt.video.p_palette = calloc( 1, sizeof(video_palette_t) );
621 fmt.video.p_palette->i_entries = __MIN(fmt.i_extra/4, 256);
623 for( int k = 0; k < fmt.video.p_palette->i_entries; k++ )
625 for( int j = 0; j < 4; j++ )
626 fmt.video.p_palette->palette[k][j] = p_pal[4*k+j];
633 case( AVIFOURCC_txts):
634 msg_Dbg( p_demux, "stream[%d] subtitle attachment", i );
635 AVI_ExtractSubtitle( p_demux, i, p_strl, p_strn );
639 case( AVIFOURCC_iavs):
640 case( AVIFOURCC_ivas):
641 msg_Dbg( p_demux, "stream[%d] iavs with handler %4.4s", i, (char *)&p_strh->i_handler );
642 tk->i_cat = VIDEO_ES;
643 tk->i_codec = AVI_FourccGetCodec( VIDEO_ES, p_strh->i_handler );
644 tk->i_samplesize = 0;
645 tk->i_dv_audio_rate = tk->i_codec == VLC_CODEC_DV ? -1 : 0;
647 es_format_Init( &fmt, VIDEO_ES, p_strh->i_handler );
648 fmt.video.i_width = p_avih->i_width;
649 fmt.video.i_height = p_avih->i_height;
652 case( AVIFOURCC_mids):
653 msg_Dbg( p_demux, "stream[%d] midi is UNSUPPORTED", i );
656 msg_Warn( p_demux, "stream[%d] unknown type %4.4s", i, (char *)&p_strh->i_type );
661 fmt.psz_description = FromACP( p_strn->p_str );
662 tk->p_es = es_out_Add( p_demux->out, &fmt );
663 TAB_APPEND( p_sys->i_track, p_sys->track, tk );
664 es_format_Clean( &fmt );
667 if( p_sys->i_track <= 0 )
669 msg_Err( p_demux, "no valid track" );
673 i_do_index = var_InheritInteger( p_demux, "avi-index" );
674 if( i_do_index == 1 ) /* Always fix */
677 if( p_sys->b_fastseekable )
679 AVI_IndexCreate( p_demux );
683 msg_Warn( p_demux, "cannot create index (unseekable stream)" );
684 AVI_IndexLoad( p_demux );
689 AVI_IndexLoad( p_demux );
692 /* *** movie length in sec *** */
693 p_sys->i_length = AVI_MovieGetLength( p_demux );
695 /* Check the index completeness */
696 unsigned int i_idx_totalframes = 0;
697 for( unsigned int i = 0; i < p_sys->i_track; i++ )
699 const avi_track_t *tk = p_sys->track[i];
700 if( tk->i_cat == VIDEO_ES && tk->idx.p_entry )
701 i_idx_totalframes = __MAX(i_idx_totalframes, tk->idx.i_size);
703 if( i_idx_totalframes != p_avih->i_totalframes &&
704 p_sys->i_length < (mtime_t)p_avih->i_totalframes *
705 (mtime_t)p_avih->i_microsecperframe /
708 if( !vlc_object_alive( p_demux) )
711 msg_Warn( p_demux, "broken or missing index, 'seek' will be "
712 "approximative or will exhibit strange behavior" );
713 if( (i_do_index == 0 || i_do_index == 3) && !b_index )
715 if( !p_sys->b_fastseekable ) {
719 if( i_do_index == 0 )
721 switch( dialog_Question( p_demux, _("Broken or missing AVI Index") ,
722 _( "Because this AVI file index is broken or missing, "
723 "seeking will not work correctly.\n"
724 "VLC won't repair your file but can temporary fix this "
725 "problem by building an index in memory.\n"
726 "This step might take a long time on a large file.\n"
727 "What do you want to do?" ),
728 _( "Build index then play" ), _( "Play as is" ), _( "Do not play") ) )
732 msg_Dbg( p_demux, "Fixing AVI index" );
742 msg_Dbg( p_demux, "Fixing AVI index" );
748 /* fix some BeOS MediaKit generated file */
749 for( i = 0 ; i < p_sys->i_track; i++ )
751 avi_track_t *tk = p_sys->track[i];
752 avi_chunk_list_t *p_strl;
753 avi_chunk_strf_auds_t *p_auds;
755 if( tk->i_cat != AUDIO_ES )
759 if( tk->idx.i_size < 1 ||
761 tk->i_samplesize != 0 )
765 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
766 p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
768 if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
769 (unsigned int)tk->i_rate == p_auds->p_wf->nSamplesPerSec )
771 int64_t i_track_length =
772 tk->idx.p_entry[tk->idx.i_size-1].i_length +
773 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal;
774 mtime_t i_length = (mtime_t)p_avih->i_totalframes *
775 (mtime_t)p_avih->i_microsecperframe;
779 msg_Warn( p_demux, "track[%d] cannot be fixed (BeOS MediaKit generated)", i );
782 tk->i_samplesize = 1;
783 tk->i_rate = i_track_length * (int64_t)1000000/ i_length;
784 msg_Warn( p_demux, "track[%d] fixed with rate=%d scale=%d (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
788 if( p_sys->b_seekable )
790 /* we have read all chunk so go back to movi */
791 stream_Seek( p_demux->s, p_movi->i_chunk_pos );
793 /* Skip movi header */
794 stream_Read( p_demux->s, NULL, 12 );
796 p_sys->i_movi_begin = p_movi->i_chunk_pos;
800 for( unsigned i = 0; i < p_sys->i_attachment; i++)
801 vlc_input_attachment_Delete(p_sys->attachment[i]);
802 free(p_sys->attachment);
805 vlc_meta_Delete( p_sys->meta );
807 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
809 return b_aborted ? VLC_ETIMEOUT : VLC_EGENERIC;
812 /*****************************************************************************
813 * Close: frees unused data
814 *****************************************************************************/
815 static void Close ( vlc_object_t * p_this )
817 demux_t * p_demux = (demux_t *)p_this;
818 demux_sys_t *p_sys = p_demux->p_sys ;
820 for( unsigned int i = 0; i < p_sys->i_track; i++ )
822 if( p_sys->track[i] )
824 avi_index_Clean( &p_sys->track[i]->idx );
825 free( p_sys->track[i] );
828 free( p_sys->track );
830 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
831 vlc_meta_Delete( p_sys->meta );
833 for( unsigned i = 0; i < p_sys->i_attachment; i++)
834 vlc_input_attachment_Delete(p_sys->attachment[i]);
835 free(p_sys->attachment);
840 /*****************************************************************************
841 * ReadFrame: Reads frame, using stride if necessary
842 *****************************************************************************/
844 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
845 const int i_header, const int i_size )
847 block_t *p_frame = stream_Block( p_demux->s, __EVEN( i_size ) );
848 if ( !p_frame ) return p_frame;
850 if( i_size % 2 ) /* read was padded on word boundary */
856 if( tk->i_idxposb == 0 )
858 p_frame->p_buffer += i_header;
859 p_frame->i_buffer -= i_header;
862 if ( !tk->i_width_bytes )
865 const unsigned int i_stride_bytes = ((( (tk->i_width_bytes << 3) + 31) & ~31) >> 3);
867 if ( p_frame->i_buffer < i_stride_bytes )
869 p_frame->i_buffer = 0;
875 const uint8_t *p_src = p_frame->p_buffer + i_stride_bytes;
876 const uint8_t *p_end = p_frame->p_buffer + p_frame->i_buffer;
877 uint8_t *p_dst = p_frame->p_buffer + tk->i_width_bytes;
879 p_frame->i_buffer = tk->i_width_bytes;
881 while ( p_src + i_stride_bytes <= p_end )
883 memmove( p_dst, p_src, tk->i_width_bytes );
884 p_src += i_stride_bytes;
885 p_dst += tk->i_width_bytes;
886 p_frame->i_buffer += tk->i_width_bytes;
891 block_t *p_flippedframe = block_Alloc( p_frame->i_buffer );
892 if ( !p_flippedframe )
894 block_Release( p_frame );
898 unsigned int i_lines = p_frame->i_buffer / i_stride_bytes;
899 const uint8_t *p_src = p_frame->p_buffer + i_lines * i_stride_bytes;
900 uint8_t *p_dst = p_flippedframe->p_buffer;
902 p_flippedframe->i_buffer = 0;
904 while ( i_lines-- > 0 )
906 p_src -= i_stride_bytes;
907 memcpy( p_dst, p_src, tk->i_width_bytes );
908 p_dst += tk->i_width_bytes;
909 p_flippedframe->i_buffer += tk->i_width_bytes;
912 block_Release( p_frame );
913 p_frame = p_flippedframe;
919 /*****************************************************************************
920 * Demux_Seekable: reads and demuxes data packets for stream seekable
921 *****************************************************************************
922 * AVIDemux: reads and demuxes data packets
923 *****************************************************************************
924 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
925 *****************************************************************************/
932 off_t i_posf; /* where we will read :
933 if i_idxposb == 0 : begining of chunk (+8 to acces data)
934 else : point on data directly */
935 } avi_track_toread_t;
937 static int Demux_Seekable( demux_t *p_demux )
939 demux_sys_t *p_sys = p_demux->p_sys;
941 unsigned int i_track_count = 0;
942 unsigned int i_track;
943 /* cannot be more than 100 stream (dcXX or wbXX) */
944 avi_track_toread_t toread[100];
947 /* detect new selected/unselected streams */
948 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
950 avi_track_t *tk = p_sys->track[i_track];
953 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
954 if( tk->p_es_dv_audio )
957 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
960 if( b && !tk->b_activated )
962 if( p_sys->b_seekable)
964 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
966 tk->b_activated = true;
968 else if( !b && tk->b_activated )
970 tk->b_activated = false;
978 if( i_track_count <= 0 )
980 int64_t i_length = p_sys->i_length * (mtime_t)1000000;
982 p_sys->i_time += 25*1000; /* read 25ms */
985 if( p_sys->i_time >= i_length )
989 msg_Warn( p_demux, "no track selected, exiting..." );
993 /* wait for the good time */
994 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
995 p_sys->i_time += 25*1000; /* read 25ms */
998 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1000 avi_track_t *tk = p_sys->track[i_track];
1003 toread[i_track].b_ok = tk->b_activated && !tk->b_eof;
1004 if( tk->i_idxposc < tk->idx.i_size )
1006 toread[i_track].i_posf = tk->idx.p_entry[tk->i_idxposc].i_pos;
1007 if( tk->i_idxposb > 0 )
1009 toread[i_track].i_posf += 8 + tk->i_idxposb;
1014 toread[i_track].i_posf = -1;
1017 i_dpts = p_sys->i_time - AVI_GetPTS( tk );
1019 if( tk->i_samplesize )
1021 toread[i_track].i_toread = AVI_PTSToByte( tk, llabs( i_dpts ) );
1025 toread[i_track].i_toread = AVI_PTSToChunk( tk, llabs( i_dpts ) );
1030 toread[i_track].i_toread *= -1;
1043 /* search for first chunk to be read */
1044 for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
1046 if( !toread[i].b_ok ||
1047 AVI_GetDPTS( p_sys->track[i],
1048 toread[i].i_toread ) <= -25 * 1000 )
1053 if( toread[i].i_toread > 0 )
1055 b_done = false; /* not yet finished */
1057 if( toread[i].i_posf > 0 )
1059 if( i_pos == -1 || i_pos > toread[i].i_posf )
1062 i_pos = toread[i].i_posf;
1069 for( i = 0; i < p_sys->i_track; i++ )
1071 if( toread[i].b_ok )
1074 msg_Warn( p_demux, "all tracks have failed, exiting..." );
1080 int i_loop_count = 0;
1082 /* no valid index, we will parse directly the stream
1083 * in case we fail we will disable all finished stream */
1084 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1086 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1087 if( AVI_PacketNext( p_demux ) )
1089 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1094 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1099 avi_packet_t avi_pk;
1101 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1104 "cannot get packet header, track disabled" );
1105 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1107 if( avi_pk.i_stream >= p_sys->i_track ||
1108 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1110 if( AVI_PacketNext( p_demux ) )
1113 "cannot skip packet, track disabled" );
1114 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1117 /* Prevents from eating all the CPU with broken files.
1118 * This value should be low enough so that it doesn't
1119 * affect the reading speed too much. */
1120 if( !(++i_loop_count % 1024) )
1122 if( !vlc_object_alive (p_demux) ) return -1;
1125 if( !(i_loop_count % (1024 * 10)) )
1127 "don't seem to find any data..." );
1133 i_track = avi_pk.i_stream;
1134 tk = p_sys->track[i_track];
1136 /* add this chunk to the index */
1138 index.i_id = avi_pk.i_fourcc;
1139 index.i_flags = AVI_GetKeyFlag(tk->i_codec, avi_pk.i_peek);
1140 index.i_pos = avi_pk.i_pos;
1141 index.i_length = avi_pk.i_size;
1142 index.i_lengthtotal = index.i_length;
1143 avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1145 /* do we will read this data ? */
1146 if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -25*1000 )
1152 if( AVI_PacketNext( p_demux ) )
1155 "cannot skip packet, track disabled" );
1156 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1165 stream_Seek( p_demux->s, i_pos );
1168 /* Set the track to use */
1169 tk = p_sys->track[i_track];
1171 /* read thoses data */
1172 if( tk->i_samplesize )
1174 unsigned int i_toread;
1176 if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1178 if( tk->i_samplesize > 1 )
1180 i_toread = tk->i_samplesize;
1184 i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1185 i_toread = __MAX( i_toread, 100 );
1188 i_size = __MIN( tk->idx.p_entry[tk->i_idxposc].i_length -
1194 i_size = tk->idx.p_entry[tk->i_idxposc].i_length;
1197 if( tk->i_idxposb == 0 )
1199 i_size += 8; /* need to read and skip header */
1202 if( ( p_frame = ReadFrame( p_demux, tk,
1203 ( tk->i_idxposb == 0 ) ? 8 : 0, i_size ) )==NULL )
1205 msg_Warn( p_demux, "failed reading data" );
1207 toread[i_track].b_ok = false;
1211 p_frame->i_pts = AVI_GetPTS( tk ) + 1;
1212 if( tk->idx.p_entry[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1214 p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1218 p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1222 if( tk->i_samplesize )
1224 if( tk->i_idxposb == 0 )
1228 toread[i_track].i_toread -= i_size;
1229 tk->i_idxposb += i_size;
1230 if( tk->i_idxposb >=
1231 tk->idx.p_entry[tk->i_idxposc].i_length )
1239 int i_length = tk->idx.p_entry[tk->i_idxposc].i_length;
1242 if( tk->i_cat == AUDIO_ES )
1244 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1246 toread[i_track].i_toread--;
1249 if( tk->i_idxposc < tk->idx.i_size)
1251 toread[i_track].i_posf =
1252 tk->idx.p_entry[tk->i_idxposc].i_pos;
1253 if( tk->i_idxposb > 0 )
1255 toread[i_track].i_posf += 8 + tk->i_idxposb;
1261 toread[i_track].i_posf = -1;
1264 if( tk->i_cat != VIDEO_ES )
1265 p_frame->i_dts = p_frame->i_pts;
1268 p_frame->i_dts = p_frame->i_pts;
1269 p_frame->i_pts = VLC_TS_INVALID;
1272 if( tk->i_dv_audio_rate )
1273 AVI_DvHandleAudio( p_demux, tk, p_frame );
1274 es_out_Send( p_demux->out, tk->p_es, p_frame );
1279 /*****************************************************************************
1280 * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1281 *****************************************************************************
1282 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1283 *****************************************************************************/
1284 static int Demux_UnSeekable( demux_t *p_demux )
1286 demux_sys_t *p_sys = p_demux->p_sys;
1287 avi_track_t *p_stream_master = NULL;
1288 unsigned int i_stream;
1289 unsigned int i_packet;
1291 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_time + 1 );
1293 /* *** find master stream for data packet skipping algo *** */
1294 /* *** -> first video, if any, or first audio ES *** */
1295 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1297 avi_track_t *tk = p_sys->track[i_stream];
1300 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1301 if( tk->p_es_dv_audio )
1304 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1308 if( b && tk->i_cat == VIDEO_ES )
1310 p_stream_master = tk;
1314 p_stream_master = tk;
1318 if( !p_stream_master )
1320 msg_Warn( p_demux, "no more stream selected" );
1324 p_sys->i_time = AVI_GetPTS( p_stream_master );
1326 for( i_packet = 0; i_packet < 10; i_packet++)
1328 #define p_stream p_sys->track[avi_pk.i_stream]
1330 avi_packet_t avi_pk;
1332 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1337 if( avi_pk.i_stream >= p_sys->i_track ||
1338 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1340 /* we haven't found an audio or video packet:
1341 * - we have seek, found first next packet
1342 * - others packets could be found, skip them
1344 switch( avi_pk.i_fourcc )
1346 case AVIFOURCC_JUNK:
1347 case AVIFOURCC_LIST:
1348 case AVIFOURCC_RIFF:
1349 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1350 case AVIFOURCC_idx1:
1353 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1355 return( 0 ); /* eof */
1358 "seems to have lost position, resync" );
1359 if( AVI_PacketSearch( p_demux ) )
1361 msg_Err( p_demux, "resync failed" );
1368 /* check for time */
1369 if( llabs( AVI_GetPTS( p_stream ) -
1370 AVI_GetPTS( p_stream_master ) )< 600*1000 )
1372 /* load it and send to decoder */
1373 block_t *p_frame = ReadFrame( p_demux, p_stream, 8, avi_pk.i_size + 8 ) ;
1374 if( p_frame == NULL )
1378 p_frame->i_pts = AVI_GetPTS( p_stream ) + 1;
1380 if( avi_pk.i_cat != VIDEO_ES )
1381 p_frame->i_dts = p_frame->i_pts;
1384 p_frame->i_dts = p_frame->i_pts;
1385 p_frame->i_pts = VLC_TS_INVALID;
1388 if( p_stream->i_dv_audio_rate )
1389 AVI_DvHandleAudio( p_demux, p_stream, p_frame );
1390 es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1394 if( AVI_PacketNext( p_demux ) )
1400 /* *** update stream time position *** */
1401 if( p_stream->i_samplesize )
1403 p_stream->i_idxposb += avi_pk.i_size;
1407 if( p_stream->i_cat == AUDIO_ES )
1409 p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1411 p_stream->i_idxposc++;
1421 /*****************************************************************************
1422 * Seek: goto to i_date or i_percent
1423 *****************************************************************************/
1424 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1426 demux_sys_t *p_sys = p_demux->p_sys;
1427 msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1428 i_date / CLOCK_FREQ, i_percent );
1430 if( p_sys->b_seekable )
1432 int64_t i_pos_backup = stream_Tell( p_demux->s );
1434 /* Check and lazy load indexes if it was not done (not fastseekable) */
1435 if ( !p_sys->b_indexloaded && ( p_sys->i_avih_flags & AVIF_HASINDEX ) )
1437 avi_chunk_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
1438 if (unlikely( !p_riff ))
1439 return VLC_EGENERIC;
1441 int i_ret = AVI_ChunkFetchIndexes( p_demux->s, p_riff );
1444 /* Go back to position before index failure */
1445 if ( stream_Tell( p_demux->s ) - i_pos_backup )
1446 stream_Seek( p_demux->s, i_pos_backup );
1448 if ( p_sys->i_avih_flags & AVIF_MUSTUSEINDEX )
1449 return VLC_EGENERIC;
1451 else AVI_IndexLoad( p_demux );
1453 p_sys->b_indexloaded = true; /* we don't want to try each time */
1456 if( !p_sys->i_length )
1458 avi_track_t *p_stream = NULL;
1459 unsigned i_stream = 0;
1462 if ( !p_sys->i_movi_lastchunk_pos && /* set when index is successfully loaded */
1463 ! ( p_sys->i_avih_flags & AVIF_ISINTERLEAVED ) )
1465 msg_Err( p_demux, "seeking without index at %d%%"
1466 " only works for interleaved files", i_percent );
1467 goto failandresetpos;
1469 /* use i_percent to create a true i_date */
1470 if( i_percent >= 100 )
1472 msg_Warn( p_demux, "cannot seek so far !" );
1473 goto failandresetpos;
1475 i_percent = __MAX( i_percent, 0 );
1477 /* try to find chunk that is at i_percent or the file */
1478 i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1479 p_sys->i_movi_begin );
1480 /* search first selected stream (and prefer non-EOF ones) */
1481 for( unsigned i = 0; i < p_sys->i_track; i++ )
1483 avi_track_t *p_track = p_sys->track[i];
1484 if( !p_track->b_activated )
1489 if( !p_track->b_eof )
1492 if( p_stream == NULL )
1494 msg_Warn( p_demux, "cannot find any selected stream" );
1495 goto failandresetpos;
1498 /* be sure that the index exist */
1499 if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1501 msg_Warn( p_demux, "cannot seek" );
1502 goto failandresetpos;
1505 while( i_pos >= p_stream->idx.p_entry[p_stream->i_idxposc].i_pos +
1506 p_stream->idx.p_entry[p_stream->i_idxposc].i_length + 8 )
1508 /* search after i_idxposc */
1509 if( AVI_StreamChunkSet( p_demux,
1510 i_stream, p_stream->i_idxposc + 1 ) )
1512 msg_Warn( p_demux, "cannot seek" );
1513 goto failandresetpos;
1517 i_date = AVI_GetPTS( p_stream );
1518 /* TODO better support for i_samplesize != 0 */
1519 msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1523 for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1525 avi_track_t *p_stream = p_sys->track[i_stream];
1527 if( !p_stream->b_activated )
1530 p_stream->b_eof = AVI_TrackSeek( p_demux, i_stream, i_date ) != 0;
1532 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1533 p_sys->i_time = i_date;
1534 msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /CLOCK_FREQ );
1538 /* Go back to position before index failure */
1539 if ( stream_Tell( p_demux->s ) - i_pos_backup )
1540 stream_Seek( p_demux->s, i_pos_backup );
1542 return VLC_EGENERIC;
1546 msg_Err( p_demux, "shouldn't yet be executed" );
1547 return VLC_EGENERIC;
1551 /*****************************************************************************
1553 *****************************************************************************/
1554 static double ControlGetPosition( demux_t *p_demux )
1556 demux_sys_t *p_sys = p_demux->p_sys;
1558 if( p_sys->i_length > 0 )
1560 return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)CLOCK_FREQ );
1562 else if( stream_Size( p_demux->s ) > 0 )
1564 double i64 = (uint64_t)stream_Tell( p_demux->s );
1565 return i64 / stream_Size( p_demux->s );
1570 static int Control( demux_t *p_demux, int i_query, va_list args )
1572 demux_sys_t *p_sys = p_demux->p_sys;
1580 case DEMUX_GET_POSITION:
1581 pf = (double*)va_arg( args, double * );
1582 *pf = ControlGetPosition( p_demux );
1584 case DEMUX_SET_POSITION:
1585 f = (double)va_arg( args, double );
1586 if( p_sys->b_seekable )
1588 i64 = (mtime_t)(f * CLOCK_FREQ * p_sys->i_length);
1589 return Seek( p_demux, i64, (int)(f * 100) );
1593 int64_t i_pos = stream_Size( p_demux->s ) * f;
1594 return stream_Seek( p_demux->s, i_pos );
1597 case DEMUX_GET_TIME:
1598 pi64 = (int64_t*)va_arg( args, int64_t * );
1599 *pi64 = p_sys->i_time;
1602 case DEMUX_SET_TIME:
1606 i64 = (int64_t)va_arg( args, int64_t );
1607 if( !p_sys->b_seekable )
1609 return VLC_EGENERIC;
1611 else if( p_sys->i_length > 0 )
1613 i_percent = 100 * i64 / (p_sys->i_length*CLOCK_FREQ);
1615 else if( p_sys->i_time > 0 )
1617 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1618 (double)i64 / (double)p_sys->i_time );
1620 return Seek( p_demux, i64, i_percent );
1622 case DEMUX_GET_LENGTH:
1623 pi64 = (int64_t*)va_arg( args, int64_t * );
1624 *pi64 = p_sys->i_length * (mtime_t)CLOCK_FREQ;
1628 pf = (double*)va_arg( args, double * );
1630 for( i = 0; i < (int)p_sys->i_track; i++ )
1632 avi_track_t *tk = p_sys->track[i];
1633 if( tk->i_cat == VIDEO_ES && tk->i_scale > 0)
1635 *pf = (float)tk->i_rate / (float)tk->i_scale;
1641 case DEMUX_GET_META:
1642 p_meta = (vlc_meta_t*)va_arg( args, vlc_meta_t* );
1643 vlc_meta_Merge( p_meta, p_sys->meta );
1646 case DEMUX_GET_ATTACHMENTS:
1648 if( p_sys->i_attachment <= 0 )
1649 return VLC_EGENERIC;
1651 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1652 int *pi_int = va_arg( args, int * );
1654 *pi_int = p_sys->i_attachment;
1655 *ppp_attach = calloc( p_sys->i_attachment, sizeof(**ppp_attach));
1656 for( unsigned i = 0; i < p_sys->i_attachment && *ppp_attach; i++ )
1657 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachment[i] );
1662 return VLC_EGENERIC;
1666 /*****************************************************************************
1667 * Function to convert pts to chunk or byte
1668 *****************************************************************************/
1670 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1675 return (mtime_t)((int64_t)i_pts *
1676 (int64_t)tk->i_rate /
1677 (int64_t)tk->i_scale /
1678 (int64_t)CLOCK_FREQ );
1680 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1682 if( !tk->i_scale || !tk->i_samplesize )
1685 return (mtime_t)((int64_t)i_pts *
1686 (int64_t)tk->i_rate /
1687 (int64_t)tk->i_scale /
1689 (int64_t)tk->i_samplesize );
1692 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1699 i_dpts = (mtime_t)( (int64_t)1000000 *
1701 (int64_t)tk->i_scale /
1702 (int64_t)tk->i_rate );
1704 if( tk->i_samplesize )
1706 return i_dpts / tk->i_samplesize;
1711 static mtime_t AVI_GetPTS( avi_track_t *tk )
1713 if( tk->i_samplesize )
1715 int64_t i_count = 0;
1717 /* we need a valid entry we will emulate one */
1718 if( tk->i_idxposc == tk->idx.i_size )
1722 /* use the last entry */
1723 i_count = tk->idx.p_entry[tk->idx.i_size - 1].i_lengthtotal
1724 + tk->idx.p_entry[tk->idx.i_size - 1].i_length;
1729 i_count = tk->idx.p_entry[tk->i_idxposc].i_lengthtotal;
1731 return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1735 if( tk->i_cat == AUDIO_ES )
1737 return AVI_GetDPTS( tk, tk->i_blockno );
1741 return AVI_GetDPTS( tk, tk->i_idxposc );
1746 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1748 demux_sys_t *p_sys = p_demux->p_sys;
1749 avi_packet_t avi_pk;
1750 int i_loop_count = 0;
1752 /* find first chunk of i_stream that isn't in index */
1754 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1756 stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1757 if( AVI_PacketNext( p_demux ) )
1759 return VLC_EGENERIC;
1764 stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1769 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
1771 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1773 msg_Warn( p_demux, "cannot get packet header" );
1774 return VLC_EGENERIC;
1776 if( avi_pk.i_stream >= p_sys->i_track ||
1777 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1779 if( AVI_PacketNext( p_demux ) )
1781 return VLC_EGENERIC;
1784 /* Prevents from eating all the CPU with broken files.
1785 * This value should be low enough so that it doesn't
1786 * affect the reading speed too much. */
1787 if( !(++i_loop_count % 1024) )
1789 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
1792 if( !(i_loop_count % (1024 * 10)) )
1793 msg_Warn( p_demux, "don't seem to find any data..." );
1798 avi_track_t *tk_pk = p_sys->track[avi_pk.i_stream];
1800 /* add this chunk to the index */
1802 index.i_id = avi_pk.i_fourcc;
1803 index.i_flags = AVI_GetKeyFlag(tk_pk->i_codec, avi_pk.i_peek);
1804 index.i_pos = avi_pk.i_pos;
1805 index.i_length = avi_pk.i_size;
1806 index.i_lengthtotal = index.i_length;
1807 avi_index_Append( &tk_pk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1809 if( avi_pk.i_stream == i_stream )
1814 if( AVI_PacketNext( p_demux ) )
1816 return VLC_EGENERIC;
1822 /* be sure that i_ck will be a valid index entry */
1823 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1826 demux_sys_t *p_sys = p_demux->p_sys;
1827 avi_track_t *p_stream = p_sys->track[i_stream];
1829 p_stream->i_idxposc = i_ck;
1830 p_stream->i_idxposb = 0;
1832 if( i_ck >= p_stream->idx.i_size )
1834 p_stream->i_idxposc = p_stream->idx.i_size - 1;
1837 p_stream->i_idxposc++;
1838 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1840 return VLC_EGENERIC;
1843 } while( p_stream->i_idxposc < i_ck );
1849 /* XXX FIXME up to now, we assume that all chunk are one after one */
1850 static int AVI_StreamBytesSet( demux_t *p_demux,
1851 unsigned int i_stream,
1854 demux_sys_t *p_sys = p_demux->p_sys;
1855 avi_track_t *p_stream = p_sys->track[i_stream];
1857 if( ( p_stream->idx.i_size > 0 )
1858 &&( i_byte < p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_lengthtotal +
1859 p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_length ) )
1861 /* index is valid to find the ck */
1862 /* uses dichototmie to be fast enougth */
1863 int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->idx.i_size - 1 );
1864 int i_idxmax = p_stream->idx.i_size;
1868 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal > i_byte )
1870 i_idxmax = i_idxposc ;
1871 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1875 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal +
1876 p_stream->idx.p_entry[i_idxposc].i_length <= i_byte)
1878 i_idxmin = i_idxposc ;
1879 i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1883 p_stream->i_idxposc = i_idxposc;
1884 p_stream->i_idxposb = i_byte -
1885 p_stream->idx.p_entry[i_idxposc].i_lengthtotal;
1894 p_stream->i_idxposc = p_stream->idx.i_size - 1;
1895 p_stream->i_idxposb = 0;
1898 p_stream->i_idxposc++;
1899 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1901 return VLC_EGENERIC;
1904 } while( p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal +
1905 p_stream->idx.p_entry[p_stream->i_idxposc].i_length <= i_byte );
1907 p_stream->i_idxposb = i_byte -
1908 p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal;
1913 static int AVI_TrackSeek( demux_t *p_demux,
1917 demux_sys_t *p_sys = p_demux->p_sys;
1918 avi_track_t *tk = p_sys->track[i_stream];
1920 #define p_stream p_sys->track[i_stream]
1923 i_oldpts = AVI_GetPTS( p_stream );
1925 if( !p_stream->i_samplesize )
1927 if( AVI_StreamChunkSet( p_demux,
1929 AVI_PTSToChunk( p_stream, i_date ) ) )
1931 return VLC_EGENERIC;
1934 if( p_stream->i_cat == AUDIO_ES )
1938 for( i = 0; i < tk->i_idxposc; i++ )
1940 if( tk->i_blocksize > 0 )
1942 tk->i_blockno += ( tk->idx.p_entry[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
1952 "old:%"PRId64" %s new %"PRId64,
1954 i_oldpts > i_date ? ">" : "<",
1957 if( p_stream->i_cat == VIDEO_ES )
1959 /* search key frame */
1960 //if( i_date < i_oldpts || 1 )
1962 while( p_stream->i_idxposc > 0 &&
1963 !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
1966 if( AVI_StreamChunkSet( p_demux,
1968 p_stream->i_idxposc - 1 ) )
1970 return VLC_EGENERIC;
1977 while( p_stream->i_idxposc < p_stream->idx.i_size &&
1978 !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
1981 if( AVI_StreamChunkSet( p_demux,
1983 p_stream->i_idxposc + 1 ) )
1985 return VLC_EGENERIC;
1994 if( AVI_StreamBytesSet( p_demux,
1996 AVI_PTSToByte( p_stream, i_date ) ) )
1998 return VLC_EGENERIC;
2005 /****************************************************************************
2006 * Return true if it's a key frame
2007 ****************************************************************************/
2008 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
2012 case VLC_CODEC_DIV1:
2014 * startcode: 0x00000100 32bits
2015 * framenumber ? 5bits
2016 * piture type 0(I),1(P) 2bits
2018 if( GetDWBE( p_byte ) != 0x00000100 )
2020 /* it's not an msmpegv1 stream, strange...*/
2021 return AVIIF_KEYFRAME;
2023 return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
2025 case VLC_CODEC_DIV2:
2026 case VLC_CODEC_DIV3:
2027 case VLC_CODEC_WMV1:
2029 * picture type 0(I),1(P) 2bits
2031 return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2032 case VLC_CODEC_MP4V:
2033 /* we should find first occurrence of 0x000001b6 (32bits)
2034 * startcode: 0x000001b6 32bits
2035 * piture type 0(I),1(P) 2bits
2037 if( GetDWBE( p_byte ) != 0x000001b6 )
2039 /* not true , need to find the first VOP header */
2040 return AVIIF_KEYFRAME;
2042 return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2045 /* I can't do it, so say yes */
2046 return AVIIF_KEYFRAME;
2050 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
2055 wf_tag_to_fourcc( i_codec, &i_codec, NULL );
2058 return vlc_fourcc_GetCodec( i_cat, i_codec );
2060 return VLC_FOURCC( 'u', 'n', 'd', 'f' );
2064 /****************************************************************************
2066 ****************************************************************************/
2067 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
2068 unsigned int *pi_number, unsigned int *pi_type )
2070 #define SET_PTR( p, v ) if( p ) *(p) = (v);
2073 c1 = ((uint8_t *)&i_id)[0];
2074 c2 = ((uint8_t *)&i_id)[1];
2076 if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
2078 SET_PTR( pi_number, 100 ); /* > max stream number */
2079 SET_PTR( pi_type, UNKNOWN_ES );
2083 SET_PTR( pi_number, (c1 - '0') * 10 + (c2 - '0' ) );
2084 switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
2087 SET_PTR( pi_type, AUDIO_ES );
2092 SET_PTR( pi_type, VIDEO_ES );
2096 SET_PTR( pi_type, SPU_ES );
2099 SET_PTR( pi_type, IGNORE_ES );
2102 SET_PTR( pi_type, UNKNOWN_ES );
2109 /****************************************************************************
2111 ****************************************************************************/
2112 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
2114 const uint8_t *p_peek;
2116 if( stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
2118 return VLC_EGENERIC;
2120 p_pk->i_fourcc = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
2121 p_pk->i_size = GetDWLE( p_peek + 4 );
2122 p_pk->i_pos = stream_Tell( p_demux->s );
2123 if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
2125 p_pk->i_type = VLC_FOURCC( p_peek[8], p_peek[9],
2126 p_peek[10], p_peek[11] );
2133 memcpy( p_pk->i_peek, p_peek + 8, 8 );
2135 AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
2139 static int AVI_PacketNext( demux_t *p_demux )
2141 avi_packet_t avi_ck;
2144 if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2146 return VLC_EGENERIC;
2149 if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2150 ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2154 else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2155 avi_ck.i_type == AVIFOURCC_AVIX )
2161 i_skip = __EVEN( avi_ck.i_size ) + 8;
2164 if( stream_Read( p_demux->s, NULL, i_skip ) != i_skip )
2166 return VLC_EGENERIC;
2171 static int AVI_PacketRead( demux_t *p_demux,
2173 block_t **pp_frame )
2177 i_size = __EVEN( p_pk->i_size + 8 );
2179 if( ( *pp_frame = stream_Block( p_demux->s, i_size ) ) == NULL )
2181 return VLC_EGENERIC;
2183 (*pp_frame)->p_buffer += 8;
2184 (*pp_frame)->i_buffer -= 8;
2186 if( i_size != p_pk->i_size + 8 )
2188 (*pp_frame)->i_buffer--;
2194 static int AVI_PacketSearch( demux_t *p_demux )
2196 demux_sys_t *p_sys = p_demux->p_sys;
2197 avi_packet_t avi_pk;
2202 if( stream_Read( p_demux->s, NULL, 1 ) != 1 )
2204 return VLC_EGENERIC;
2206 AVI_PacketGetHeader( p_demux, &avi_pk );
2207 if( avi_pk.i_stream < p_sys->i_track &&
2208 ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2212 switch( avi_pk.i_fourcc )
2214 case AVIFOURCC_JUNK:
2215 case AVIFOURCC_LIST:
2216 case AVIFOURCC_RIFF:
2217 case AVIFOURCC_idx1:
2221 /* Prevents from eating all the CPU with broken files.
2222 * This value should be low enough so that it doesn't affect the
2223 * reading speed too much (not that we care much anyway because
2224 * this code is called only on broken files). */
2225 if( !(++i_count % 1024) )
2227 if( !vlc_object_alive (p_demux) ) return VLC_EGENERIC;
2230 if( !(i_count % (1024 * 10)) )
2231 msg_Warn( p_demux, "trying to resync..." );
2236 /****************************************************************************
2238 ****************************************************************************/
2239 static void avi_index_Init( avi_index_t *p_index )
2241 p_index->i_size = 0;
2243 p_index->p_entry = NULL;
2245 static void avi_index_Clean( avi_index_t *p_index )
2247 free( p_index->p_entry );
2249 static void avi_index_Append( avi_index_t *p_index, off_t *pi_last_pos,
2250 avi_entry_t *p_entry )
2252 /* Update last chunk position */
2253 if( *pi_last_pos < p_entry->i_pos )
2254 *pi_last_pos = p_entry->i_pos;
2257 if( p_index->i_size >= p_index->i_max )
2259 p_index->i_max += 16384;
2260 p_index->p_entry = realloc_or_free( p_index->p_entry,
2261 p_index->i_max * sizeof( *p_index->p_entry ) );
2262 if( !p_index->p_entry )
2265 /* calculate cumulate length */
2266 if( p_index->i_size > 0 )
2268 p_entry->i_lengthtotal =
2269 p_index->p_entry[p_index->i_size - 1].i_length +
2270 p_index->p_entry[p_index->i_size - 1].i_lengthtotal;
2274 p_entry->i_lengthtotal = 0;
2277 p_index->p_entry[p_index->i_size++] = *p_entry;
2280 static int AVI_IndexFind_idx1( demux_t *p_demux,
2281 avi_chunk_idx1_t **pp_idx1,
2282 uint64_t *pi_offset )
2284 demux_sys_t *p_sys = p_demux->p_sys;
2286 avi_chunk_list_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2287 avi_chunk_idx1_t *p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2291 msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2292 return VLC_EGENERIC;
2296 /* The offset in the index should be from the start of the movi content,
2297 * but some broken files use offset from the start of the file. Just
2298 * checking the offset of the first packet is not enough as some files
2299 * has unused chunk at the beginning of the movi content.
2301 avi_chunk_list_t *p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2302 uint64_t i_first_pos = UINT64_MAX;
2303 for( unsigned i = 0; i < __MIN( p_idx1->i_entry_count, 100 ); i++ )
2305 if ( p_idx1->entry[i].i_length > 0 )
2306 i_first_pos = __MIN( i_first_pos, p_idx1->entry[i].i_pos );
2309 const uint64_t i_movi_content = p_movi->i_chunk_pos + 8;
2310 if( i_first_pos < i_movi_content )
2312 *pi_offset = i_movi_content;
2314 else if( p_sys->b_seekable && i_first_pos < UINT64_MAX )
2316 const uint8_t *p_peek;
2317 if( !stream_Seek( p_demux->s, i_movi_content + i_first_pos ) &&
2318 stream_Peek( p_demux->s, &p_peek, 4 ) >= 4 &&
2319 ( !isdigit( p_peek[0] ) || !isdigit( p_peek[1] ) ||
2320 !isalpha( p_peek[2] ) || !isalpha( p_peek[3] ) ) )
2323 *pi_offset = i_movi_content;
2332 static int AVI_IndexLoad_idx1( demux_t *p_demux,
2333 avi_index_t p_index[], off_t *pi_last_offset )
2335 demux_sys_t *p_sys = p_demux->p_sys;
2337 avi_chunk_idx1_t *p_idx1;
2339 if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2340 return VLC_EGENERIC;
2342 p_sys->b_indexloaded = true;
2344 for( unsigned i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2349 AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2352 if( i_stream < p_sys->i_track &&
2353 (i_cat == p_sys->track[i_stream]->i_cat || i_cat == UNKNOWN_ES ) )
2356 index.i_id = p_idx1->entry[i_index].i_fourcc;
2357 index.i_flags = p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2358 index.i_pos = p_idx1->entry[i_index].i_pos + i_offset;
2359 index.i_length = p_idx1->entry[i_index].i_length;
2360 index.i_lengthtotal = index.i_length;
2362 avi_index_Append( &p_index[i_stream], pi_last_offset, &index );
2368 static void __Parse_indx( demux_t *p_demux, avi_index_t *p_index, off_t *pi_max_offset,
2369 avi_chunk_indx_t *p_indx )
2373 p_demux->p_sys->b_indexloaded = true;
2375 msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2376 if( p_indx->i_indexsubtype == 0 )
2378 for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2380 index.i_id = p_indx->i_id;
2381 index.i_flags = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2382 index.i_pos = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2383 index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2384 index.i_lengthtotal = index.i_length;
2386 avi_index_Append( p_index, pi_max_offset, &index );
2389 else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2391 for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2393 index.i_id = p_indx->i_id;
2394 index.i_flags = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2395 index.i_pos = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2396 index.i_length = p_indx->idx.field[i].i_size;
2397 index.i_lengthtotal = index.i_length;
2399 avi_index_Append( p_index, pi_max_offset, &index );
2404 msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2408 static void AVI_IndexLoad_indx( demux_t *p_demux,
2409 avi_index_t p_index[], off_t *pi_last_offset )
2411 demux_sys_t *p_sys = p_demux->p_sys;
2413 avi_chunk_list_t *p_riff;
2414 avi_chunk_list_t *p_hdrl;
2416 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2417 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2419 for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2421 avi_chunk_list_t *p_strl;
2422 avi_chunk_indx_t *p_indx;
2424 #define p_stream p_sys->track[i_stream]
2425 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2426 p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2431 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2436 if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2438 __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, p_indx );
2440 else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2442 if ( !p_sys->b_seekable )
2445 for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2447 if( stream_Seek( p_demux->s, p_indx->idx.super[i].i_offset )||
2448 AVI_ChunkRead( p_demux->s, &ck_sub, NULL ) )
2452 if( ck_sub.indx.i_indextype == AVI_INDEX_OF_CHUNKS )
2453 __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, &ck_sub.indx );
2454 AVI_ChunkFree( p_demux->s, &ck_sub );
2459 msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2465 static void AVI_IndexLoad( demux_t *p_demux )
2467 demux_sys_t *p_sys = p_demux->p_sys;
2470 assert( p_sys->i_track <= 100 );
2471 avi_index_t p_idx_indx[p_sys->i_track];
2472 avi_index_t p_idx_idx1[p_sys->i_track];
2473 for( unsigned i = 0; i < p_sys->i_track; i++ )
2475 avi_index_Init( &p_idx_indx[i] );
2476 avi_index_Init( &p_idx_idx1[i] );
2478 off_t i_indx_last_pos = p_sys->i_movi_lastchunk_pos;
2479 off_t i_idx1_last_pos = p_sys->i_movi_lastchunk_pos;
2481 AVI_IndexLoad_indx( p_demux, p_idx_indx, &i_indx_last_pos );
2482 if( !p_sys->b_odml )
2483 AVI_IndexLoad_idx1( p_demux, p_idx_idx1, &i_idx1_last_pos );
2485 /* Select the longest index */
2486 for( unsigned i = 0; i < p_sys->i_track; i++ )
2488 if( p_idx_indx[i].i_size > p_idx_idx1[i].i_size )
2490 msg_Dbg( p_demux, "selected ODML index for stream[%u]", i );
2491 p_sys->track[i]->idx = p_idx_indx[i];
2492 avi_index_Clean( &p_idx_idx1[i] );
2496 msg_Dbg( p_demux, "selected standard index for stream[%u]", i );
2497 p_sys->track[i]->idx = p_idx_idx1[i];
2498 avi_index_Clean( &p_idx_indx[i] );
2501 p_sys->i_movi_lastchunk_pos = __MAX( i_indx_last_pos, i_idx1_last_pos );
2503 for( unsigned i = 0; i < p_sys->i_track; i++ )
2505 avi_index_t *p_index = &p_sys->track[i]->idx;
2509 for( unsigned j = 0; !b_key && j < p_index->i_size; j++ )
2510 b_key = p_index->p_entry[j].i_flags & AVIIF_KEYFRAME;
2513 msg_Err( p_demux, "no key frame set for track %u", i );
2514 for( unsigned j = 0; j < p_index->i_size; j++ )
2515 p_index->p_entry[j].i_flags |= AVIIF_KEYFRAME;
2519 msg_Dbg( p_demux, "stream[%d] created %d index entries",
2520 i, p_index->i_size );
2524 static void AVI_IndexCreate( demux_t *p_demux )
2526 demux_sys_t *p_sys = p_demux->p_sys;
2528 avi_chunk_list_t *p_riff;
2529 avi_chunk_list_t *p_movi;
2531 unsigned int i_stream;
2534 mtime_t i_dialog_update;
2535 dialog_progress_bar_t *p_dialog = NULL;
2537 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2538 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2542 msg_Err( p_demux, "cannot find p_movi" );
2546 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2547 avi_index_Init( &p_sys->track[i_stream]->idx );
2549 i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2550 stream_Size( p_demux->s ) );
2552 stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2553 msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2556 /* Only show dialog if AVI is > 10MB */
2557 i_dialog_update = mdate();
2558 if( stream_Size( p_demux->s ) > 10000000 )
2559 p_dialog = dialog_ProgressCreate( p_demux, _("Fixing AVI Index..."),
2560 NULL, _("Cancel") );
2566 if( !vlc_object_alive (p_demux) )
2569 /* Don't update/check dialog too often */
2570 if( p_dialog && mdate() - i_dialog_update > 100000 )
2572 if( dialog_ProgressCancelled( p_dialog ) )
2575 double f_current = stream_Tell( p_demux->s );
2576 double f_size = stream_Size( p_demux->s );
2577 double f_pos = f_current / f_size;
2578 dialog_ProgressSet( p_dialog, NULL, f_pos );
2580 i_dialog_update = mdate();
2583 if( AVI_PacketGetHeader( p_demux, &pk ) )
2586 if( pk.i_stream < p_sys->i_track &&
2587 pk.i_cat == p_sys->track[pk.i_stream]->i_cat )
2589 avi_track_t *tk = p_sys->track[pk.i_stream];
2592 index.i_id = pk.i_fourcc;
2593 index.i_flags = AVI_GetKeyFlag(tk->i_codec, pk.i_peek);
2594 index.i_pos = pk.i_pos;
2595 index.i_length = pk.i_size;
2596 index.i_lengthtotal = pk.i_size;
2597 avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
2601 switch( pk.i_fourcc )
2603 case AVIFOURCC_idx1:
2606 avi_chunk_list_t *p_sysx;
2607 p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2608 AVIFOURCC_RIFF, 1 );
2610 msg_Dbg( p_demux, "looking for new RIFF chunk" );
2611 if( stream_Seek( p_demux->s, p_sysx->i_chunk_pos + 24 ) )
2617 case AVIFOURCC_RIFF:
2618 msg_Dbg( p_demux, "new RIFF chunk found" );
2622 case AVIFOURCC_JUNK:
2626 msg_Warn( p_demux, "need resync, probably broken avi" );
2627 if( AVI_PacketSearch( p_demux ) )
2629 msg_Warn( p_demux, "lost sync, abord index creation" );
2635 if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2636 AVI_PacketNext( p_demux ) )
2643 if( p_dialog != NULL )
2644 dialog_ProgressDestroy( p_dialog );
2646 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2648 msg_Dbg( p_demux, "stream[%d] creating %d index entries",
2649 i_stream, p_sys->track[i_stream]->idx.i_size );
2654 static void AVI_MetaLoad( demux_t *p_demux,
2655 avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih )
2657 demux_sys_t *p_sys = p_demux->p_sys;
2659 vlc_meta_t *p_meta = p_sys->meta = vlc_meta_New();
2664 snprintf( buffer, sizeof(buffer), "%s%s%s%s",
2665 p_avih->i_flags&AVIF_HASINDEX ? " HAS_INDEX" : "",
2666 p_avih->i_flags&AVIF_MUSTUSEINDEX ? " MUST_USE_INDEX" : "",
2667 p_avih->i_flags&AVIF_ISINTERLEAVED ? " IS_INTERLEAVED" : "",
2668 p_avih->i_flags&AVIF_TRUSTCKTYPE ? " TRUST_CKTYPE" : "" );
2669 vlc_meta_SetSetting( p_meta, buffer );
2671 avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
2675 static const struct {
2679 { AVIFOURCC_IART, vlc_meta_Artist },
2680 { AVIFOURCC_ICMT, vlc_meta_Description },
2681 { AVIFOURCC_ICOP, vlc_meta_Copyright },
2682 { AVIFOURCC_IGNR, vlc_meta_Genre },
2683 { AVIFOURCC_INAM, vlc_meta_Title },
2684 { AVIFOURCC_ICRD, vlc_meta_Date },
2685 { AVIFOURCC_ILNG, vlc_meta_Language },
2686 { AVIFOURCC_IRTD, vlc_meta_Rating },
2687 { AVIFOURCC_IWEB, vlc_meta_URL },
2688 { AVIFOURCC_IPRT, vlc_meta_TrackNumber },
2689 { AVIFOURCC_IFRM, vlc_meta_TrackTotal },
2692 for( int i = 0; p_dsc[i].i_id != 0; i++ )
2694 avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_dsc[i].i_id, 0 );
2697 char *psz_value = FromACP( p_strz->p_str );
2702 vlc_meta_Set( p_meta, p_dsc[i].i_type, psz_value );
2706 static const vlc_fourcc_t p_extra[] = {
2707 AVIFOURCC_IARL, AVIFOURCC_ICMS, AVIFOURCC_ICRP, AVIFOURCC_IDIM, AVIFOURCC_IDPI,
2708 AVIFOURCC_IENG, AVIFOURCC_IKEY, AVIFOURCC_ILGT, AVIFOURCC_IMED, AVIFOURCC_IPLT,
2709 AVIFOURCC_IPRD, AVIFOURCC_ISBJ, AVIFOURCC_ISFT, AVIFOURCC_ISHP, AVIFOURCC_ISRC,
2710 AVIFOURCC_ISRF, AVIFOURCC_ITCH, AVIFOURCC_ISMP, AVIFOURCC_IDIT, AVIFOURCC_ISGN,
2711 AVIFOURCC_IWRI, AVIFOURCC_IPRO, AVIFOURCC_ICNM, AVIFOURCC_IPDS, AVIFOURCC_IEDT,
2712 AVIFOURCC_ICDS, AVIFOURCC_IMUS, AVIFOURCC_ISTD, AVIFOURCC_IDST, AVIFOURCC_ICNT,
2716 for( int i = 0; p_extra[i] != 0; i++ )
2718 avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_extra[i], 0 );
2721 char *psz_value = FromACP( p_strz->p_str );
2726 vlc_meta_AddExtra( p_meta, p_strz->p_type, psz_value );
2731 static void AVI_DvHandleAudio( demux_t *p_demux, avi_track_t *tk, block_t *p_frame )
2733 size_t i_offset = 80 * 6 + 80 * 16 * 3 + 3;
2734 if( p_frame->i_buffer < i_offset + 5 )
2737 if( p_frame->p_buffer[i_offset] != 0x50 )
2741 dv_get_audio_format( &fmt, &p_frame->p_buffer[i_offset + 1] );
2743 if( tk->p_es_dv_audio && tk->i_dv_audio_rate != (int)fmt.audio.i_rate )
2745 es_out_Del( p_demux->out, tk->p_es_dv_audio );
2746 tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2748 else if( !tk->p_es_dv_audio )
2750 tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2752 tk->i_dv_audio_rate = fmt.audio.i_rate;
2754 block_t *p_frame_audio = dv_extract_audio( p_frame );
2756 es_out_Send( p_demux->out, tk->p_es_dv_audio, p_frame_audio );
2759 /*****************************************************************************
2761 *****************************************************************************/
2762 static void AVI_ExtractSubtitle( demux_t *p_demux,
2763 unsigned int i_stream,
2764 avi_chunk_list_t *p_strl,
2765 avi_chunk_STRING_t *p_strn )
2767 demux_sys_t *p_sys = p_demux->p_sys;
2768 block_t *p_block = NULL;
2769 input_attachment_t *p_attachment = NULL;
2770 char *psz_description = NULL;
2771 avi_chunk_indx_t *p_indx = NULL;
2773 if( !p_sys->b_seekable )
2776 p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2782 if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES &&
2783 p_indx->i_entriesinuse > 0 )
2785 if( stream_Seek( p_demux->s, p_indx->idx.super[0].i_offset )||
2786 AVI_ChunkRead( p_demux->s, &ck, NULL ) )
2791 if( p_indx->i_indextype != AVI_INDEX_OF_CHUNKS ||
2792 p_indx->i_entriesinuse != 1 ||
2793 p_indx->i_indexsubtype != 0 )
2796 i_position = p_indx->i_baseoffset +
2797 p_indx->idx.std[0].i_offset - 8;
2798 i_size = (p_indx->idx.std[0].i_size & 0x7fffffff) + 8;
2802 avi_chunk_idx1_t *p_idx1;
2805 if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2809 for( unsigned i = 0; i < p_idx1->i_entry_count; i++ )
2811 const idx1_entry_t *e = &p_idx1->entry[i];
2813 unsigned i_stream_idx;
2815 AVI_ParseStreamHeader( e->i_fourcc, &i_stream_idx, &i_cat );
2816 if( i_cat == SPU_ES && i_stream_idx == i_stream )
2818 i_position = e->i_pos + i_offset;
2819 i_size = e->i_length + 8;
2828 if( i_size > 10000000 )
2830 msg_Dbg( p_demux, "Attached subtitle too big: %u", i_size );
2834 if( stream_Seek( p_demux->s, i_position ) )
2836 p_block = stream_Block( p_demux->s, i_size );
2840 /* Parse packet header */
2841 const uint8_t *p = p_block->p_buffer;
2842 if( i_size < 8 || p[2] != 't' || p[3] != 'x' )
2847 /* Parse subtitle chunk header */
2848 if( i_size < 11 || memcmp( p, "GAB2", 4 ) ||
2849 p[4] != 0x00 || GetWLE( &p[5] ) != 0x2 )
2851 const unsigned i_name = GetDWLE( &p[7] );
2852 if( 11 + i_size <= i_name )
2855 psz_description = FromCharset( "UTF-16LE", &p[11], i_name );
2857 i_size -= 11 + i_name;
2858 if( i_size < 6 || GetWLE( &p[0] ) != 0x04 )
2860 const unsigned i_payload = GetDWLE( &p[2] );
2861 if( i_size < 6 + i_payload || i_payload <= 0 )
2866 if( !psz_description )
2867 psz_description = p_strn ? FromACP( p_strn->p_str ) : NULL;
2869 if( asprintf( &psz_name, "subtitle%d.srt", p_sys->i_attachment ) <= 0 )
2871 p_attachment = vlc_input_attachment_New( psz_name,
2872 "application/x-srt",
2876 TAB_APPEND( p_sys->i_attachment, p_sys->attachment, p_attachment );
2880 free( psz_description );
2883 block_Release( p_block );
2886 msg_Dbg( p_demux, "Loaded an embedded subtitle" );
2888 msg_Warn( p_demux, "Failed to load an embedded subtitle" );
2890 if( p_indx == &ck.indx )
2891 AVI_ChunkFree( p_demux->s, &ck );
2893 /*****************************************************************************
2895 *****************************************************************************/
2896 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
2898 demux_sys_t *p_sys = p_demux->p_sys;
2902 for( i = 0; i < p_sys->i_track; i++ )
2904 avi_track_t *tk = p_sys->track[i];
2905 if( tk->i_idxposc >= tk->idx.i_size )
2917 /****************************************************************************
2918 * AVI_MovieGetLength give max streams length in second
2919 ****************************************************************************/
2920 static mtime_t AVI_MovieGetLength( demux_t *p_demux )
2922 demux_sys_t *p_sys = p_demux->p_sys;
2923 mtime_t i_maxlength = 0;
2926 for( i = 0; i < p_sys->i_track; i++ )
2928 avi_track_t *tk = p_sys->track[i];
2931 /* fix length for each stream */
2932 if( tk->idx.i_size < 1 || !tk->idx.p_entry )
2937 if( tk->i_samplesize )
2939 i_length = AVI_GetDPTS( tk,
2940 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal +
2941 tk->idx.p_entry[tk->idx.i_size-1].i_length );
2945 i_length = AVI_GetDPTS( tk, tk->idx.i_size );
2947 i_length /= (mtime_t)1000000; /* in seconds */
2950 "stream[%d] length:%"PRId64" (based on index)",
2953 i_maxlength = __MAX( i_maxlength, i_length );