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 *****************************************************************************/
35 #include <vlc_common.h>
36 #include <vlc_plugin.h>
37 #include <vlc_demux.h>
38 #include <vlc_input.h>
40 #include <vlc_dialog.h>
43 #include <vlc_codecs.h>
44 #include <vlc_charset.h>
45 #include <vlc_memory.h>
50 /*****************************************************************************
52 *****************************************************************************/
54 #define INTERLEAVE_TEXT N_("Force interleaved method" )
56 #define INDEX_TEXT N_("Force index creation")
57 #define INDEX_LONGTEXT N_( \
58 "Recreate a index for the AVI file. Use this if your AVI file is damaged "\
59 "or incomplete (not seekable)." )
61 #define BI_RAWRGB 0x00
62 #define BI_RGBBITFIELDS 0x03
64 static int Open ( vlc_object_t * );
65 static void Close( vlc_object_t * );
67 static const int pi_index[] = {0,1,2,3};
69 static const char *const ppsz_indexes[] = { N_("Ask for action"),
72 N_("Fix when necessary")};
75 set_shortname( "AVI" )
76 set_description( N_("AVI demuxer") )
77 set_capability( "demux", 212 )
78 set_category( CAT_INPUT )
79 set_subcategory( SUBCAT_INPUT_DEMUX )
81 add_bool( "avi-interleaved", false,
82 INTERLEAVE_TEXT, INTERLEAVE_TEXT, true )
83 add_integer( "avi-index", 0,
84 INDEX_TEXT, INDEX_LONGTEXT, false )
85 change_integer_list( pi_index, ppsz_indexes )
87 set_callbacks( Open, Close )
90 /*****************************************************************************
92 *****************************************************************************/
93 static int Control ( demux_t *, int, va_list );
94 static int Seek ( demux_t *, mtime_t, int );
95 static int Demux_Seekable ( demux_t * );
96 static int Demux_UnSeekable( demux_t * );
98 static char *FromACP( const char *str )
100 return FromCharset(vlc_pgettext("GetACP", "CP1252"), str, strlen(str));
103 #define IGNORE_ES NAV_ES
104 #define READ_LENGTH (25 * 1000) // 25ms
105 #define READ_LENGTH_NONINTERLEAVED (CLOCK_FREQ * 3 / 2)
111 vlc_fourcc_t i_fourcc;
114 vlc_fourcc_t i_type; /* only for AVIFOURCC_LIST */
116 uint8_t i_peek[8]; /* first 8 bytes */
118 unsigned int i_stream;
119 enum es_format_category_e i_cat;
129 int64_t i_lengthtotal;
137 avi_entry_t *p_entry;
140 static void avi_index_Init( avi_index_t * );
141 static void avi_index_Clean( avi_index_t * );
142 static void avi_index_Append( avi_index_t *, off_t *, avi_entry_t * );
150 unsigned int i_scale;
151 unsigned int i_samplesize;
153 unsigned int i_width_bytes;
160 es_out_id_t *p_es_dv_audio;
165 unsigned int i_idxposc; /* numero of chunk */
166 unsigned int i_idxposb; /* byte in the current chunk */
168 /* For VBR audio only */
169 unsigned int i_blockno;
170 unsigned int i_blocksize;
182 bool b_indexloaded; /* if we read indexes from end of file before starting */
183 mtime_t i_read_increment;
184 uint32_t i_avih_flags;
190 off_t i_movi_lastchunk_pos; /* XXX position of last valid chunk */
192 /* number of streams and information */
193 unsigned int i_track;
199 unsigned int i_attachment;
200 input_attachment_t **attachment;
203 static inline off_t __EVEN( off_t i )
205 return (i & 1) ? i + 1 : i;
208 static mtime_t AVI_PTSToChunk( avi_track_t *, mtime_t i_pts );
209 static mtime_t AVI_PTSToByte ( avi_track_t *, mtime_t i_pts );
210 static mtime_t AVI_GetDPTS ( avi_track_t *, int64_t i_count );
211 static mtime_t AVI_GetPTS ( avi_track_t * );
214 static int AVI_StreamChunkFind( demux_t *, unsigned int i_stream );
215 static int AVI_StreamChunkSet ( demux_t *,
216 unsigned int i_stream, unsigned int i_ck );
217 static int AVI_StreamBytesSet ( demux_t *,
218 unsigned int i_stream, off_t i_byte );
220 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t );
221 static int AVI_GetKeyFlag ( vlc_fourcc_t , uint8_t * );
223 static int AVI_PacketGetHeader( demux_t *, avi_packet_t *p_pk );
224 static int AVI_PacketNext ( demux_t * );
225 static int AVI_PacketSearch ( demux_t * );
227 static void AVI_IndexLoad ( demux_t * );
228 static void AVI_IndexCreate ( demux_t * );
230 static void AVI_ExtractSubtitle( demux_t *, unsigned int i_stream, avi_chunk_list_t *, avi_chunk_STRING_t * );
232 static void AVI_DvHandleAudio( demux_t *, avi_track_t *, block_t * );
234 static mtime_t AVI_MovieGetLength( demux_t * );
236 static void AVI_MetaLoad( demux_t *, avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih );
238 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
239 const int i_header, const int i_size );
241 /*****************************************************************************
243 *****************************************************************************/
244 static int AVI_TrackSeek ( demux_t *, int, mtime_t );
245 static int AVI_TrackStopFinishedStreams( demux_t *);
248 - For VBR mp3 stream:
249 count blocks by rounded-up chunksizes instead of chunks
250 we need full emulation of dshow avi demuxer bugs :(
251 fixes silly nandub-style a-v delaying in avi with vbr mp3...
252 (from mplayer 2002/08/02)
256 /*****************************************************************************
257 * Open: check file and initializes AVI structures
258 *****************************************************************************/
259 static int Open( vlc_object_t * p_this )
261 demux_t *p_demux = (demux_t *)p_this;
264 bool b_index = false, b_aborted = false;
267 avi_chunk_list_t *p_riff;
268 avi_chunk_list_t *p_hdrl, *p_movi;
269 avi_chunk_avih_t *p_avih;
271 unsigned int i_track;
272 unsigned int i_peeker;
274 const uint8_t *p_peek;
276 /* Is it an avi file ? */
277 if( vlc_stream_Peek( p_demux->s, &p_peek, 200 ) < 200 )
280 for( i_peeker = 0; i_peeker < 188; i_peeker++ )
282 if( !strncmp( (char *)&p_peek[0], "RIFF", 4 ) && !strncmp( (char *)&p_peek[8], "AVI ", 4 ) )
284 if( !strncmp( (char *)&p_peek[0], "ON2 ", 4 ) && !strncmp( (char *)&p_peek[8], "ON2f", 4 ) )
288 if( i_peeker == 188 )
294 && vlc_stream_Read( p_demux->s, NULL, i_peeker ) < i_peeker )
297 /* Initialize input structures. */
298 p_sys = p_demux->p_sys = calloc( 1, sizeof(demux_sys_t) );
299 if( unlikely(!p_sys) )
301 p_sys->b_odml = false;
304 TAB_INIT(p_sys->i_attachment, p_sys->attachment);
306 vlc_stream_Control( p_demux->s, STREAM_CAN_FASTSEEK,
307 &p_sys->b_fastseekable );
308 vlc_stream_Control( p_demux->s, STREAM_CAN_SEEK, &p_sys->b_seekable );
310 p_demux->pf_control = Control;
311 p_demux->pf_demux = (p_sys->b_seekable) ? Demux_Seekable : Demux_UnSeekable;
313 p_sys->b_interleaved = var_InheritBool( p_demux, "avi-interleaved" );
315 if( AVI_ChunkReadRoot( p_demux->s, &p_sys->ck_root ) )
317 msg_Err( p_demux, "avi module discarded (invalid file)" );
322 if( AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF ) > 1 )
324 unsigned int i_count =
325 AVI_ChunkCount( &p_sys->ck_root, AVIFOURCC_RIFF );
327 msg_Warn( p_demux, "multiple riff -> OpenDML ?" );
328 for( unsigned i = 1; i < i_count; i++ )
330 avi_chunk_list_t *p_sysx;
332 p_sysx = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, i );
333 if( p_sysx->i_type == AVIFOURCC_AVIX )
335 msg_Warn( p_demux, "detected OpenDML file" );
336 p_sys->b_odml = true;
342 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
343 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
344 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0 );
346 p_movi = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_movi, 0 );
348 if( !p_hdrl || !p_movi )
350 msg_Err( p_demux, "invalid file: cannot find hdrl or movi chunks" );
354 if( !( p_avih = AVI_ChunkFind( p_hdrl, AVIFOURCC_avih, 0 ) ) )
356 msg_Err( p_demux, "invalid file: cannot find avih chunk" );
359 i_track = AVI_ChunkCount( p_hdrl, AVIFOURCC_strl );
360 if( p_avih->i_streams != i_track )
363 "found %d stream but %d are declared",
364 i_track, p_avih->i_streams );
368 msg_Err( p_demux, "no stream defined!" );
372 /* print information on streams */
373 msg_Dbg( p_demux, "AVIH: %d stream, flags %s%s%s%s ",
375 p_avih->i_flags&AVIF_HASINDEX?" HAS_INDEX":"",
376 p_avih->i_flags&AVIF_MUSTUSEINDEX?" MUST_USE_INDEX":"",
377 p_avih->i_flags&AVIF_ISINTERLEAVED?" IS_INTERLEAVED":"",
378 p_avih->i_flags&AVIF_TRUSTCKTYPE?" TRUST_CKTYPE":"" );
380 p_sys->b_interleaved |= (p_avih->i_flags & AVIF_ISINTERLEAVED);
382 if( p_sys->b_interleaved && !p_sys->b_fastseekable )
383 p_sys->i_read_increment = READ_LENGTH;
385 p_sys->i_read_increment = READ_LENGTH_NONINTERLEAVED;
386 /* non seekable and non interleaved case ? well... */
388 AVI_MetaLoad( p_demux, p_riff, p_avih );
389 p_sys->i_avih_flags = p_avih->i_flags;
391 /* now read info on each stream and create ES */
392 for( unsigned i = 0 ; i < i_track; i++ )
394 avi_track_t *tk = calloc( 1, sizeof( avi_track_t ) );
395 if( unlikely( !tk ) )
398 avi_chunk_list_t *p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
399 avi_chunk_strh_t *p_strh = AVI_ChunkFind( p_strl, AVIFOURCC_strh, 0 );
400 avi_chunk_STRING_t *p_strn = AVI_ChunkFind( p_strl, AVIFOURCC_strn, 0 );
401 avi_chunk_strf_auds_t *p_auds = NULL;
402 avi_chunk_strf_vids_t *p_vids = NULL;
405 tk->b_activated = true;
407 p_vids = (avi_chunk_strf_vids_t*)AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
408 p_auds = (avi_chunk_strf_auds_t*)p_vids;
410 if( p_strl == NULL || p_strh == NULL || p_vids == NULL )
412 msg_Warn( p_demux, "stream[%d] incomplete", i );
417 tk->i_rate = p_strh->i_rate;
418 tk->i_scale = p_strh->i_scale;
419 tk->i_samplesize = p_strh->i_samplesize;
420 msg_Dbg( p_demux, "stream[%u] rate:%u scale:%u samplesize:%u",
421 i, tk->i_rate, tk->i_scale, tk->i_samplesize );
423 switch( p_strh->i_type )
425 case( AVIFOURCC_auds ):
427 es_format_Init( &tk->fmt, AUDIO_ES, 0 );
429 if( p_auds->p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE &&
430 p_auds->p_wf->cbSize >= sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX) )
432 WAVEFORMATEXTENSIBLE *p_wfe = (WAVEFORMATEXTENSIBLE *)p_auds->p_wf;
433 tk->fmt.i_codec = AVI_FourccGetCodec( AUDIO_ES, p_wfe->SubFormat.Data1 );
436 tk->fmt.i_codec = AVI_FourccGetCodec( AUDIO_ES, p_auds->p_wf->wFormatTag );
438 tk->i_blocksize = p_auds->p_wf->nBlockAlign;
439 if( tk->i_blocksize == 0 )
441 if( p_auds->p_wf->wFormatTag == 1 )
442 tk->i_blocksize = p_auds->p_wf->nChannels * (p_auds->p_wf->wBitsPerSample/8);
446 else if( tk->i_samplesize != 0 && tk->i_samplesize != tk->i_blocksize )
448 msg_Warn( p_demux, "track[%u] samplesize=%u and blocksize=%u are not equal."
449 "Using blocksize as a workaround.",
450 i, tk->i_samplesize, tk->i_blocksize );
451 tk->i_samplesize = tk->i_blocksize;
454 if( tk->fmt.i_codec == VLC_CODEC_VORBIS )
456 tk->i_blocksize = 0; /* fix vorbis VBR decoding */
459 if ( tk->fmt.i_codec == VLC_CODEC_MP4A )
461 tk->i_samplesize = 0; /* ADTS/AAC VBR */
464 /* Fix broken scale/rate */
465 if ( tk->fmt.i_codec == VLC_CODEC_ADPCM_IMA_WAV &&
466 tk->i_samplesize && tk->i_samplesize > tk->i_rate )
469 tk->i_rate = p_auds->p_wf->nSamplesPerSec;
472 /* From libavformat */
473 /* Fix broken sample size (which is mp2 num samples / frame) #12722 */
474 if( tk->fmt.i_codec == VLC_CODEC_MPGA &&
475 tk->i_samplesize == 1152 && p_auds->p_wf->nBlockAlign == 1152 )
477 p_auds->p_wf->nBlockAlign = tk->i_samplesize = 0;
480 tk->fmt.audio.i_channels = p_auds->p_wf->nChannels;
481 tk->fmt.audio.i_rate = p_auds->p_wf->nSamplesPerSec;
482 tk->fmt.i_bitrate = p_auds->p_wf->nAvgBytesPerSec*8;
483 tk->fmt.audio.i_blockalign = p_auds->p_wf->nBlockAlign;
484 tk->fmt.audio.i_bitspersample = p_auds->p_wf->wBitsPerSample;
485 tk->fmt.b_packetized = !tk->i_blocksize;
487 avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
490 int i_chunk = AVIFOURCC_IAS1 + ((i - 1) << 24);
491 avi_chunk_STRING_t *p_lang = AVI_ChunkFind( p_info, i_chunk, 0 );
492 if( p_lang != NULL && p_lang->p_str != NULL )
493 tk->fmt.psz_language = FromACP( p_lang->p_str );
497 "stream[%u] audio(0x%x - %s) %d channels %dHz %dbits",
498 i, p_auds->p_wf->wFormatTag,
499 vlc_fourcc_GetDescription(AUDIO_ES, tk->fmt.i_codec),
500 p_auds->p_wf->nChannels,
501 p_auds->p_wf->nSamplesPerSec,
502 p_auds->p_wf->wBitsPerSample );
504 if( p_auds->p_wf->cbSize > 0 && p_auds->i_chunk_size > sizeof(WAVEFORMATEX) )
506 int i_extra = __MIN( p_auds->p_wf->cbSize,
507 p_auds->i_chunk_size - sizeof(WAVEFORMATEX) );
508 tk->fmt.p_extra = malloc( i_extra );
509 if( unlikely(tk->fmt.p_extra == NULL) )
511 es_format_Clean( &tk->fmt );
515 tk->fmt.i_extra = i_extra;
516 memcpy( tk->fmt.p_extra, &p_auds->p_wf[1], tk->fmt.i_extra );
521 case( AVIFOURCC_vids ):
523 if( p_vids->p_bih->biCompression == VLC_FOURCC( 'D', 'X', 'S', 'B' ) )
525 msg_Dbg( p_demux, "stream[%u] subtitles", i );
526 es_format_Init( &tk->fmt, SPU_ES, p_vids->p_bih->biCompression );
530 es_format_Init( &tk->fmt, VIDEO_ES,
531 AVI_FourccGetCodec( VIDEO_ES, p_vids->p_bih->biCompression ) );
533 if( p_vids->p_bih->biCompression == BI_RAWRGB )
535 switch( p_vids->p_bih->biBitCount )
538 tk->fmt.i_codec = VLC_CODEC_RGB32;
541 tk->fmt.i_codec = VLC_CODEC_RGB24;
543 case 16: /* Yes it is RV15 */
545 tk->fmt.i_codec = VLC_CODEC_RGB15;
547 case 9: /* <- TODO check that */
548 tk->fmt.i_codec = VLC_CODEC_I410;
551 if ( p_vids->p_bih->biClrUsed )
552 tk->fmt.i_codec = VLC_CODEC_RGBP;
554 tk->fmt.i_codec = VLC_CODEC_GREY;
558 switch( tk->fmt.i_codec )
560 case VLC_CODEC_RGB24:
561 case VLC_CODEC_RGB32:
562 tk->fmt.video.i_rmask = 0x00ff0000;
563 tk->fmt.video.i_gmask = 0x0000ff00;
564 tk->fmt.video.i_bmask = 0x000000ff;
566 case VLC_CODEC_RGB15:
567 tk->fmt.video.i_rmask = 0x7c00;
568 tk->fmt.video.i_gmask = 0x03e0;
569 tk->fmt.video.i_bmask = 0x001f;
573 const VLC_BITMAPINFO *p_bi = (const VLC_BITMAPINFO *) p_vids->p_bih;
574 tk->fmt.video.p_palette = malloc( sizeof(video_palette_t) );
575 if ( tk->fmt.video.p_palette )
578 for( uint32_t j = 0; j < p_vids->p_bih->biClrUsed; j++ )
580 entry = GetDWBE( &p_bi->bmiColors[j] );
581 tk->fmt.video.p_palette->palette[j][0] = entry >> 24;
582 tk->fmt.video.p_palette->palette[j][1] = (entry >> 16) & 0xFF;
583 tk->fmt.video.p_palette->palette[j][2] = (entry >> 8) & 0xFF;
584 tk->fmt.video.p_palette->palette[j][3] = entry & 0xFF;
586 tk->fmt.video.p_palette->i_entries = p_vids->p_bih->biClrUsed;
594 tk->i_width_bytes = p_vids->p_bih->biWidth * (p_vids->p_bih->biBitCount >> 3);
595 /* RGB DIB are coded from bottom to top */
596 if ( p_vids->p_bih->biHeight < INT32_MAX ) tk->b_flipped = true;
600 tk->fmt.i_codec = p_vids->p_bih->biCompression;
601 if( tk->fmt.i_codec == VLC_CODEC_MP4V &&
602 !strncasecmp( (char*)&p_strh->i_handler, "XVID", 4 ) )
605 tk->fmt.i_original_fourcc = VLC_FOURCC( 'X', 'V', 'I', 'D' );
608 tk->i_samplesize = 0;
610 tk->fmt.video.i_visible_width =
611 tk->fmt.video.i_width = p_vids->p_bih->biWidth;
612 tk->fmt.video.i_visible_height =
613 tk->fmt.video.i_height = p_vids->p_bih->biHeight;
614 tk->fmt.video.i_bits_per_pixel = p_vids->p_bih->biBitCount;
615 tk->fmt.video.i_frame_rate = tk->i_rate;
616 tk->fmt.video.i_frame_rate_base = tk->i_scale;
618 /* Uncompresse Bitmap or YUV, YUV being always topdown */
619 if ( tk->fmt.video.i_height > INT32_MAX )
620 tk->fmt.video.i_height =
621 (unsigned int)(-(int)p_vids->p_bih->biHeight);
623 avi_chunk_vprp_t *p_vprp = AVI_ChunkFind( p_strl, AVIFOURCC_vprp, 0 );
626 uint32_t i_frame_aspect_ratio = p_vprp->i_frame_aspect_ratio;
627 if( p_vprp->i_video_format_token >= 1 &&
628 p_vprp->i_video_format_token <= 4 )
629 i_frame_aspect_ratio = 0x00040003;
630 tk->fmt.video.i_sar_num = ((i_frame_aspect_ratio >> 16) & 0xffff) *
631 tk->fmt.video.i_height;
632 tk->fmt.video.i_sar_den = ((i_frame_aspect_ratio >> 0) & 0xffff) *
633 tk->fmt.video.i_width;
635 /* Extradata is the remainder of the chunk less the BIH */
636 if( p_vids->i_chunk_size <= INT_MAX - sizeof(VLC_BITMAPINFOHEADER) )
638 int i_extra = p_vids->i_chunk_size - sizeof(VLC_BITMAPINFOHEADER);
641 tk->fmt.p_extra = malloc( i_extra );
642 if( unlikely(tk->fmt.p_extra == NULL) )
644 es_format_Clean( &tk->fmt );
648 tk->fmt.i_extra = i_extra;
649 memcpy( tk->fmt.p_extra, &p_vids->p_bih[1], tk->fmt.i_extra );
653 msg_Dbg( p_demux, "stream[%u] video(%4.4s) %"PRIu32"x%"PRIu32" %dbpp %ffps",
654 i, (char*)&p_vids->p_bih->biCompression,
655 (uint32_t)p_vids->p_bih->biWidth,
656 (uint32_t)p_vids->p_bih->biHeight,
657 p_vids->p_bih->biBitCount,
658 (float)tk->i_rate/(float)tk->i_scale );
660 /* Extract palette from extradata if bpp <= 8 */
661 if( tk->fmt.video.i_bits_per_pixel > 0 && tk->fmt.video.i_bits_per_pixel <= 8 )
663 /* The palette should not be included in biSize, but come
664 * directly after BITMAPINFORHEADER in the BITMAPINFO structure */
665 if( tk->fmt.i_extra > 0 )
667 tk->fmt.video.p_palette = calloc( 1, sizeof(video_palette_t) );
668 if( likely(tk->fmt.video.p_palette) )
670 const uint8_t *p_pal = tk->fmt.p_extra;
671 tk->fmt.video.p_palette->i_entries = __MIN(tk->fmt.i_extra/4, 256);
672 for( int k = 0; k < tk->fmt.video.p_palette->i_entries; k++ )
674 for( int j = 0; j < 4; j++ )
675 tk->fmt.video.p_palette->palette[k][j] = p_pal[4*k+j];
683 case( AVIFOURCC_txts):
684 msg_Dbg( p_demux, "stream[%u] subtitle attachment", i );
685 AVI_ExtractSubtitle( p_demux, i, p_strl, p_strn );
689 case( AVIFOURCC_iavs):
690 case( AVIFOURCC_ivas):
691 msg_Dbg( p_demux, "stream[%u] iavs with handler %4.4s", i, (char *)&p_strh->i_handler );
692 es_format_Init( &tk->fmt, VIDEO_ES, p_strh->i_handler );
693 tk->i_samplesize = 0;
694 tk->i_dv_audio_rate = p_strh->i_handler == VLC_CODEC_DV ? -1 : 0;
696 tk->fmt.video.i_visible_width =
697 tk->fmt.video.i_width = p_avih->i_width;
698 tk->fmt.video.i_visible_height =
699 tk->fmt.video.i_height = p_avih->i_height;
702 case( AVIFOURCC_mids):
703 msg_Dbg( p_demux, "stream[%u] midi is UNSUPPORTED", i );
706 msg_Warn( p_demux, "stream[%u] unknown type %4.4s", i, (char *)&p_strh->i_type );
710 if( p_strn && p_strn->p_str )
711 tk->fmt.psz_description = FromACP( p_strn->p_str );
712 tk->p_es = es_out_Add( p_demux->out, &tk->fmt );
713 TAB_APPEND( p_sys->i_track, p_sys->track, tk );
716 if( p_sys->i_track <= 0 )
718 msg_Err( p_demux, "no valid track" );
722 i_do_index = var_InheritInteger( p_demux, "avi-index" );
723 if( i_do_index == 1 ) /* Always fix */
726 if( p_sys->b_fastseekable )
728 AVI_IndexCreate( p_demux );
730 else if( p_sys->b_seekable )
732 AVI_IndexLoad( p_demux );
736 msg_Warn( p_demux, "cannot create index (unseekable stream)" );
739 else if( p_sys->b_seekable )
741 AVI_IndexLoad( p_demux );
744 /* *** movie length in sec *** */
745 p_sys->i_length = AVI_MovieGetLength( p_demux );
747 /* Check the index completeness */
748 unsigned int i_idx_totalframes = 0;
749 for( unsigned int i = 0; i < p_sys->i_track; i++ )
751 const avi_track_t *tk = p_sys->track[i];
752 if( tk->fmt.i_cat == VIDEO_ES && tk->idx.p_entry )
753 i_idx_totalframes = __MAX(i_idx_totalframes, tk->idx.i_size);
755 if( i_idx_totalframes != p_avih->i_totalframes &&
756 p_sys->i_length < (mtime_t)p_avih->i_totalframes *
757 (mtime_t)p_avih->i_microsecperframe /
760 msg_Warn( p_demux, "broken or missing index, 'seek' will be "
761 "approximative or will exhibit strange behavior" );
762 if( (i_do_index == 0 || i_do_index == 3) && !b_index )
764 if( !p_sys->b_fastseekable ) {
768 if( i_do_index == 0 )
770 const char *psz_msg = _(
771 "Because this file index is broken or missing, "
772 "seeking will not work correctly.\n"
773 "VLC won't repair your file but can temporary fix this "
774 "problem by building an index in memory.\n"
775 "This step might take a long time on a large file.\n"
776 "What do you want to do?");
777 switch( vlc_dialog_wait_question( p_demux,
778 VLC_DIALOG_QUESTION_NORMAL,
780 _("Build index then play"),
782 _("Broken or missing Index"),
790 msg_Dbg( p_demux, "Fixing AVI index" );
797 msg_Dbg( p_demux, "Fixing AVI index" );
803 /* fix some BeOS MediaKit generated file */
804 for( unsigned i = 0 ; i < p_sys->i_track; i++ )
806 avi_track_t *tk = p_sys->track[i];
807 avi_chunk_list_t *p_strl;
808 avi_chunk_strf_auds_t *p_auds;
810 if( tk->fmt.i_cat != AUDIO_ES )
814 if( tk->idx.i_size < 1 ||
816 tk->i_samplesize != 0 )
820 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i );
821 p_auds = AVI_ChunkFind( p_strl, AVIFOURCC_strf, 0 );
823 if( p_auds->p_wf->wFormatTag != WAVE_FORMAT_PCM &&
824 tk->i_rate == p_auds->p_wf->nSamplesPerSec )
826 int64_t i_track_length =
827 tk->idx.p_entry[tk->idx.i_size-1].i_length +
828 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal;
829 mtime_t i_length = (mtime_t)p_avih->i_totalframes *
830 (mtime_t)p_avih->i_microsecperframe;
834 msg_Warn( p_demux, "track[%u] cannot be fixed (BeOS MediaKit generated)", i );
837 tk->i_samplesize = 1;
838 tk->i_rate = i_track_length * CLOCK_FREQ / i_length;
839 msg_Warn( p_demux, "track[%u] fixed with rate=%u scale=%u (BeOS MediaKit generated)", i, tk->i_rate, tk->i_scale );
843 if( p_sys->b_seekable )
845 /* we have read all chunk so go back to movi */
846 if( vlc_stream_Seek( p_demux->s, p_movi->i_chunk_pos ) )
849 /* Skip movi header */
850 if( vlc_stream_Read( p_demux->s, NULL, 12 ) < 12 )
853 p_sys->i_movi_begin = p_movi->i_chunk_pos;
857 for( unsigned i = 0; i < p_sys->i_attachment; i++)
858 vlc_input_attachment_Delete(p_sys->attachment[i]);
859 free(p_sys->attachment);
862 vlc_meta_Delete( p_sys->meta );
864 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
866 return b_aborted ? VLC_ETIMEOUT : VLC_EGENERIC;
869 /*****************************************************************************
870 * Close: frees unused data
871 *****************************************************************************/
872 static void Close ( vlc_object_t * p_this )
874 demux_t * p_demux = (demux_t *)p_this;
875 demux_sys_t *p_sys = p_demux->p_sys ;
877 for( unsigned int i = 0; i < p_sys->i_track; i++ )
879 if( p_sys->track[i] )
881 es_format_Clean( &p_sys->track[i]->fmt );
882 avi_index_Clean( &p_sys->track[i]->idx );
883 free( p_sys->track[i] );
886 free( p_sys->track );
888 AVI_ChunkFreeRoot( p_demux->s, &p_sys->ck_root );
889 vlc_meta_Delete( p_sys->meta );
891 for( unsigned i = 0; i < p_sys->i_attachment; i++)
892 vlc_input_attachment_Delete(p_sys->attachment[i]);
893 free(p_sys->attachment);
898 /*****************************************************************************
899 * ReadFrame: Reads frame, using stride if necessary
900 *****************************************************************************/
902 block_t * ReadFrame( demux_t *p_demux, const avi_track_t *tk,
903 const int i_header, const int i_size )
905 block_t *p_frame = vlc_stream_Block( p_demux->s, __EVEN( i_size ) );
906 if ( !p_frame ) return p_frame;
908 if( i_size % 2 ) /* read was padded on word boundary */
914 p_frame->p_buffer += i_header;
915 p_frame->i_buffer -= i_header;
917 if ( !tk->i_width_bytes )
920 const unsigned int i_stride_bytes = ((( (tk->i_width_bytes << 3) + 31) & ~31) >> 3);
922 if ( p_frame->i_buffer < i_stride_bytes )
924 p_frame->i_buffer = 0;
930 const uint8_t *p_src = p_frame->p_buffer + i_stride_bytes;
931 const uint8_t *p_end = p_frame->p_buffer + p_frame->i_buffer;
932 uint8_t *p_dst = p_frame->p_buffer + tk->i_width_bytes;
934 p_frame->i_buffer = tk->i_width_bytes;
936 while ( p_src + i_stride_bytes <= p_end )
938 memmove( p_dst, p_src, tk->i_width_bytes );
939 p_src += i_stride_bytes;
940 p_dst += tk->i_width_bytes;
941 p_frame->i_buffer += tk->i_width_bytes;
946 block_t *p_flippedframe = block_Alloc( p_frame->i_buffer );
947 if ( !p_flippedframe )
949 block_Release( p_frame );
953 unsigned int i_lines = p_frame->i_buffer / i_stride_bytes;
954 const uint8_t *p_src = p_frame->p_buffer + i_lines * i_stride_bytes;
955 uint8_t *p_dst = p_flippedframe->p_buffer;
957 p_flippedframe->i_buffer = 0;
959 while ( i_lines-- > 0 )
961 p_src -= i_stride_bytes;
962 memcpy( p_dst, p_src, tk->i_width_bytes );
963 p_dst += tk->i_width_bytes;
964 p_flippedframe->i_buffer += tk->i_width_bytes;
967 block_Release( p_frame );
968 p_frame = p_flippedframe;
974 /*****************************************************************************
975 * Demux_Seekable: reads and demuxes data packets for stream seekable
976 *****************************************************************************
977 * AVIDemux: reads and demuxes data packets
978 *****************************************************************************
979 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
980 *****************************************************************************/
987 off_t i_posf; /* where we will read :
988 if i_idxposb == 0 : begining of chunk (+8 to acces data)
989 else : point on data directly */
990 } avi_track_toread_t;
992 static int Demux_Seekable( demux_t *p_demux )
994 demux_sys_t *p_sys = p_demux->p_sys;
996 unsigned int i_track_count = 0;
997 unsigned int i_track;
998 /* cannot be more than 100 stream (dcXX or wbXX) */
999 avi_track_toread_t toread[100];
1002 /* detect new selected/unselected streams */
1003 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1005 avi_track_t *tk = p_sys->track[i_track];
1008 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1009 if( tk->p_es_dv_audio )
1011 bool b_extra = false;
1012 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1015 if( b && !tk->b_activated )
1017 if( p_sys->b_seekable)
1019 AVI_TrackSeek( p_demux, i_track, p_sys->i_time );
1021 tk->b_activated = true;
1023 else if( !b && tk->b_activated )
1025 tk->b_activated = false;
1033 if( i_track_count <= 0 )
1035 int64_t i_length = p_sys->i_length * CLOCK_FREQ;
1037 p_sys->i_time += p_sys->i_read_increment;
1040 if( p_sys->i_time >= i_length )
1041 return VLC_DEMUXER_EOF;
1042 return VLC_DEMUXER_SUCCESS;
1044 msg_Warn( p_demux, "no track selected, exiting..." );
1045 return VLC_DEMUXER_EOF;
1048 /* wait for the good time */
1049 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1050 p_sys->i_time += p_sys->i_read_increment;
1053 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1055 avi_track_t *tk = p_sys->track[i_track];
1057 toread[i_track].b_ok = tk->b_activated && !tk->b_eof;
1058 if( tk->i_idxposc < tk->idx.i_size )
1060 toread[i_track].i_posf = tk->idx.p_entry[tk->i_idxposc].i_pos;
1061 if( tk->i_idxposb > 0 )
1063 toread[i_track].i_posf += 8 + tk->i_idxposb;
1068 toread[i_track].i_posf = -1;
1071 mtime_t i_dpts = p_sys->i_time - AVI_GetPTS( tk );
1073 if( tk->i_samplesize )
1075 toread[i_track].i_toread = AVI_PTSToByte( tk, i_dpts );
1077 else if ( i_dpts > -2 * CLOCK_FREQ ) /* don't send a too early dts (low fps video) */
1079 toread[i_track].i_toread = AVI_PTSToChunk( tk, i_dpts );
1082 toread[i_track].i_toread = -1;
1094 /* search for first chunk to be read */
1095 for( i = 0, b_done = true, i_pos = -1; i < p_sys->i_track; i++ )
1097 if( !toread[i].b_ok ||
1098 ( p_sys->b_fastseekable && p_sys->b_interleaved &&
1099 AVI_GetDPTS( p_sys->track[i], toread[i].i_toread ) <= -p_sys->i_read_increment ) )
1104 if( toread[i].i_toread >= 0 )
1106 b_done = false; /* not yet finished */
1108 if( toread[i].i_posf > 0 )
1110 if( i_pos == -1 || i_pos > toread[i].i_posf )
1113 i_pos = toread[i].i_posf;
1120 for( i = 0; i < p_sys->i_track; i++ )
1122 if( toread[i].b_ok )
1123 return VLC_DEMUXER_SUCCESS;
1125 msg_Warn( p_demux, "all tracks have failed, exiting..." );
1126 return VLC_DEMUXER_EOF;
1131 int i_loop_count = 0;
1133 /* no valid index, we will parse directly the stream
1134 * in case we fail we will disable all finished stream */
1135 if( p_sys->b_seekable && p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1137 vlc_stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1138 if( AVI_PacketNext( p_demux ) )
1140 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1145 vlc_stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1150 avi_packet_t avi_pk;
1152 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1155 "cannot get packet header, track disabled" );
1156 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1158 if( avi_pk.i_stream >= p_sys->i_track ||
1159 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1161 if( AVI_PacketNext( p_demux ) )
1164 "cannot skip packet, track disabled" );
1165 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1168 /* Prevents from eating all the CPU with broken files.
1169 * This value should be low enough so that it doesn't
1170 * affect the reading speed too much. */
1171 if( !(++i_loop_count % 1024) )
1175 if( !(i_loop_count % (1024 * 10)) )
1177 "don't seem to find any data..." );
1183 i_track = avi_pk.i_stream;
1184 tk = p_sys->track[i_track];
1186 /* add this chunk to the index */
1188 index.i_id = avi_pk.i_fourcc;
1189 index.i_flags = AVI_GetKeyFlag(tk->fmt.i_codec, avi_pk.i_peek);
1190 index.i_pos = avi_pk.i_pos;
1191 index.i_length = avi_pk.i_size;
1192 index.i_lengthtotal = index.i_length;
1193 avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1195 /* do we will read this data ? */
1196 if( AVI_GetDPTS( tk, toread[i_track].i_toread ) > -p_sys->i_read_increment )
1202 if( AVI_PacketNext( p_demux ) )
1205 "cannot skip packet, track disabled" );
1206 return( AVI_TrackStopFinishedStreams( p_demux ) ? 0 : 1 );
1215 if( !p_sys->b_fastseekable
1216 && (i_pos > vlc_stream_Tell( p_demux->s )) )
1218 vlc_stream_Read( p_demux->s, NULL,
1219 i_pos - vlc_stream_Tell( p_demux->s ) );
1223 vlc_stream_Seek( p_demux->s, i_pos );
1227 /* Set the track to use */
1228 tk = p_sys->track[i_track];
1230 /* read thoses data */
1231 if( tk->i_samplesize )
1233 unsigned int i_toread;
1235 if( ( i_toread = toread[i_track].i_toread ) <= 0 )
1237 if( tk->i_samplesize > 1 )
1239 i_toread = tk->i_samplesize;
1243 i_toread = AVI_PTSToByte( tk, 20 * 1000 );
1244 i_toread = __MAX( i_toread, 100 );
1247 i_size = __MIN( tk->idx.p_entry[tk->i_idxposc].i_length -
1253 i_size = tk->idx.p_entry[tk->i_idxposc].i_length;
1256 if( tk->i_idxposb == 0 )
1258 i_size += 8; /* need to read and skip header */
1261 if( ( p_frame = ReadFrame( p_demux, tk,
1262 ( tk->i_idxposb == 0 ) ? 8 : 0, i_size ) )==NULL )
1264 msg_Warn( p_demux, "failed reading data" );
1266 toread[i_track].b_ok = false;
1270 p_frame->i_pts = VLC_TS_0 + AVI_GetPTS( tk );
1271 if( tk->idx.p_entry[tk->i_idxposc].i_flags&AVIIF_KEYFRAME )
1273 p_frame->i_flags = BLOCK_FLAG_TYPE_I;
1277 p_frame->i_flags = BLOCK_FLAG_TYPE_PB;
1281 if( tk->i_samplesize )
1283 if( tk->i_idxposb == 0 )
1287 toread[i_track].i_toread -= i_size;
1288 tk->i_idxposb += i_size;
1289 if( tk->i_idxposb >=
1290 tk->idx.p_entry[tk->i_idxposc].i_length )
1298 int i_length = tk->idx.p_entry[tk->i_idxposc].i_length;
1301 if( tk->fmt.i_cat == AUDIO_ES )
1303 tk->i_blockno += tk->i_blocksize > 0 ? ( i_length + tk->i_blocksize - 1 ) / tk->i_blocksize : 1;
1305 toread[i_track].i_toread--;
1308 if( tk->i_idxposc < tk->idx.i_size)
1310 toread[i_track].i_posf =
1311 tk->idx.p_entry[tk->i_idxposc].i_pos;
1312 if( tk->i_idxposb > 0 )
1314 toread[i_track].i_posf += 8 + tk->i_idxposb;
1320 toread[i_track].i_posf = -1;
1323 if( tk->fmt.i_cat != VIDEO_ES )
1324 p_frame->i_dts = p_frame->i_pts;
1327 p_frame->i_dts = p_frame->i_pts;
1328 p_frame->i_pts = VLC_TS_INVALID;
1331 if( tk->i_dv_audio_rate )
1332 AVI_DvHandleAudio( p_demux, tk, p_frame );
1335 es_out_Send( p_demux->out, tk->p_es, p_frame );
1337 block_Release( p_frame );
1342 /*****************************************************************************
1343 * Demux_UnSeekable: reads and demuxes data packets for unseekable file
1344 *****************************************************************************
1345 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1346 *****************************************************************************/
1347 static int Demux_UnSeekable( demux_t *p_demux )
1349 demux_sys_t *p_sys = p_demux->p_sys;
1350 avi_track_t *p_stream_master = NULL;
1351 unsigned int i_stream;
1352 unsigned int i_packet;
1354 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1356 /* *** find master stream for data packet skipping algo *** */
1357 /* *** -> first video, if any, or first audio ES *** */
1358 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1360 avi_track_t *tk = p_sys->track[i_stream];
1363 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1364 if( tk->p_es_dv_audio )
1367 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es_dv_audio, &b_extra );
1373 if( tk->fmt.i_cat == VIDEO_ES )
1375 p_stream_master = tk;
1378 else if( !p_stream_master )
1380 p_stream_master = tk;
1385 if( !p_stream_master )
1387 if( p_sys->i_track )
1389 p_stream_master = p_sys->track[0];
1393 msg_Warn( p_demux, "no more stream selected" );
1394 return VLC_DEMUXER_EOF;
1398 p_sys->i_time = AVI_GetPTS( p_stream_master );
1400 for( i_packet = 0; i_packet < 10; i_packet++)
1402 #define p_stream p_sys->track[avi_pk.i_stream]
1404 avi_packet_t avi_pk;
1406 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1408 return VLC_DEMUXER_EOF;
1411 if( avi_pk.i_stream >= p_sys->i_track ||
1412 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1414 /* we haven't found an audio or video packet:
1415 * - we have seek, found first next packet
1416 * - others packets could be found, skip them
1418 switch( avi_pk.i_fourcc )
1420 case AVIFOURCC_JUNK:
1421 case AVIFOURCC_LIST:
1422 case AVIFOURCC_RIFF:
1423 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1424 case AVIFOURCC_idx1:
1427 return( !AVI_PacketNext( p_demux ) ? 1 : 0 );
1429 return VLC_DEMUXER_EOF;
1432 "seems to have lost position @%"PRIu64", resync",
1433 vlc_stream_Tell(p_demux->s) );
1434 if( AVI_PacketSearch( p_demux ) )
1436 msg_Err( p_demux, "resync failed" );
1437 return VLC_DEMUXER_EGENERIC;
1443 /* check for time */
1444 if( p_stream == p_stream_master ||
1445 llabs( AVI_GetPTS( p_stream ) -
1446 AVI_GetPTS( p_stream_master ) )< 2 * CLOCK_FREQ )
1448 /* load it and send to decoder */
1449 block_t *p_frame = ReadFrame( p_demux, p_stream, 8, avi_pk.i_size + 8 ) ;
1450 if( p_frame == NULL )
1452 return VLC_DEMUXER_EGENERIC;
1454 p_frame->i_pts = VLC_TS_0 + AVI_GetPTS( p_stream );
1456 if( avi_pk.i_cat != VIDEO_ES )
1457 p_frame->i_dts = p_frame->i_pts;
1460 p_frame->i_dts = p_frame->i_pts;
1461 p_frame->i_pts = VLC_TS_INVALID;
1464 if( p_stream->i_dv_audio_rate )
1465 AVI_DvHandleAudio( p_demux, p_stream, p_frame );
1467 if( p_stream->p_es )
1468 es_out_Send( p_demux->out, p_stream->p_es, p_frame );
1470 block_Release( p_frame );
1474 if( AVI_PacketNext( p_demux ) )
1476 return VLC_DEMUXER_EOF;
1480 /* *** update stream time position *** */
1481 if( p_stream->i_samplesize )
1483 p_stream->i_idxposb += avi_pk.i_size;
1487 if( p_stream->fmt.i_cat == AUDIO_ES )
1489 p_stream->i_blockno += p_stream->i_blocksize > 0 ? ( avi_pk.i_size + p_stream->i_blocksize - 1 ) / p_stream->i_blocksize : 1;
1491 p_stream->i_idxposc++;
1498 return VLC_DEMUXER_SUCCESS;
1501 /*****************************************************************************
1502 * Seek: goto to i_date or i_percent
1503 *****************************************************************************/
1504 static int Seek( demux_t *p_demux, mtime_t i_date, int i_percent )
1506 demux_sys_t *p_sys = p_demux->p_sys;
1507 msg_Dbg( p_demux, "seek requested: %"PRId64" seconds %d%%",
1508 i_date / CLOCK_FREQ, i_percent );
1510 if( p_sys->b_seekable )
1512 int64_t i_pos_backup = vlc_stream_Tell( p_demux->s );
1514 /* Check and lazy load indexes if it was not done (not fastseekable) */
1515 if ( !p_sys->b_indexloaded && ( p_sys->i_avih_flags & AVIF_HASINDEX ) )
1517 avi_chunk_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0 );
1518 if (unlikely( !p_riff ))
1519 return VLC_EGENERIC;
1521 int i_ret = AVI_ChunkFetchIndexes( p_demux->s, p_riff );
1524 /* Go back to position before index failure */
1525 if ( vlc_stream_Tell( p_demux->s ) - i_pos_backup )
1526 vlc_stream_Seek( p_demux->s, i_pos_backup );
1528 if ( p_sys->i_avih_flags & AVIF_MUSTUSEINDEX )
1529 return VLC_EGENERIC;
1531 else AVI_IndexLoad( p_demux );
1533 p_sys->b_indexloaded = true; /* we don't want to try each time */
1536 if( !p_sys->i_length )
1538 avi_track_t *p_stream = NULL;
1539 unsigned i_stream = 0;
1542 if ( !p_sys->i_movi_lastchunk_pos && /* set when index is successfully loaded */
1543 ! ( p_sys->i_avih_flags & AVIF_ISINTERLEAVED ) )
1545 msg_Err( p_demux, "seeking without index at %d%%"
1546 " only works for interleaved files", i_percent );
1547 goto failandresetpos;
1549 /* use i_percent to create a true i_date */
1550 if( i_percent >= 100 )
1552 msg_Warn( p_demux, "cannot seek so far !" );
1553 goto failandresetpos;
1555 i_percent = __MAX( i_percent, 0 );
1557 /* try to find chunk that is at i_percent or the file */
1558 i_pos = __MAX( i_percent * stream_Size( p_demux->s ) / 100,
1559 p_sys->i_movi_begin );
1560 /* search first selected stream (and prefer non-EOF ones) */
1561 for( unsigned i = 0; i < p_sys->i_track; i++ )
1563 avi_track_t *p_track = p_sys->track[i];
1564 if( !p_track->b_activated )
1569 if( !p_track->b_eof )
1572 if( p_stream == NULL )
1574 msg_Warn( p_demux, "cannot find any selected stream" );
1575 goto failandresetpos;
1578 /* be sure that the index exist */
1579 if( AVI_StreamChunkSet( p_demux, i_stream, 0 ) )
1581 msg_Warn( p_demux, "cannot seek" );
1582 goto failandresetpos;
1585 while( i_pos >= p_stream->idx.p_entry[p_stream->i_idxposc].i_pos +
1586 p_stream->idx.p_entry[p_stream->i_idxposc].i_length + 8 )
1588 /* search after i_idxposc */
1589 if( AVI_StreamChunkSet( p_demux,
1590 i_stream, p_stream->i_idxposc + 1 ) )
1592 msg_Warn( p_demux, "cannot seek" );
1593 goto failandresetpos;
1597 i_date = AVI_GetPTS( p_stream );
1598 /* TODO better support for i_samplesize != 0 */
1599 msg_Dbg( p_demux, "estimate date %"PRId64, i_date );
1603 for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
1605 avi_track_t *p_stream = p_sys->track[i_stream];
1607 if( !p_stream->b_activated )
1610 p_stream->b_eof = AVI_TrackSeek( p_demux, i_stream, i_date ) != 0;
1612 p_sys->i_time = i_date;
1613 es_out_Control( p_demux->out, ES_OUT_SET_PCR, VLC_TS_0 + p_sys->i_time );
1614 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, VLC_TS_0 + p_sys->i_time );
1615 msg_Dbg( p_demux, "seek: %"PRId64" seconds", p_sys->i_time /CLOCK_FREQ );
1619 /* Go back to position before index failure */
1620 if ( vlc_stream_Tell( p_demux->s ) - i_pos_backup )
1621 vlc_stream_Seek( p_demux->s, i_pos_backup );
1623 return VLC_EGENERIC;
1627 msg_Err( p_demux, "shouldn't yet be executed" );
1628 return VLC_EGENERIC;
1632 /*****************************************************************************
1634 *****************************************************************************/
1635 static double ControlGetPosition( demux_t *p_demux )
1637 demux_sys_t *p_sys = p_demux->p_sys;
1639 if( p_sys->i_length > 0 )
1641 return (double)p_sys->i_time / (double)( p_sys->i_length * (mtime_t)CLOCK_FREQ );
1643 else if( stream_Size( p_demux->s ) > 0 )
1645 double i64 = (uint64_t)vlc_stream_Tell( p_demux->s );
1646 return i64 / stream_Size( p_demux->s );
1651 static int Control( demux_t *p_demux, int i_query, va_list args )
1653 demux_sys_t *p_sys = p_demux->p_sys;
1660 case DEMUX_CAN_SEEK:
1661 *va_arg( args, bool * ) = p_sys->b_seekable;
1664 case DEMUX_GET_POSITION:
1665 pf = va_arg( args, double * );
1666 *pf = ControlGetPosition( p_demux );
1668 case DEMUX_SET_POSITION:
1669 f = va_arg( args, double );
1670 if ( !p_sys->b_seekable )
1672 return VLC_EGENERIC;
1676 i64 = (mtime_t)(f * CLOCK_FREQ * p_sys->i_length);
1677 return Seek( p_demux, i64, (int)(f * 100) );
1680 case DEMUX_GET_TIME:
1681 pi64 = va_arg( args, int64_t * );
1682 *pi64 = p_sys->i_time;
1685 case DEMUX_SET_TIME:
1689 i64 = va_arg( args, int64_t );
1690 if( !p_sys->b_seekable )
1692 return VLC_EGENERIC;
1694 else if( p_sys->i_length > 0 )
1696 i_percent = 100 * i64 / (p_sys->i_length*CLOCK_FREQ);
1698 else if( p_sys->i_time > 0 )
1700 i_percent = (int)( 100.0 * ControlGetPosition( p_demux ) *
1701 (double)i64 / (double)p_sys->i_time );
1703 return Seek( p_demux, i64, i_percent );
1705 case DEMUX_GET_LENGTH:
1706 pi64 = va_arg( args, int64_t * );
1707 *pi64 = p_sys->i_length * (mtime_t)CLOCK_FREQ;
1711 pf = va_arg( args, double * );
1713 for( unsigned i = 0; i < p_sys->i_track; i++ )
1715 avi_track_t *tk = p_sys->track[i];
1716 if( tk->fmt.i_cat == VIDEO_ES && tk->i_scale > 0)
1718 *pf = (float)tk->i_rate / (float)tk->i_scale;
1724 case DEMUX_GET_META:
1725 p_meta = va_arg( args, vlc_meta_t * );
1726 vlc_meta_Merge( p_meta, p_sys->meta );
1729 case DEMUX_GET_ATTACHMENTS:
1731 if( p_sys->i_attachment <= 0 )
1732 return VLC_EGENERIC;
1734 input_attachment_t ***ppp_attach = va_arg( args, input_attachment_t*** );
1735 int *pi_int = va_arg( args, int * );
1737 *ppp_attach = calloc( p_sys->i_attachment, sizeof(**ppp_attach) );
1738 if( likely(*ppp_attach) )
1740 *pi_int = p_sys->i_attachment;
1741 for( unsigned i = 0; i < p_sys->i_attachment; i++ )
1742 (*ppp_attach)[i] = vlc_input_attachment_Duplicate( p_sys->attachment[i] );
1745 return VLC_EGENERIC;
1749 return VLC_EGENERIC;
1753 /*****************************************************************************
1754 * Function to convert pts to chunk or byte
1755 *****************************************************************************/
1757 static mtime_t AVI_PTSToChunk( avi_track_t *tk, mtime_t i_pts )
1762 return (mtime_t)((int64_t)i_pts *
1763 (int64_t)tk->i_rate /
1764 (int64_t)tk->i_scale /
1765 (int64_t)CLOCK_FREQ );
1767 static mtime_t AVI_PTSToByte( avi_track_t *tk, mtime_t i_pts )
1769 if( !tk->i_scale || !tk->i_samplesize )
1772 return (mtime_t)((int64_t)i_pts *
1773 (int64_t)tk->i_rate /
1774 (int64_t)tk->i_scale /
1776 (int64_t)tk->i_samplesize );
1779 static mtime_t AVI_GetDPTS( avi_track_t *tk, int64_t i_count )
1786 i_dpts = (mtime_t)( (int64_t)1000000 *
1788 (int64_t)tk->i_scale /
1789 (int64_t)tk->i_rate );
1791 if( tk->i_samplesize )
1793 return i_dpts / tk->i_samplesize;
1798 static mtime_t AVI_GetPTS( avi_track_t *tk )
1800 if( tk->i_samplesize )
1802 int64_t i_count = 0;
1804 /* we need a valid entry we will emulate one */
1805 if( tk->i_idxposc == tk->idx.i_size )
1809 /* use the last entry */
1810 i_count = tk->idx.p_entry[tk->idx.i_size - 1].i_lengthtotal
1811 + tk->idx.p_entry[tk->idx.i_size - 1].i_length;
1816 i_count = tk->idx.p_entry[tk->i_idxposc].i_lengthtotal;
1818 return AVI_GetDPTS( tk, i_count + tk->i_idxposb );
1822 if( tk->fmt.i_cat == AUDIO_ES )
1824 return AVI_GetDPTS( tk, tk->i_blockno );
1828 return AVI_GetDPTS( tk, tk->i_idxposc );
1833 static int AVI_StreamChunkFind( demux_t *p_demux, unsigned int i_stream )
1835 demux_sys_t *p_sys = p_demux->p_sys;
1836 avi_packet_t avi_pk;
1837 int i_loop_count = 0;
1839 /* find first chunk of i_stream that isn't in index */
1841 if( p_sys->i_movi_lastchunk_pos >= p_sys->i_movi_begin + 12 )
1843 vlc_stream_Seek( p_demux->s, p_sys->i_movi_lastchunk_pos );
1844 if( AVI_PacketNext( p_demux ) )
1846 return VLC_EGENERIC;
1851 vlc_stream_Seek( p_demux->s, p_sys->i_movi_begin + 12 );
1856 if( AVI_PacketGetHeader( p_demux, &avi_pk ) )
1858 msg_Warn( p_demux, "cannot get packet header" );
1859 return VLC_EGENERIC;
1861 if( avi_pk.i_stream >= p_sys->i_track ||
1862 ( avi_pk.i_cat != AUDIO_ES && avi_pk.i_cat != VIDEO_ES ) )
1864 if( AVI_PacketNext( p_demux ) )
1866 return VLC_EGENERIC;
1869 /* Prevents from eating all the CPU with broken files.
1870 * This value should be low enough so that it doesn't
1871 * affect the reading speed too much. */
1872 if( !(++i_loop_count % 1024) )
1876 if( !(i_loop_count % (1024 * 10)) )
1877 msg_Warn( p_demux, "don't seem to find any data..." );
1882 avi_track_t *tk_pk = p_sys->track[avi_pk.i_stream];
1884 /* add this chunk to the index */
1886 index.i_id = avi_pk.i_fourcc;
1887 index.i_flags = AVI_GetKeyFlag(tk_pk->fmt.i_codec, avi_pk.i_peek);
1888 index.i_pos = avi_pk.i_pos;
1889 index.i_length = avi_pk.i_size;
1890 index.i_lengthtotal = index.i_length;
1891 avi_index_Append( &tk_pk->idx, &p_sys->i_movi_lastchunk_pos, &index );
1893 if( avi_pk.i_stream == i_stream )
1898 if( AVI_PacketNext( p_demux ) )
1900 return VLC_EGENERIC;
1906 /* be sure that i_ck will be a valid index entry */
1907 static int AVI_StreamChunkSet( demux_t *p_demux, unsigned int i_stream,
1910 demux_sys_t *p_sys = p_demux->p_sys;
1911 avi_track_t *p_stream = p_sys->track[i_stream];
1913 p_stream->i_idxposc = i_ck;
1914 p_stream->i_idxposb = 0;
1916 if( i_ck >= p_stream->idx.i_size )
1918 p_stream->i_idxposc = p_stream->idx.i_size - 1;
1921 p_stream->i_idxposc++;
1922 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1924 return VLC_EGENERIC;
1927 } while( p_stream->i_idxposc < i_ck );
1933 /* XXX FIXME up to now, we assume that all chunk are one after one */
1934 static int AVI_StreamBytesSet( demux_t *p_demux,
1935 unsigned int i_stream,
1938 demux_sys_t *p_sys = p_demux->p_sys;
1939 avi_track_t *p_stream = p_sys->track[i_stream];
1941 if( ( p_stream->idx.i_size > 0 )
1942 &&( i_byte < p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_lengthtotal +
1943 p_stream->idx.p_entry[p_stream->idx.i_size - 1].i_length ) )
1945 /* index is valid to find the ck */
1946 /* uses dichototmie to be fast enougth */
1947 int i_idxposc = __MIN( p_stream->i_idxposc, p_stream->idx.i_size - 1 );
1948 int i_idxmax = p_stream->idx.i_size;
1952 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal > i_byte )
1954 i_idxmax = i_idxposc ;
1955 i_idxposc = ( i_idxmin + i_idxposc ) / 2 ;
1959 if( p_stream->idx.p_entry[i_idxposc].i_lengthtotal +
1960 p_stream->idx.p_entry[i_idxposc].i_length <= i_byte)
1962 i_idxmin = i_idxposc ;
1963 i_idxposc = (i_idxmax + i_idxposc ) / 2 ;
1967 p_stream->i_idxposc = i_idxposc;
1968 p_stream->i_idxposb = i_byte -
1969 p_stream->idx.p_entry[i_idxposc].i_lengthtotal;
1978 p_stream->i_idxposc = p_stream->idx.i_size - 1;
1979 p_stream->i_idxposb = 0;
1982 p_stream->i_idxposc++;
1983 if( AVI_StreamChunkFind( p_demux, i_stream ) )
1985 return VLC_EGENERIC;
1988 } while( p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal +
1989 p_stream->idx.p_entry[p_stream->i_idxposc].i_length <= i_byte );
1991 p_stream->i_idxposb = i_byte -
1992 p_stream->idx.p_entry[p_stream->i_idxposc].i_lengthtotal;
1997 static int AVI_TrackSeek( demux_t *p_demux,
2001 demux_sys_t *p_sys = p_demux->p_sys;
2002 avi_track_t *tk = p_sys->track[i_stream];
2004 #define p_stream p_sys->track[i_stream]
2007 i_oldpts = AVI_GetPTS( p_stream );
2009 if( !p_stream->i_samplesize )
2011 if( AVI_StreamChunkSet( p_demux,
2013 AVI_PTSToChunk( p_stream, i_date ) ) )
2015 return VLC_EGENERIC;
2018 if( p_stream->fmt.i_cat == AUDIO_ES )
2022 for( i = 0; i < tk->i_idxposc; i++ )
2024 if( tk->i_blocksize > 0 )
2026 tk->i_blockno += ( tk->idx.p_entry[i].i_length + tk->i_blocksize - 1 ) / tk->i_blocksize;
2036 "old:%"PRId64" %s new %"PRId64,
2038 i_oldpts > i_date ? ">" : "<",
2041 if( p_stream->fmt.i_cat == VIDEO_ES )
2043 /* search key frame */
2044 //if( i_date < i_oldpts || 1 )
2046 while( p_stream->i_idxposc > 0 &&
2047 !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
2050 if( AVI_StreamChunkSet( p_demux,
2052 p_stream->i_idxposc - 1 ) )
2054 return VLC_EGENERIC;
2061 while( p_stream->i_idxposc < p_stream->idx.i_size &&
2062 !( p_stream->idx.p_entry[p_stream->i_idxposc].i_flags &
2065 if( AVI_StreamChunkSet( p_demux,
2067 p_stream->i_idxposc + 1 ) )
2069 return VLC_EGENERIC;
2078 if( AVI_StreamBytesSet( p_demux,
2080 AVI_PTSToByte( p_stream, i_date ) ) )
2082 return VLC_EGENERIC;
2089 /****************************************************************************
2090 * Return true if it's a key frame
2091 ****************************************************************************/
2092 static int AVI_GetKeyFlag( vlc_fourcc_t i_fourcc, uint8_t *p_byte )
2096 case VLC_CODEC_DIV1:
2098 * startcode: 0x00000100 32bits
2099 * framenumber ? 5bits
2100 * piture type 0(I),1(P) 2bits
2102 if( GetDWBE( p_byte ) != 0x00000100 )
2104 /* it's not an msmpegv1 stream, strange...*/
2105 return AVIIF_KEYFRAME;
2107 return p_byte[4] & 0x06 ? 0 : AVIIF_KEYFRAME;
2109 case VLC_CODEC_DIV2:
2110 case VLC_CODEC_DIV3:
2111 case VLC_CODEC_WMV1:
2113 * picture type 0(I),1(P) 2bits
2115 return p_byte[0] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2116 case VLC_CODEC_MP4V:
2117 /* we should find first occurrence of 0x000001b6 (32bits)
2118 * startcode: 0x000001b6 32bits
2119 * piture type 0(I),1(P) 2bits
2121 if( GetDWBE( p_byte ) != 0x000001b6 )
2123 /* not true , need to find the first VOP header */
2124 return AVIIF_KEYFRAME;
2126 return p_byte[4] & 0xC0 ? 0 : AVIIF_KEYFRAME;
2129 /* I can't do it, so say yes */
2130 return AVIIF_KEYFRAME;
2134 vlc_fourcc_t AVI_FourccGetCodec( unsigned int i_cat, vlc_fourcc_t i_codec )
2139 wf_tag_to_fourcc( i_codec, &i_codec, NULL );
2142 return vlc_fourcc_GetCodec( i_cat, i_codec );
2144 return VLC_CODEC_UNKNOWN;
2148 /****************************************************************************
2150 ****************************************************************************/
2151 static void AVI_ParseStreamHeader( vlc_fourcc_t i_id,
2152 unsigned int *pi_number,
2153 enum es_format_category_e *pi_type )
2157 c1 = ((uint8_t *)&i_id)[0];
2158 c2 = ((uint8_t *)&i_id)[1];
2160 if( c1 < '0' || c1 > '9' || c2 < '0' || c2 > '9' )
2162 *pi_number = 100; /* > max stream number */
2163 *pi_type = UNKNOWN_ES;
2167 *pi_number = (c1 - '0') * 10 + (c2 - '0' );
2168 switch( VLC_TWOCC( ((uint8_t *)&i_id)[2], ((uint8_t *)&i_id)[3] ) )
2171 *pi_type = AUDIO_ES;
2176 *pi_type = VIDEO_ES;
2183 *pi_type = IGNORE_ES;
2186 *pi_type = UNKNOWN_ES;
2192 /****************************************************************************
2194 ****************************************************************************/
2195 static int AVI_PacketGetHeader( demux_t *p_demux, avi_packet_t *p_pk )
2197 const uint8_t *p_peek;
2199 if( vlc_stream_Peek( p_demux->s, &p_peek, 16 ) < 16 )
2201 return VLC_EGENERIC;
2203 p_pk->i_fourcc = VLC_FOURCC( p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
2204 p_pk->i_size = GetDWLE( p_peek + 4 );
2205 p_pk->i_pos = vlc_stream_Tell( p_demux->s );
2206 if( p_pk->i_fourcc == AVIFOURCC_LIST || p_pk->i_fourcc == AVIFOURCC_RIFF )
2208 p_pk->i_type = VLC_FOURCC( p_peek[8], p_peek[9],
2209 p_peek[10], p_peek[11] );
2216 memcpy( p_pk->i_peek, p_peek + 8, 8 );
2218 AVI_ParseStreamHeader( p_pk->i_fourcc, &p_pk->i_stream, &p_pk->i_cat );
2222 static int AVI_PacketNext( demux_t *p_demux )
2224 avi_packet_t avi_ck;
2227 if( AVI_PacketGetHeader( p_demux, &avi_ck ) )
2229 return VLC_EGENERIC;
2232 if( avi_ck.i_fourcc == AVIFOURCC_LIST &&
2233 ( avi_ck.i_type == AVIFOURCC_rec || avi_ck.i_type == AVIFOURCC_movi ) )
2237 else if( avi_ck.i_fourcc == AVIFOURCC_RIFF &&
2238 avi_ck.i_type == AVIFOURCC_AVIX )
2244 if( avi_ck.i_size > UINT32_MAX - 9 )
2245 return VLC_EGENERIC;
2246 i_skip = __EVEN( avi_ck.i_size ) + 8;
2249 if( i_skip > SSIZE_MAX )
2250 return VLC_EGENERIC;
2252 ssize_t i_ret = vlc_stream_Read( p_demux->s, NULL, i_skip );
2253 if( i_ret < 0 || (size_t) i_ret != i_skip )
2255 return VLC_EGENERIC;
2260 static int AVI_PacketSearch( demux_t *p_demux )
2262 demux_sys_t *p_sys = p_demux->p_sys;
2263 avi_packet_t avi_pk;
2268 if( vlc_stream_Read( p_demux->s, NULL, 1 ) != 1 )
2270 return VLC_EGENERIC;
2272 AVI_PacketGetHeader( p_demux, &avi_pk );
2273 if( avi_pk.i_stream < p_sys->i_track &&
2274 ( avi_pk.i_cat == AUDIO_ES || avi_pk.i_cat == VIDEO_ES ) )
2278 switch( avi_pk.i_fourcc )
2280 case AVIFOURCC_JUNK:
2281 case AVIFOURCC_LIST:
2282 case AVIFOURCC_RIFF:
2283 case AVIFOURCC_idx1:
2287 /* Prevents from eating all the CPU with broken files.
2288 * This value should be low enough so that it doesn't affect the
2289 * reading speed too much (not that we care much anyway because
2290 * this code is called only on broken files). */
2291 if( !(++i_count % 1024) )
2294 if( !(i_count % (1024 * 10)) )
2295 msg_Warn( p_demux, "trying to resync..." );
2300 /****************************************************************************
2302 ****************************************************************************/
2303 static void avi_index_Init( avi_index_t *p_index )
2305 p_index->i_size = 0;
2307 p_index->p_entry = NULL;
2309 static void avi_index_Clean( avi_index_t *p_index )
2311 free( p_index->p_entry );
2313 static void avi_index_Append( avi_index_t *p_index, off_t *pi_last_pos,
2314 avi_entry_t *p_entry )
2316 /* Update last chunk position */
2317 if( *pi_last_pos < p_entry->i_pos )
2318 *pi_last_pos = p_entry->i_pos;
2321 if( p_index->i_size >= p_index->i_max )
2323 p_index->i_max += 16384;
2324 p_index->p_entry = realloc_or_free( p_index->p_entry,
2325 p_index->i_max * sizeof( *p_index->p_entry ) );
2326 if( !p_index->p_entry )
2329 /* calculate cumulate length */
2330 if( p_index->i_size > 0 )
2332 p_entry->i_lengthtotal =
2333 p_index->p_entry[p_index->i_size - 1].i_length +
2334 p_index->p_entry[p_index->i_size - 1].i_lengthtotal;
2338 p_entry->i_lengthtotal = 0;
2341 p_index->p_entry[p_index->i_size++] = *p_entry;
2344 static int AVI_IndexFind_idx1( demux_t *p_demux,
2345 avi_chunk_idx1_t **pp_idx1,
2346 uint64_t *pi_offset )
2348 demux_sys_t *p_sys = p_demux->p_sys;
2350 avi_chunk_list_t *p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2351 avi_chunk_idx1_t *p_idx1 = AVI_ChunkFind( p_riff, AVIFOURCC_idx1, 0);
2355 msg_Warn( p_demux, "cannot find idx1 chunk, no index defined" );
2356 return VLC_EGENERIC;
2360 /* The offset in the index should be from the start of the movi content,
2361 * but some broken files use offset from the start of the file. Just
2362 * checking the offset of the first packet is not enough as some files
2363 * has unused chunk at the beginning of the movi content.
2365 avi_chunk_list_t *p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2366 uint64_t i_first_pos = UINT64_MAX;
2367 for( unsigned i = 0; i < __MIN( p_idx1->i_entry_count, 100 ); i++ )
2369 if ( p_idx1->entry[i].i_length > 0 )
2370 i_first_pos = __MIN( i_first_pos, p_idx1->entry[i].i_pos );
2373 const uint64_t i_movi_content = p_movi->i_chunk_pos + 8;
2374 if( i_first_pos < i_movi_content )
2376 *pi_offset = i_movi_content;
2378 else if( p_sys->b_seekable && i_first_pos < UINT64_MAX )
2380 const uint8_t *p_peek;
2381 if( !vlc_stream_Seek( p_demux->s, i_movi_content + i_first_pos ) &&
2382 vlc_stream_Peek( p_demux->s, &p_peek, 4 ) >= 4 &&
2383 ( !isdigit( p_peek[0] ) || !isdigit( p_peek[1] ) ||
2384 !isalpha( p_peek[2] ) || !isalpha( p_peek[3] ) ) )
2387 *pi_offset = i_movi_content;
2389 if( p_idx1->i_entry_count )
2391 /* Invalidate offset if index refers past the data section to avoid false
2392 positives when the offset equals sample size */
2393 size_t i_dataend = *pi_offset + p_idx1->entry[p_idx1->i_entry_count - 1].i_pos +
2394 p_idx1->entry[p_idx1->i_entry_count - 1].i_length;
2395 if( i_dataend > p_movi->i_chunk_pos + p_movi->i_chunk_size )
2407 static int AVI_IndexLoad_idx1( demux_t *p_demux,
2408 avi_index_t p_index[], off_t *pi_last_offset )
2410 demux_sys_t *p_sys = p_demux->p_sys;
2412 avi_chunk_idx1_t *p_idx1;
2414 if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2415 return VLC_EGENERIC;
2417 p_sys->b_indexloaded = true;
2419 for( unsigned i_index = 0; i_index < p_idx1->i_entry_count; i_index++ )
2421 enum es_format_category_e i_cat;
2424 AVI_ParseStreamHeader( p_idx1->entry[i_index].i_fourcc,
2427 if( i_stream < p_sys->i_track &&
2428 (i_cat == p_sys->track[i_stream]->fmt.i_cat || i_cat == UNKNOWN_ES ) )
2431 index.i_id = p_idx1->entry[i_index].i_fourcc;
2432 index.i_flags = p_idx1->entry[i_index].i_flags&(~AVIIF_FIXKEYFRAME);
2433 index.i_pos = p_idx1->entry[i_index].i_pos + i_offset;
2434 index.i_length = p_idx1->entry[i_index].i_length;
2435 index.i_lengthtotal = index.i_length;
2437 avi_index_Append( &p_index[i_stream], pi_last_offset, &index );
2442 for( unsigned i_index = 0; i_index< p_idx1->i_entry_count && i_index < p_sys->i_track; i_index++ )
2444 for( unsigned i = 0; i < p_index[i_index].i_size; i++ )
2447 if( p_sys->track[i_index]->i_samplesize )
2449 i_length = AVI_GetDPTS( p_sys->track[i_index],
2450 p_index[i_index].p_entry[i].i_lengthtotal );
2454 i_length = AVI_GetDPTS( p_sys->track[i_index], i );
2456 msg_Dbg( p_demux, "index stream %d @%ld time %ld", i_index,
2457 p_index[i_index].p_entry[i].i_pos, i_length );
2464 static void __Parse_indx( demux_t *p_demux, avi_index_t *p_index, off_t *pi_max_offset,
2465 avi_chunk_indx_t *p_indx )
2469 p_demux->p_sys->b_indexloaded = true;
2471 msg_Dbg( p_demux, "loading subindex(0x%x) %d entries", p_indx->i_indextype, p_indx->i_entriesinuse );
2472 if( p_indx->i_indexsubtype == 0 )
2474 for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2476 index.i_id = p_indx->i_id;
2477 index.i_flags = p_indx->idx.std[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2478 index.i_pos = p_indx->i_baseoffset + p_indx->idx.std[i].i_offset - 8;
2479 index.i_length = p_indx->idx.std[i].i_size&0x7fffffff;
2480 index.i_lengthtotal = index.i_length;
2482 avi_index_Append( p_index, pi_max_offset, &index );
2485 else if( p_indx->i_indexsubtype == AVI_INDEX_2FIELD )
2487 for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2489 index.i_id = p_indx->i_id;
2490 index.i_flags = p_indx->idx.field[i].i_size & 0x80000000 ? 0 : AVIIF_KEYFRAME;
2491 index.i_pos = p_indx->i_baseoffset + p_indx->idx.field[i].i_offset - 8;
2492 index.i_length = p_indx->idx.field[i].i_size;
2493 index.i_lengthtotal = index.i_length;
2495 avi_index_Append( p_index, pi_max_offset, &index );
2500 msg_Warn( p_demux, "unknown subtype index(0x%x)", p_indx->i_indexsubtype );
2504 static void AVI_IndexLoad_indx( demux_t *p_demux,
2505 avi_index_t p_index[], off_t *pi_last_offset )
2507 demux_sys_t *p_sys = p_demux->p_sys;
2509 avi_chunk_list_t *p_riff;
2510 avi_chunk_list_t *p_hdrl;
2512 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2513 p_hdrl = AVI_ChunkFind( p_riff, AVIFOURCC_hdrl, 0 );
2515 for( unsigned i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2517 avi_chunk_list_t *p_strl;
2518 avi_chunk_indx_t *p_indx;
2520 #define p_stream p_sys->track[i_stream]
2521 p_strl = AVI_ChunkFind( p_hdrl, AVIFOURCC_strl, i_stream );
2522 p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2527 msg_Warn( p_demux, "cannot find indx (misdetect/broken OpenDML "
2532 if( p_indx->i_indextype == AVI_INDEX_OF_CHUNKS )
2534 __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, p_indx );
2536 else if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES )
2538 if ( !p_sys->b_seekable )
2541 for( unsigned i = 0; i < p_indx->i_entriesinuse; i++ )
2543 if( vlc_stream_Seek( p_demux->s,
2544 p_indx->idx.super[i].i_offset ) ||
2545 AVI_ChunkRead( p_demux->s, &ck_sub, NULL ) )
2549 if( ck_sub.indx.i_indextype == AVI_INDEX_OF_CHUNKS )
2550 __Parse_indx( p_demux, &p_index[i_stream], pi_last_offset, &ck_sub.indx );
2551 AVI_ChunkClean( p_demux->s, &ck_sub );
2556 msg_Warn( p_demux, "unknown type index(0x%x)", p_indx->i_indextype );
2562 static void AVI_IndexLoad( demux_t *p_demux )
2564 demux_sys_t *p_sys = p_demux->p_sys;
2567 assert( p_sys->i_track <= 100 );
2568 avi_index_t p_idx_indx[p_sys->i_track];
2569 avi_index_t p_idx_idx1[p_sys->i_track];
2570 for( unsigned i = 0; i < p_sys->i_track; i++ )
2572 avi_index_Init( &p_idx_indx[i] );
2573 avi_index_Init( &p_idx_idx1[i] );
2575 off_t i_indx_last_pos = p_sys->i_movi_lastchunk_pos;
2576 off_t i_idx1_last_pos = p_sys->i_movi_lastchunk_pos;
2578 AVI_IndexLoad_indx( p_demux, p_idx_indx, &i_indx_last_pos );
2579 if( !p_sys->b_odml )
2580 AVI_IndexLoad_idx1( p_demux, p_idx_idx1, &i_idx1_last_pos );
2582 /* Select the longest index */
2583 for( unsigned i = 0; i < p_sys->i_track; i++ )
2585 if( p_idx_indx[i].i_size > p_idx_idx1[i].i_size )
2587 msg_Dbg( p_demux, "selected ODML index for stream[%u]", i );
2588 p_sys->track[i]->idx = p_idx_indx[i];
2589 avi_index_Clean( &p_idx_idx1[i] );
2593 msg_Dbg( p_demux, "selected standard index for stream[%u]", i );
2594 p_sys->track[i]->idx = p_idx_idx1[i];
2595 avi_index_Clean( &p_idx_indx[i] );
2598 p_sys->i_movi_lastchunk_pos = __MAX( i_indx_last_pos, i_idx1_last_pos );
2600 for( unsigned i = 0; i < p_sys->i_track; i++ )
2602 avi_index_t *p_index = &p_sys->track[i]->idx;
2606 for( unsigned j = 0; !b_key && j < p_index->i_size; j++ )
2607 b_key = p_index->p_entry[j].i_flags & AVIIF_KEYFRAME;
2610 msg_Err( p_demux, "no key frame set for track %u", i );
2611 for( unsigned j = 0; j < p_index->i_size; j++ )
2612 p_index->p_entry[j].i_flags |= AVIIF_KEYFRAME;
2616 msg_Dbg( p_demux, "stream[%d] created %d index entries",
2617 i, p_index->i_size );
2621 static void AVI_IndexCreate( demux_t *p_demux )
2623 demux_sys_t *p_sys = p_demux->p_sys;
2625 avi_chunk_list_t *p_riff;
2626 avi_chunk_list_t *p_movi;
2628 unsigned int i_stream;
2631 mtime_t i_dialog_update;
2632 vlc_dialog_id *p_dialog_id = NULL;
2634 p_riff = AVI_ChunkFind( &p_sys->ck_root, AVIFOURCC_RIFF, 0);
2635 p_movi = AVI_ChunkFind( p_riff, AVIFOURCC_movi, 0);
2639 msg_Err( p_demux, "cannot find p_movi" );
2643 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2644 avi_index_Init( &p_sys->track[i_stream]->idx );
2646 i_movi_end = __MIN( (off_t)(p_movi->i_chunk_pos + p_movi->i_chunk_size),
2647 stream_Size( p_demux->s ) );
2649 vlc_stream_Seek( p_demux->s, p_movi->i_chunk_pos + 12 );
2650 msg_Warn( p_demux, "creating index from LIST-movi, will take time !" );
2653 /* Only show dialog if AVI is > 10MB */
2654 i_dialog_update = mdate();
2655 if( stream_Size( p_demux->s ) > 10000000 )
2658 vlc_dialog_display_progress( p_demux, false, 0.0, _("Cancel"),
2659 _("Broken or missing AVI Index"),
2660 _("Fixing AVI Index...") );
2667 /* Don't update/check dialog too often */
2668 if( p_dialog_id != NULL && mdate() - i_dialog_update > 100000 )
2670 if( vlc_dialog_is_cancelled( p_demux, p_dialog_id ) )
2673 double f_current = vlc_stream_Tell( p_demux->s );
2674 double f_size = stream_Size( p_demux->s );
2675 double f_pos = f_current / f_size;
2676 vlc_dialog_update_progress( p_demux, p_dialog_id, f_pos );
2678 i_dialog_update = mdate();
2681 if( AVI_PacketGetHeader( p_demux, &pk ) )
2684 if( pk.i_stream < p_sys->i_track &&
2685 pk.i_cat == p_sys->track[pk.i_stream]->fmt.i_cat )
2687 avi_track_t *tk = p_sys->track[pk.i_stream];
2690 index.i_id = pk.i_fourcc;
2691 index.i_flags = AVI_GetKeyFlag(tk->fmt.i_codec, pk.i_peek);
2692 index.i_pos = pk.i_pos;
2693 index.i_length = pk.i_size;
2694 index.i_lengthtotal = pk.i_size;
2695 avi_index_Append( &tk->idx, &p_sys->i_movi_lastchunk_pos, &index );
2699 switch( pk.i_fourcc )
2701 case AVIFOURCC_idx1:
2704 avi_chunk_list_t *p_sysx;
2705 p_sysx = AVI_ChunkFind( &p_sys->ck_root,
2706 AVIFOURCC_RIFF, 1 );
2708 msg_Dbg( p_demux, "looking for new RIFF chunk" );
2709 if( vlc_stream_Seek( p_demux->s,
2710 p_sysx->i_chunk_pos + 24 ) )
2716 case AVIFOURCC_RIFF:
2717 msg_Dbg( p_demux, "new RIFF chunk found" );
2721 case AVIFOURCC_JUNK:
2725 msg_Warn( p_demux, "need resync, probably broken avi" );
2726 if( AVI_PacketSearch( p_demux ) )
2728 msg_Warn( p_demux, "lost sync, abord index creation" );
2734 if( ( !p_sys->b_odml && pk.i_pos + pk.i_size >= i_movi_end ) ||
2735 AVI_PacketNext( p_demux ) )
2742 if( p_dialog_id != NULL )
2743 vlc_dialog_release( p_demux, p_dialog_id );
2745 for( i_stream = 0; i_stream < p_sys->i_track; i_stream++ )
2747 msg_Dbg( p_demux, "stream[%d] creating %d index entries",
2748 i_stream, p_sys->track[i_stream]->idx.i_size );
2753 static void AVI_MetaLoad( demux_t *p_demux,
2754 avi_chunk_list_t *p_riff, avi_chunk_avih_t *p_avih )
2756 demux_sys_t *p_sys = p_demux->p_sys;
2758 vlc_meta_t *p_meta = p_sys->meta = vlc_meta_New();
2763 snprintf( buffer, sizeof(buffer), "%s%s%s%s",
2764 p_avih->i_flags&AVIF_HASINDEX ? " HAS_INDEX" : "",
2765 p_avih->i_flags&AVIF_MUSTUSEINDEX ? " MUST_USE_INDEX" : "",
2766 p_avih->i_flags&AVIF_ISINTERLEAVED ? " IS_INTERLEAVED" : "",
2767 p_avih->i_flags&AVIF_TRUSTCKTYPE ? " TRUST_CKTYPE" : "" );
2768 vlc_meta_SetSetting( p_meta, buffer );
2770 avi_chunk_list_t *p_info = AVI_ChunkFind( p_riff, AVIFOURCC_INFO, 0 );
2774 static const struct {
2778 { AVIFOURCC_IART, vlc_meta_Artist },
2779 { AVIFOURCC_ICMT, vlc_meta_Description },
2780 { AVIFOURCC_ICOP, vlc_meta_Copyright },
2781 { AVIFOURCC_IGNR, vlc_meta_Genre },
2782 { AVIFOURCC_INAM, vlc_meta_Title },
2783 { AVIFOURCC_ICRD, vlc_meta_Date },
2784 { AVIFOURCC_ILNG, vlc_meta_Language },
2785 { AVIFOURCC_IRTD, vlc_meta_Rating },
2786 { AVIFOURCC_IWEB, vlc_meta_URL },
2787 { AVIFOURCC_IPRT, vlc_meta_TrackNumber },
2788 { AVIFOURCC_IFRM, vlc_meta_TrackTotal },
2791 for( int i = 0; p_dsc[i].i_id != 0; i++ )
2793 avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_dsc[i].i_id, 0 );
2794 if( !p_strz || !p_strz->p_str )
2796 char *psz_value = FromACP( p_strz->p_str );
2801 vlc_meta_Set( p_meta, p_dsc[i].i_type, psz_value );
2805 static const vlc_fourcc_t p_extra[] = {
2806 AVIFOURCC_IARL, AVIFOURCC_ICMS, AVIFOURCC_ICRP, AVIFOURCC_IDIM, AVIFOURCC_IDPI,
2807 AVIFOURCC_IENG, AVIFOURCC_IKEY, AVIFOURCC_ILGT, AVIFOURCC_IMED, AVIFOURCC_IPLT,
2808 AVIFOURCC_IPRD, AVIFOURCC_ISBJ, AVIFOURCC_ISFT, AVIFOURCC_ISHP, AVIFOURCC_ISRC,
2809 AVIFOURCC_ISRF, AVIFOURCC_ITCH, AVIFOURCC_ISMP, AVIFOURCC_IDIT, AVIFOURCC_ISGN,
2810 AVIFOURCC_IWRI, AVIFOURCC_IPRO, AVIFOURCC_ICNM, AVIFOURCC_IPDS, AVIFOURCC_IEDT,
2811 AVIFOURCC_ICDS, AVIFOURCC_IMUS, AVIFOURCC_ISTD, AVIFOURCC_IDST, AVIFOURCC_ICNT,
2815 for( int i = 0; p_extra[i] != 0; i++ )
2817 avi_chunk_STRING_t *p_strz = AVI_ChunkFind( p_info, p_extra[i], 0 );
2818 if( !p_strz || !p_strz->p_str )
2820 char *psz_value = FromACP( p_strz->p_str );
2825 vlc_meta_AddExtra( p_meta, p_strz->p_type, psz_value );
2830 static void AVI_DvHandleAudio( demux_t *p_demux, avi_track_t *tk, block_t *p_frame )
2832 size_t i_offset = 80 * 6 + 80 * 16 * 3 + 3;
2833 if( p_frame->i_buffer < i_offset + 5 )
2836 if( p_frame->p_buffer[i_offset] != 0x50 )
2840 dv_get_audio_format( &fmt, &p_frame->p_buffer[i_offset + 1] );
2842 if( tk->p_es_dv_audio && tk->i_dv_audio_rate != (int)fmt.audio.i_rate )
2844 es_out_Del( p_demux->out, tk->p_es_dv_audio );
2845 tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2847 else if( !tk->p_es_dv_audio )
2849 tk->p_es_dv_audio = es_out_Add( p_demux->out, &fmt );
2851 tk->i_dv_audio_rate = fmt.audio.i_rate;
2852 es_format_Clean( &fmt );
2854 block_t *p_frame_audio = dv_extract_audio( p_frame );
2857 if( tk->p_es_dv_audio )
2858 es_out_Send( p_demux->out, tk->p_es_dv_audio, p_frame_audio );
2860 block_Release( p_frame_audio );
2864 /*****************************************************************************
2866 *****************************************************************************/
2867 static void AVI_ExtractSubtitle( demux_t *p_demux,
2868 unsigned int i_stream,
2869 avi_chunk_list_t *p_strl,
2870 avi_chunk_STRING_t *p_strn )
2872 demux_sys_t *p_sys = p_demux->p_sys;
2873 block_t *p_block = NULL;
2874 input_attachment_t *p_attachment = NULL;
2875 char *psz_description = NULL;
2876 avi_chunk_indx_t *p_indx = NULL;
2878 if( !p_sys->b_seekable )
2881 p_indx = AVI_ChunkFind( p_strl, AVIFOURCC_indx, 0 );
2887 if( p_indx->i_indextype == AVI_INDEX_OF_INDEXES &&
2888 p_indx->i_entriesinuse > 0 )
2890 if( vlc_stream_Seek( p_demux->s, p_indx->idx.super[0].i_offset ) ||
2891 AVI_ChunkRead( p_demux->s, &ck, NULL ) )
2896 if( p_indx->i_indextype != AVI_INDEX_OF_CHUNKS ||
2897 p_indx->i_entriesinuse != 1 ||
2898 p_indx->i_indexsubtype != 0 )
2901 i_position = p_indx->i_baseoffset +
2902 p_indx->idx.std[0].i_offset - 8;
2903 i_size = (p_indx->idx.std[0].i_size & 0x7fffffff) + 8;
2907 avi_chunk_idx1_t *p_idx1;
2910 if( AVI_IndexFind_idx1( p_demux, &p_idx1, &i_offset ) )
2914 for( unsigned i = 0; i < p_idx1->i_entry_count; i++ )
2916 const idx1_entry_t *e = &p_idx1->entry[i];
2917 enum es_format_category_e i_cat;
2918 unsigned i_stream_idx;
2920 AVI_ParseStreamHeader( e->i_fourcc, &i_stream_idx, &i_cat );
2921 if( i_cat == SPU_ES && i_stream_idx == i_stream )
2923 i_position = e->i_pos + i_offset;
2924 i_size = e->i_length + 8;
2933 if( i_size > 10000000 )
2935 msg_Dbg( p_demux, "Attached subtitle too big: %u", i_size );
2939 if( vlc_stream_Seek( p_demux->s, i_position ) )
2941 p_block = vlc_stream_Block( p_demux->s, i_size );
2945 /* Parse packet header */
2946 const uint8_t *p = p_block->p_buffer;
2947 if( i_size < 8 || p[2] != 't' || p[3] != 'x' )
2952 /* Parse subtitle chunk header */
2953 if( i_size < 11 || memcmp( p, "GAB2", 4 ) ||
2954 p[4] != 0x00 || GetWLE( &p[5] ) != 0x2 )
2956 const unsigned i_name = GetDWLE( &p[7] );
2957 if( 11 + i_size <= i_name )
2960 psz_description = FromCharset( "UTF-16LE", &p[11], i_name );
2962 i_size -= 11 + i_name;
2963 if( i_size < 6 || GetWLE( &p[0] ) != 0x04 )
2965 const unsigned i_payload = GetDWLE( &p[2] );
2966 if( i_size < 6 + i_payload || i_payload <= 0 )
2971 if( !psz_description )
2972 psz_description = p_strn && p_strn->p_str ? FromACP( p_strn->p_str ) : NULL;
2974 if( asprintf( &psz_name, "subtitle%d.srt", p_sys->i_attachment ) <= 0 )
2976 p_attachment = vlc_input_attachment_New( psz_name,
2977 "application/x-srt",
2981 TAB_APPEND( p_sys->i_attachment, p_sys->attachment, p_attachment );
2985 free( psz_description );
2988 block_Release( p_block );
2991 msg_Dbg( p_demux, "Loaded an embedded subtitle" );
2993 msg_Warn( p_demux, "Failed to load an embedded subtitle" );
2995 if( p_indx == &ck.indx )
2996 AVI_ChunkClean( p_demux->s, &ck );
2998 /*****************************************************************************
3000 *****************************************************************************/
3001 static int AVI_TrackStopFinishedStreams( demux_t *p_demux )
3003 demux_sys_t *p_sys = p_demux->p_sys;
3007 for( i = 0; i < p_sys->i_track; i++ )
3009 avi_track_t *tk = p_sys->track[i];
3010 if( tk->i_idxposc >= tk->idx.i_size )
3022 /****************************************************************************
3023 * AVI_MovieGetLength give max streams length in second
3024 ****************************************************************************/
3025 static mtime_t AVI_MovieGetLength( demux_t *p_demux )
3027 demux_sys_t *p_sys = p_demux->p_sys;
3028 mtime_t i_maxlength = 0;
3031 for( i = 0; i < p_sys->i_track; i++ )
3033 avi_track_t *tk = p_sys->track[i];
3036 /* fix length for each stream */
3037 if( tk->idx.i_size < 1 || !tk->idx.p_entry )
3042 if( tk->i_samplesize )
3044 i_length = AVI_GetDPTS( tk,
3045 tk->idx.p_entry[tk->idx.i_size-1].i_lengthtotal +
3046 tk->idx.p_entry[tk->idx.i_size-1].i_length );
3050 i_length = AVI_GetDPTS( tk, tk->idx.i_size );
3052 i_length /= CLOCK_FREQ; /* in seconds */
3055 "stream[%d] length:%"PRId64" (based on index)",
3058 i_maxlength = __MAX( i_maxlength, i_length );