1 /*****************************************************************************
2 * matroska_segment.cpp : matroska demuxer
3 *****************************************************************************
4 * Copyright (C) 2003-2010 VLC authors and VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Steve Lhomme <steve.lhomme@free.fr>
10 * This program is free software; you can redistribute it and/or modify it
11 * under the terms of the GNU Lesser General Public License as published by
12 * the Free Software Foundation; either version 2.1 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this program; if not, write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23 *****************************************************************************/
25 #include "matroska_segment.hpp"
26 #include "chapters.hpp"
29 #include "Ebml_parser.hpp"
31 matroska_segment_c::matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
34 ,i_timescale(MKVD_TIMECODESCALE)
38 ,i_seekhead_position(-1)
40 ,i_tracks_position(-1)
42 ,i_chapters_position(-1)
44 ,i_attachments_position(-1)
50 ,p_prev_segment_uid(NULL)
51 ,p_next_segment_uid(NULL)
55 ,psz_muxing_application(NULL)
56 ,psz_writing_application(NULL)
57 ,psz_segment_filename(NULL)
64 ,b_ref_external_segments(false)
66 p_indexes = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
69 matroska_segment_c::~matroska_segment_c()
71 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
73 delete tracks[i_track]->p_compression_data;
74 es_format_Clean( &tracks[i_track]->fmt );
75 delete tracks[i_track]->p_sys;
76 free( tracks[i_track]->p_extra_data );
77 free( tracks[i_track]->psz_codec );
78 delete tracks[i_track];
81 free( psz_writing_application );
82 free( psz_muxing_application );
83 free( psz_segment_filename );
91 delete p_prev_segment_uid;
92 delete p_next_segment_uid;
94 vlc_delete_all( stored_editions );
95 vlc_delete_all( translations );
96 vlc_delete_all( families );
100 /*****************************************************************************
102 *****************************************************************************
103 * * LoadCues : load the cues element and update index
104 * * LoadTags : load ... the tags element
105 * * InformationCreate : create all information, load tags if present
106 *****************************************************************************/
107 void matroska_segment_c::LoadCues( KaxCues *cues )
115 msg_Err( &sys.demuxer, "There can be only 1 Cues per section." );
119 ep = new EbmlParser( &es, cues, &sys.demuxer );
120 while( ( el = ep->Get() ) != NULL )
122 if( MKV_IS_ID( el, KaxCuePoint ) )
124 b_invalid_cue = false;
125 #define idx p_indexes[i_index]
128 idx.i_block_number= -1;
134 while( ( el = ep->Get() ) != NULL )
136 if( MKV_IS_ID( el, KaxCueTime ) )
138 KaxCueTime &ctime = *(KaxCueTime*)el;
141 if( unlikely( ctime.GetSize() >= SIZE_MAX ) )
143 msg_Err( &sys.demuxer, "CueTime size too big");
144 b_invalid_cue = true;
147 ctime.ReadData( es.I_O() );
151 msg_Err( &sys.demuxer, "Error while reading CueTime" );
152 b_invalid_cue = true;
155 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
157 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
162 while( ( el = ep->Get() ) != NULL )
164 if( unlikely( el->GetSize() >= SIZE_MAX ) )
167 msg_Err( &sys.demuxer, "Error %s too big, aborting", typeid(*el).name() );
168 b_invalid_cue = true;
172 if( MKV_IS_ID( el, KaxCueTrack ) )
174 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
175 ctrack.ReadData( es.I_O() );
176 idx.i_track = uint16( ctrack );
178 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
180 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
182 ccpos.ReadData( es.I_O() );
183 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
185 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
187 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
189 cbnum.ReadData( es.I_O() );
190 idx.i_block_number = uint32( cbnum );
194 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
201 msg_Err( &sys.demuxer, "Error while reading %s", typeid(*el).name() );
202 b_invalid_cue = true;
209 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
215 msg_Dbg( &sys.demuxer, " * added time=%"PRId64" pos=%"PRId64
216 " track=%d bnum=%d", idx.i_time, idx.i_position,
217 idx.i_track, idx.i_block_number );
219 if( likely( !b_invalid_cue ) )
222 if( i_index >= i_index_max )
225 p_indexes = (mkv_index_t*)xrealloc( p_indexes,
226 sizeof( mkv_index_t ) * i_index_max );
233 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
238 msg_Dbg( &sys.demuxer, "| - loading cues done." );
242 static const struct {
243 vlc_meta_type_t type;
245 int target_type; /* 0 is valid for all target_type */
247 {vlc_meta_Album, "TITLE", 50},
248 {vlc_meta_Title, "TITLE", 0},
249 {vlc_meta_Artist, "ARTIST", 0},
250 {vlc_meta_Genre, "GENRE", 0},
251 {vlc_meta_Copyright, "COPYRIGHT", 0},
252 {vlc_meta_TrackNumber, "PART_NUMBER", 0},
253 {vlc_meta_Description, "DESCRIPTION", 0},
254 {vlc_meta_Description, "COMMENT", 0},
255 {vlc_meta_Rating, "RATING", 0},
256 {vlc_meta_Date, "DATE_RELEASED", 0},
257 {vlc_meta_Date, "DATE_RELEASE", 0},
258 {vlc_meta_Date, "DATE_RECORDED", 0},
259 {vlc_meta_URL, "URL", 0},
260 {vlc_meta_Publisher, "PUBLISHER", 0},
261 {vlc_meta_EncodedBy, "ENCODED_BY", 0},
262 {vlc_meta_TrackTotal, "TOTAL_PARTS", 0},
263 {vlc_meta_Title, NULL, 0},
266 SimpleTag * matroska_segment_c::ParseSimpleTags( KaxTagSimple *tag, int target_type )
269 EbmlParser *ep = new EbmlParser( &es, tag, &sys.demuxer );
270 SimpleTag * p_simple = new SimpleTag;
274 msg_Err( &sys.demuxer, "Couldn't allocate memory for Simple Tag... ignoring it");
279 sys.meta = vlc_meta_New();
281 msg_Dbg( &sys.demuxer, "| + Simple Tag ");
284 while( ( el = ep->Get() ) != NULL )
286 if( unlikely( el->GetSize() >= SIZE_MAX ) )
288 msg_Err( &sys.demuxer, "Error %s too big ignoring the tag", typeid(*el).name() );
293 if( MKV_IS_ID( el, KaxTagName ) )
295 KaxTagName &key = *(KaxTagName*)el;
296 key.ReadData( es.I_O(), SCOPE_ALL_DATA );
297 p_simple->psz_tag_name = strdup( UTFstring( key ).GetUTF8().c_str() );
299 else if( MKV_IS_ID( el, KaxTagString ) )
301 KaxTagString &value = *(KaxTagString*)el;
302 value.ReadData( es.I_O(), SCOPE_ALL_DATA );
303 p_simple->p_value = strdup( UTFstring( value ).GetUTF8().c_str() );
305 else if( MKV_IS_ID( el, KaxTagLangue ) )
307 KaxTagLangue &language = *(KaxTagLangue*) el;
308 language.ReadData( es.I_O(), SCOPE_ALL_DATA );
309 p_simple->psz_lang = strdup( string( language ).c_str());
311 else if( MKV_IS_ID( el, KaxTagDefault ) )
313 KaxTagDefault & dft = *(KaxTagDefault*) el;
314 dft.ReadData( es.I_O(), SCOPE_ALL_DATA );
315 p_simple->b_default = (bool) uint8( dft );
317 /*Tags can be nested*/
318 else if( MKV_IS_ID( el, KaxTagSimple) )
320 SimpleTag * p_st = ParseSimpleTags( (KaxTagSimple*)el, target_type );
322 p_simple->sub_tags.push_back( p_st );
324 /*TODO Handle binary tags*/
329 msg_Err( &sys.demuxer, "Error while reading Tag ");
336 if( !p_simple->psz_tag_name || !p_simple->p_value )
338 msg_Warn( &sys.demuxer, "Invalid MKV SimpleTag found.");
343 for( int i = 0; metadata_map[i].key; i++ )
345 if( !strcmp( p_simple->psz_tag_name, metadata_map[i].key ) &&
346 (metadata_map[i].target_type == 0 || target_type == metadata_map[i].target_type ) )
348 vlc_meta_Set( sys.meta, metadata_map[i].type, p_simple->p_value );
349 msg_Dbg( &sys.demuxer, "| | + Meta %s: %s", p_simple->psz_tag_name, p_simple->p_value);
353 msg_Dbg( &sys.demuxer, "| | + Meta %s: %s", p_simple->psz_tag_name, p_simple->p_value);
354 vlc_meta_AddExtra( sys.meta, p_simple->psz_tag_name, p_simple->p_value);
359 #define PARSE_TAG( type ) \
361 msg_Dbg( &sys.demuxer, "| + " type ); \
363 while( ( el = ep->Get() ) != NULL ) \
365 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() ); \
367 ep->Up(); } while( 0 )
370 void matroska_segment_c::LoadTags( KaxTags *tags )
372 /* Master elements */
373 EbmlParser *ep = new EbmlParser( &es, tags, &sys.demuxer );
376 while( ( el = ep->Get() ) != NULL )
378 if( MKV_IS_ID( el, KaxTag ) )
380 Tag * p_tag = new Tag;
383 msg_Err( &sys.demuxer,"Couldn't allocate memory for tag... ignoring it");
386 msg_Dbg( &sys.demuxer, "+ Tag" );
388 int target_type = 50;
389 while( ( el = ep->Get() ) != NULL )
391 if( MKV_IS_ID( el, KaxTagTargets ) )
393 msg_Dbg( &sys.demuxer, "| + Targets" );
395 while( ( el = ep->Get() ) != NULL )
399 if( unlikely( el->GetSize() >= SIZE_MAX ) )
401 msg_Err( &sys.demuxer, "Invalid size while reading tag");
404 if( MKV_IS_ID( el, KaxTagTargetTypeValue ) )
406 KaxTagTargetTypeValue &value = *(KaxTagTargetTypeValue*)el;
407 value.ReadData( es.I_O() );
409 msg_Dbg( &sys.demuxer, "| | + TargetTypeValue: %u", uint32(value));
410 target_type = uint32(value);
412 if( MKV_IS_ID( el, KaxTagTrackUID ) )
414 p_tag->i_tag_type = TRACK_UID;
415 KaxTagTrackUID &uid = *(KaxTagTrackUID*) el;
416 uid.ReadData( es.I_O() );
417 p_tag->i_uid = uint64( uid );
418 msg_Dbg( &sys.demuxer, "| | + TrackUID: %"PRIu64, p_tag->i_uid);
421 if( MKV_IS_ID( el, KaxTagEditionUID ) )
423 p_tag->i_tag_type = EDITION_UID;
424 KaxTagEditionUID &uid = *(KaxTagEditionUID*) el;
425 uid.ReadData( es.I_O() );
426 p_tag->i_uid = uint64( uid );
427 msg_Dbg( &sys.demuxer, "| | + EditionUID: %"PRIu64, p_tag->i_uid);
429 if( MKV_IS_ID( el, KaxTagChapterUID ) )
431 p_tag->i_tag_type = CHAPTER_UID;
432 KaxTagChapterUID &uid = *(KaxTagChapterUID*) el;
433 uid.ReadData( es.I_O() );
434 p_tag->i_uid = uint64( uid );
435 msg_Dbg( &sys.demuxer, "| | + ChapterUID: %"PRIu64, p_tag->i_uid);
437 if( MKV_IS_ID( el, KaxTagAttachmentUID ) )
439 p_tag->i_tag_type = ATTACHMENT_UID;
440 KaxTagAttachmentUID &uid = *(KaxTagAttachmentUID*) el;
441 uid.ReadData( es.I_O() );
442 p_tag->i_uid = uint64( uid );
443 msg_Dbg( &sys.demuxer, "| | + AttachmentUID: %"PRIu64, p_tag->i_uid);
448 msg_Err( &sys.demuxer, "Error while reading tag");
454 else if( MKV_IS_ID( el, KaxTagSimple ) )
456 SimpleTag * p_simple =
457 ParseSimpleTags( static_cast<KaxTagSimple*>( el ),
460 p_tag->simple_tags.push_back( p_simple );
462 #if 0 // not valid anymore
463 else if( MKV_IS_ID( el, KaxTagGeneral ) )
464 PARSE_TAG( "General" );
465 else if( MKV_IS_ID( el, KaxTagGenres ) )
466 PARSE_TAG( "Genres" );
467 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
468 PARSE_TAG( "Audio Specific" );
469 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
470 PARSE_TAG( "Images Specific" );
471 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
473 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
475 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
477 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
479 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
481 msg_Dbg( &sys.demuxer, "| + Multi Date" );
483 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
485 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
487 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
489 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
491 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
493 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
495 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
497 msg_Dbg( &sys.demuxer, "| + Multi Title" );
502 msg_Dbg( &sys.demuxer, "| + LoadTag Unknown (%s)", typeid( *el ).name() );
506 this->tags.push_back(p_tag);
510 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
515 msg_Dbg( &sys.demuxer, "loading tags done." );
519 /*****************************************************************************
521 *****************************************************************************/
522 void matroska_segment_c::InformationCreate( )
525 sys.meta = vlc_meta_New();
529 vlc_meta_SetTitle( sys.meta, psz_title );
534 vlc_meta_SetDate( sys.meta, psz_date_utc );
537 if( psz_segment_filename )
539 fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
541 if( psz_muxing_application )
543 fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
545 if( psz_writing_application )
547 fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
550 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
552 // mkv_track_t *tk = tracks[i_track];
553 // vlc_meta_t *mtk = vlc_meta_New();
554 fprintf( stderr, "***** WARNING: Unhandled child meta\n");
558 if( i_tags_position >= 0 )
562 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
572 /*****************************************************************************
574 *****************************************************************************/
576 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
578 #define idx p_indexes[i_index]
580 idx.i_block_number= -1;
581 idx.i_position = cluster->GetElementPosition();
582 idx.i_time = cluster->GlobalTimecode()/ (mtime_t) 1000;
586 if( i_index >= i_index_max )
589 p_indexes = (mkv_index_t*)xrealloc( p_indexes,
590 sizeof( mkv_index_t ) * i_index_max );
595 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
600 for (size_t i=0; i<families.size(); i++)
602 for (size_t j=0; j<of_segment.families.size(); j++)
604 if ( *(families[i]) == *(of_segment.families[j]) )
612 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
616 if ( p_item_a == NULL || p_item_b == NULL )
619 p_tmp = (EbmlBinary *)p_item_a->p_segment_uid;
620 if ( p_item_b->p_prev_segment_uid != NULL
621 && *p_tmp == *p_item_b->p_prev_segment_uid )
624 p_tmp = (EbmlBinary *)p_item_a->p_next_segment_uid;
628 if ( p_item_b->p_segment_uid != NULL
629 && *p_tmp == *p_item_b->p_segment_uid )
632 if ( p_item_b->p_prev_segment_uid != NULL
633 && *p_tmp == *p_item_b->p_prev_segment_uid )
639 bool matroska_segment_c::Preload( )
644 EbmlElement *el = NULL;
646 ep->Reset( &sys.demuxer );
648 while( ( el = ep->Get() ) != NULL )
650 if( MKV_IS_ID( el, KaxSeekHead ) )
652 /* Multiple allowed */
653 /* We bail at 10, to prevent possible recursion */
654 msg_Dbg( &sys.demuxer, "| + Seek head" );
655 if( i_seekhead_count < 10 )
657 i_seekhead_position = (int64_t) es.I_O().getFilePointer();
658 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
661 else if( MKV_IS_ID( el, KaxInfo ) )
663 /* Multiple allowed, mandatory */
664 msg_Dbg( &sys.demuxer, "| + Information" );
665 if( i_info_position < 0 ) // FIXME
666 ParseInfo( static_cast<KaxInfo*>( el ) );
667 i_info_position = (int64_t) es.I_O().getFilePointer();
669 else if( MKV_IS_ID( el, KaxTracks ) )
671 /* Multiple allowed */
672 msg_Dbg( &sys.demuxer, "| + Tracks" );
673 if( i_tracks_position < 0 ) // FIXME
674 ParseTracks( static_cast<KaxTracks*>( el ) );
675 if ( tracks.size() == 0 )
677 msg_Err( &sys.demuxer, "No tracks supported" );
680 i_tracks_position = (int64_t) es.I_O().getFilePointer();
682 else if( MKV_IS_ID( el, KaxCues ) )
684 msg_Dbg( &sys.demuxer, "| + Cues" );
685 if( i_cues_position < 0 )
686 LoadCues( static_cast<KaxCues*>( el ) );
687 i_cues_position = (int64_t) es.I_O().getFilePointer();
689 else if( MKV_IS_ID( el, KaxCluster ) )
691 msg_Dbg( &sys.demuxer, "| + Cluster" );
693 cluster = (KaxCluster*)el;
695 i_cluster_pos = i_start_pos = cluster->GetElementPosition();
699 /* stop pre-parsing the stream */
702 else if( MKV_IS_ID( el, KaxAttachments ) )
704 msg_Dbg( &sys.demuxer, "| + Attachments" );
705 if( i_attachments_position < 0 )
706 ParseAttachments( static_cast<KaxAttachments*>( el ) );
707 i_attachments_position = (int64_t) es.I_O().getFilePointer();
709 else if( MKV_IS_ID( el, KaxChapters ) )
711 msg_Dbg( &sys.demuxer, "| + Chapters" );
712 if( i_chapters_position < 0 )
713 ParseChapters( static_cast<KaxChapters*>( el ) );
714 i_chapters_position = (int64_t) es.I_O().getFilePointer();
716 else if( MKV_IS_ID( el, KaxTag ) )
718 msg_Dbg( &sys.demuxer, "| + Tags" );
719 /*FIXME if( i_tags_position < 0)
720 LoadTags( static_cast<KaxTags*>( el ) );*/
721 i_tags_position = (int64_t) es.I_O().getFilePointer();
723 else if( MKV_IS_ID( el, EbmlVoid ) )
724 msg_Dbg( &sys.demuxer, "| + Void" );
726 msg_Dbg( &sys.demuxer, "| + Preload Unknown (%s)", typeid(*el).name() );
729 ComputeTrackPriority();
736 /* Here we try to load elements that were found in Seek Heads, but not yet parsed */
737 bool matroska_segment_c::LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position )
739 int64_t i_sav_position = (int64_t)es.I_O().getFilePointer();
742 es.I_O().setFilePointer( i_element_position, seek_beginning );
743 el = es.FindNextID( ClassInfos, 0xFFFFFFFFL);
747 msg_Err( &sys.demuxer, "cannot load some cues/chapters/tags etc. (broken seekhead or file)" );
748 es.I_O().setFilePointer( i_sav_position, seek_beginning );
752 if( MKV_IS_ID( el, KaxSeekHead ) )
754 /* Multiple allowed */
755 msg_Dbg( &sys.demuxer, "| + Seek head" );
756 if( i_seekhead_count < 10 )
758 i_seekhead_position = i_element_position;
759 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
762 else if( MKV_IS_ID( el, KaxInfo ) ) // FIXME
764 /* Multiple allowed, mandatory */
765 msg_Dbg( &sys.demuxer, "| + Information" );
766 if( i_info_position < 0 )
767 ParseInfo( static_cast<KaxInfo*>( el ) );
768 i_info_position = i_element_position;
770 else if( MKV_IS_ID( el, KaxTracks ) ) // FIXME
772 /* Multiple allowed */
773 msg_Dbg( &sys.demuxer, "| + Tracks" );
774 if( i_tracks_position < 0 )
775 ParseTracks( static_cast<KaxTracks*>( el ) );
776 if ( tracks.size() == 0 )
778 msg_Err( &sys.demuxer, "No tracks supported" );
780 es.I_O().setFilePointer( i_sav_position, seek_beginning );
783 i_tracks_position = i_element_position;
785 else if( MKV_IS_ID( el, KaxCues ) )
787 msg_Dbg( &sys.demuxer, "| + Cues" );
788 if( i_cues_position < 0 )
789 LoadCues( static_cast<KaxCues*>( el ) );
790 i_cues_position = i_element_position;
792 else if( MKV_IS_ID( el, KaxAttachments ) )
794 msg_Dbg( &sys.demuxer, "| + Attachments" );
795 if( i_attachments_position < 0 )
796 ParseAttachments( static_cast<KaxAttachments*>( el ) );
797 i_attachments_position = i_element_position;
799 else if( MKV_IS_ID( el, KaxChapters ) )
801 msg_Dbg( &sys.demuxer, "| + Chapters" );
802 if( i_chapters_position < 0 )
803 ParseChapters( static_cast<KaxChapters*>( el ) );
804 i_chapters_position = i_element_position;
806 else if( MKV_IS_ID( el, KaxTags ) )
808 msg_Dbg( &sys.demuxer, "| + Tags" );
809 if( i_tags_position < 0 )
810 LoadTags( static_cast<KaxTags*>( el ) );
811 i_tags_position = i_element_position;
815 msg_Dbg( &sys.demuxer, "| + LoadSeekHeadItem Unknown (%s)", typeid(*el).name() );
819 es.I_O().setFilePointer( i_sav_position, seek_beginning );
825 spoint(unsigned int tk, mtime_t date, int64_t pos, int64_t cpos):
826 i_track(tk),i_date(date), i_seek_pos(pos),
827 i_cluster_pos(cpos), p_next(NULL){}
828 unsigned int i_track;
831 int64_t i_cluster_pos;
835 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position )
838 KaxSimpleBlock *simpleblock;
839 int64_t i_block_duration;
841 int64_t i_seek_position = i_start_pos;
842 int64_t i_seek_time = i_start_time;
844 spoint *p_first = NULL;
845 spoint *p_last = NULL;
847 bool b_has_key = false;
849 for( size_t i = 0; i < tracks.size(); i++)
850 tracks[i]->i_last_dts = VLC_TS_INVALID;
852 if( i_global_position >= 0 )
854 /* Special case for seeking in files with no cues */
855 EbmlElement *el = NULL;
857 /* Start from the last known index instead of the beginning eachtime */
859 es.I_O().setFilePointer( i_start_pos, seek_beginning );
861 es.I_O().setFilePointer( p_indexes[ i_index - 1 ].i_position,
864 ep = new EbmlParser( &es, segment, &sys.demuxer );
867 while( ( el = ep->Get() ) != NULL )
869 if( MKV_IS_ID( el, KaxCluster ) )
871 cluster = (KaxCluster *)el;
872 i_cluster_pos = cluster->GetElementPosition();
875 p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
878 IndexAppendCluster( cluster );
880 if( es.I_O().getFilePointer() >= (unsigned) i_global_position )
886 /* Don't try complex seek if we seek to 0 */
887 if( i_date == 0 && i_time_offset == 0 )
889 es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, VLC_TS_0 );
890 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME,
892 es.I_O().setFilePointer( i_start_pos );
895 ep = new EbmlParser( &es, segment, &sys.demuxer );
907 for( ; i_idx < i_index; i_idx++ )
908 if( p_indexes[i_idx].i_time + i_time_offset > i_date )
914 i_seek_position = p_indexes[i_idx].i_position;
915 i_seek_time = p_indexes[i_idx].i_time;
918 msg_Dbg( &sys.demuxer, "seek got %"PRId64" (%d%%)",
919 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
921 es.I_O().setFilePointer( i_seek_position, seek_beginning );
924 ep = new EbmlParser( &es, segment, &sys.demuxer );
927 sys.i_start_pts = i_date;
929 /* now parse until key frame */
930 const int es_types[3] = { VIDEO_ES, AUDIO_ES, SPU_ES };
932 mtime_t i_seek_preroll = 0;
933 for( int i = 0; i < 2; i_cat = es_types[++i] )
935 for( i_track = 0; i_track < tracks.size(); i_track++ )
937 if( tracks[i_track]->i_seek_preroll )
940 if( es_out_Control( sys.demuxer.out,
942 tracks[i_track]->p_es,
943 &b_enabled ) == VLC_SUCCESS &&
945 i_seek_preroll = __MAX( i_seek_preroll,
946 tracks[i_track]->i_seek_preroll );
948 if( tracks[i_track]->fmt.i_cat == i_cat )
950 spoint * seekpoint = new spoint(i_track, i_seek_time, i_seek_position, i_seek_position);
951 if( unlikely( !seekpoint ) )
953 for( spoint * sp = p_first; sp; )
961 if( unlikely( !p_first ) )
968 p_last->p_next = seekpoint;
973 if( likely( p_first ) )
976 /*Neither video nor audio track... no seek further*/
977 if( unlikely( !p_first ) )
979 es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, i_date );
980 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
983 i_date -= i_seek_preroll;
989 bool b_discardable_picture;
990 if( BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
992 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
996 /* check if block's track is in our list */
997 for( i_track = 0; i_track < tracks.size(); i_track++ )
999 if( (simpleblock && tracks[i_track]->i_number == simpleblock->TrackNum()) ||
1000 (block && tracks[i_track]->i_number == block->TrackNum()) )
1005 i_pts = sys.i_chapter_time + simpleblock->GlobalTimecode() / (mtime_t) 1000;
1007 i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1008 if( i_track < tracks.size() )
1010 if( tracks[i_track]->fmt.i_cat == i_cat && b_key_picture )
1012 /* get the seekpoint */
1014 for( sp = p_first; sp; sp = sp->p_next )
1015 if( sp->i_track == i_track )
1020 sp->i_seek_pos = simpleblock->GetElementPosition();
1022 sp->i_seek_pos = i_block_pos;
1023 sp->i_cluster_pos = i_cluster_pos;
1029 } while( i_pts < i_date );
1030 if( b_has_key || !i_idx )
1033 /* No key picture was found in the cluster seek to previous seekpoint */
1034 i_date = i_time_offset + p_indexes[i_idx].i_time;
1037 es.I_O().setFilePointer( p_indexes[i_idx].i_position );
1039 ep = new EbmlParser( &es, segment, &sys.demuxer );
1043 /* rewind to the last I img */
1045 for( p_min = p_first, p_last = p_first; p_last; p_last = p_last->p_next )
1046 if( p_last->i_date < p_min->i_date )
1049 sys.i_pcr = sys.i_pts = p_min->i_date;
1050 es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, VLC_TS_0 + sys.i_pcr );
1051 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1052 cluster = (KaxCluster *) ep->UnGet( p_min->i_seek_pos, p_min->i_cluster_pos );
1054 /* hack use BlockGet to get the cluster then goto the wanted block */
1058 bool b_discardable_picture;
1059 BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration );
1061 cluster = (KaxCluster *) ep->UnGet( p_min->i_seek_pos, p_min->i_cluster_pos );
1067 p_first = p_first->p_next;
1072 int matroska_segment_c::BlockFindTrackIndex( size_t *pi_track,
1073 const KaxBlock *p_block, const KaxSimpleBlock *p_simpleblock )
1076 for( i_track = 0; i_track < tracks.size(); i_track++ )
1078 const mkv_track_t *tk = tracks[i_track];
1080 if( ( p_block != NULL && tk->i_number == p_block->TrackNum() ) ||
1081 ( p_simpleblock != NULL && tk->i_number == p_simpleblock->TrackNum() ) )
1087 if( i_track >= tracks.size() )
1088 return VLC_EGENERIC;
1091 *pi_track = i_track;
1095 void matroska_segment_c::ComputeTrackPriority()
1097 bool b_has_default_video = false;
1098 bool b_has_default_audio = false;
1099 /* check for default */
1100 for(size_t i_track = 0; i_track < tracks.size(); i_track++)
1102 mkv_track_t *p_tk = tracks[i_track];
1103 es_format_t *p_fmt = &p_tk->fmt;
1104 if( p_fmt->i_cat == VIDEO_ES )
1105 b_has_default_video |=
1106 p_tk->b_enabled && ( p_tk->b_default || p_tk->b_forced );
1107 else if( p_fmt->i_cat == AUDIO_ES )
1108 b_has_default_audio |=
1109 p_tk->b_enabled && ( p_tk->b_default || p_tk->b_forced );
1112 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1114 mkv_track_t *p_tk = tracks[i_track];
1115 es_format_t *p_fmt = &p_tk->fmt;
1117 if( unlikely( p_fmt->i_cat == UNKNOWN_ES || !p_tk->psz_codec ) )
1119 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, p_tk->i_number );
1123 else if( unlikely( !b_has_default_video && p_fmt->i_cat == VIDEO_ES ) )
1125 p_tk->b_default = true;
1126 b_has_default_video = true;
1128 else if( unlikely( !b_has_default_audio && p_fmt->i_cat == AUDIO_ES ) )
1130 p_tk->b_default = true;
1131 b_has_default_audio = true;
1133 if( unlikely( !p_tk->b_enabled ) )
1134 p_tk->fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
1135 else if( p_tk->b_forced )
1136 p_tk->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 2;
1137 else if( p_tk->b_default )
1138 p_tk->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1;
1140 p_tk->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
1142 /* Avoid multivideo tracks when unnecessary */
1143 if( p_tk->fmt.i_cat == VIDEO_ES )
1144 p_tk->fmt.i_priority--;
1148 bool matroska_segment_c::Select( mtime_t i_start_time )
1151 msg_Dbg( &sys.demuxer, "found %d es", (int)tracks.size() );
1153 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1155 mkv_track_t *p_tk = tracks[i_track];
1156 es_format_t *p_fmt = &p_tk->fmt;
1158 if( unlikely( p_fmt->i_cat == UNKNOWN_ES || !p_tk->psz_codec ) )
1160 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, p_tk->i_number );
1166 p_tk->p_es = es_out_Add( sys.demuxer.out, &p_tk->fmt );
1168 /* Turn on a subtitles track if it has been flagged as default -
1169 * but only do this if no subtitles track has already been engaged,
1170 * either by an earlier 'default track' (??) or by default
1171 * language choice behaviour.
1173 if( p_tk->b_default || p_tk->b_forced )
1175 es_out_Control( sys.demuxer.out,
1176 ES_OUT_SET_ES_DEFAULT,
1180 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_start_time );
1182 sys.i_start_pts = i_start_time;
1183 // reset the stream reading to the first cluster of the segment used
1184 es.I_O().setFilePointer( i_start_pos );
1187 ep = new EbmlParser( &es, segment, &sys.demuxer );
1192 void matroska_segment_c::UnSelect( )
1194 sys.p_ev->ResetPci();
1195 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1197 if ( tracks[i_track]->p_es != NULL )
1199 // es_format_Clean( &tracks[i_track]->fmt );
1200 es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
1201 tracks[i_track]->p_es = NULL;
1208 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, KaxSimpleBlock * & pp_simpleblock, bool *pb_key_picture, bool *pb_discardable_picture, int64_t *pi_duration )
1210 pp_simpleblock = NULL;
1213 *pb_key_picture = true;
1214 *pb_discardable_picture = false;
1220 EbmlElement *el = NULL;
1224 return VLC_EGENERIC;
1226 if( pp_simpleblock != NULL || ((el = ep->Get()) == NULL && pp_block != NULL) )
1228 /* Check blocks validity to protect againts broken files */
1229 if( BlockFindTrackIndex( &i_tk, pp_block , pp_simpleblock ) )
1232 pp_simpleblock = NULL;
1236 if( pp_simpleblock != NULL )
1238 *pb_key_picture = pp_simpleblock->IsKeyframe();
1239 *pb_discardable_picture = pp_simpleblock->IsDiscardable();
1241 /* We have block group let's check if the picture is a keyframe */
1242 else if( *pb_key_picture )
1244 switch(tracks[i_tk]->fmt.i_codec)
1246 case VLC_CODEC_THEORA:
1248 DataBuffer *p_data = &pp_block->GetBuffer(0);
1249 size_t sz = p_data->Size();
1250 const uint8_t * p_buff = p_data->Buffer();
1251 /* if the second bit of a Theora frame is 1
1252 it's not a keyframe */
1255 if( p_buff[0] & 0x40 )
1256 *pb_key_picture = false;
1259 *pb_key_picture = false;
1265 /* update the index */
1266 #define idx p_indexes[i_index - 1]
1267 if( i_index > 0 && idx.i_time == -1 )
1269 if ( pp_simpleblock != NULL )
1270 idx.i_time = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1272 idx.i_time = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1273 idx.b_key = *pb_key_picture;
1279 i_level = ep->GetLevel();
1288 msg_Warn( &sys.demuxer, "EOF" );
1289 return VLC_EGENERIC;
1292 /* Verify that we are still inside our cluster
1293 * It can happens whith broken files and when seeking
1297 if( cluster && !ep->IsTopPresent( cluster ) )
1299 msg_Warn( &sys.demuxer, "Unexpected escape from current cluster" );
1312 if( MKV_IS_ID( el, KaxCluster ) )
1314 cluster = (KaxCluster*)el;
1315 i_cluster_pos = cluster->GetElementPosition();
1317 // reset silent tracks
1318 for (size_t i=0; i<tracks.size(); i++)
1320 tracks[i]->b_silent = false;
1325 else if( MKV_IS_ID( el, KaxCues ) )
1327 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1328 return VLC_EGENERIC;
1332 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1336 if( unlikely( el->GetSize() >= SIZE_MAX ) )
1338 msg_Err( &sys.demuxer, "Error while reading %s... upping level", typeid(*el).name());
1342 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1344 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1346 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1347 cluster->InitTimecode( uint64( ctc ), i_timescale );
1349 /* add it to the index */
1352 p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1353 IndexAppendCluster( cluster );
1355 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1359 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1361 i_block_pos = el->GetElementPosition();
1364 else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1366 pp_simpleblock = (KaxSimpleBlock*)el;
1368 pp_simpleblock->ReadData( es.I_O() );
1369 pp_simpleblock->SetParent( *cluster );
1373 if( unlikely( el->GetSize() >= SIZE_MAX ) )
1375 msg_Err( &sys.demuxer, "Error while reading %s... upping level", typeid(*el).name());
1378 pp_simpleblock = NULL;
1382 if( MKV_IS_ID( el, KaxBlock ) )
1384 pp_block = (KaxBlock*)el;
1386 pp_block->ReadData( es.I_O() );
1387 pp_block->SetParent( *cluster );
1391 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1393 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1395 dur.ReadData( es.I_O() );
1396 *pi_duration = uint64( dur );
1398 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1400 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1402 ref.ReadData( es.I_O() );
1404 if( *pb_key_picture )
1405 *pb_key_picture = false;
1406 else if( int64( ref ) > 0 )
1407 *pb_discardable_picture = true;
1409 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1411 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1412 track_num.ReadData( es.I_O() );
1414 for (size_t i=0; i<tracks.size(); i++)
1416 if ( tracks[i]->i_number == uint32(track_num))
1418 tracks[i]->b_silent = true;
1423 #if LIBMATROSKA_VERSION >= 0x010401
1424 else if( MKV_IS_ID( el, KaxDiscardPadding ) )
1426 KaxDiscardPadding &dp = *(KaxDiscardPadding*) el;
1427 *pi_duration -= int64(dp);
1432 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1433 return VLC_EGENERIC;
1438 msg_Err( &sys.demuxer, "Error while reading %s... upping level", typeid(*el).name());
1441 pp_simpleblock = NULL;
1447 SimpleTag::~SimpleTag()
1452 for(size_t i = 0; i < sub_tags.size(); i++)
1458 for(size_t i = 0; i < simple_tags.size(); i++)
1459 delete simple_tags[i];