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 );
97 vlc_delete_all( tags );
101 /*****************************************************************************
103 *****************************************************************************
104 * * LoadCues : load the cues element and update index
105 * * LoadTags : load ... the tags element
106 * * InformationCreate : create all information, load tags if present
107 *****************************************************************************/
108 void matroska_segment_c::LoadCues( KaxCues *cues )
116 msg_Err( &sys.demuxer, "There can be only 1 Cues per section." );
120 ep = new EbmlParser( &es, cues, &sys.demuxer );
121 while( ( el = ep->Get() ) != NULL )
123 if( MKV_IS_ID( el, KaxCuePoint ) )
125 b_invalid_cue = false;
126 #define idx p_indexes[i_index]
129 idx.i_block_number= -1;
135 while( ( el = ep->Get() ) != NULL )
137 if( MKV_IS_ID( el, KaxCueTime ) )
139 KaxCueTime &ctime = *(KaxCueTime*)el;
142 if( unlikely( ctime.GetSize() >= SIZE_MAX ) )
144 msg_Err( &sys.demuxer, "CueTime size too big");
145 b_invalid_cue = true;
148 ctime.ReadData( es.I_O() );
152 msg_Err( &sys.demuxer, "Error while reading CueTime" );
153 b_invalid_cue = true;
156 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
158 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
163 while( ( el = ep->Get() ) != NULL )
165 if( unlikely( el->GetSize() >= SIZE_MAX ) )
168 msg_Err( &sys.demuxer, "Error %s too big, aborting", typeid(*el).name() );
169 b_invalid_cue = true;
173 if( MKV_IS_ID( el, KaxCueTrack ) )
175 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
176 ctrack.ReadData( es.I_O() );
177 idx.i_track = uint16( ctrack );
179 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
181 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
183 ccpos.ReadData( es.I_O() );
184 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
186 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
188 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
190 cbnum.ReadData( es.I_O() );
191 idx.i_block_number = uint32( cbnum );
193 #if LIBMATROSKA_VERSION >= 0x010401
194 else if( MKV_IS_ID( el, KaxCueRelativePosition ) )
198 else if( MKV_IS_ID( el, KaxCueDuration ) )
205 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
212 msg_Err( &sys.demuxer, "Error while reading %s", typeid(*el).name() );
213 b_invalid_cue = true;
220 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
226 msg_Dbg( &sys.demuxer, " * added time=%"PRId64" pos=%"PRId64
227 " track=%d bnum=%d", idx.i_time, idx.i_position,
228 idx.i_track, idx.i_block_number );
230 if( likely( !b_invalid_cue ) )
233 if( i_index >= i_index_max )
236 p_indexes = (mkv_index_t*)xrealloc( p_indexes,
237 sizeof( mkv_index_t ) * i_index_max );
244 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
249 msg_Dbg( &sys.demuxer, "| - loading cues done." );
253 static const struct {
254 vlc_meta_type_t type;
256 int target_type; /* 0 is valid for all target_type */
258 {vlc_meta_Album, "TITLE", 50},
259 {vlc_meta_Title, "TITLE", 0},
260 {vlc_meta_Artist, "ARTIST", 0},
261 {vlc_meta_Genre, "GENRE", 0},
262 {vlc_meta_Copyright, "COPYRIGHT", 0},
263 {vlc_meta_TrackNumber, "PART_NUMBER", 0},
264 {vlc_meta_Description, "DESCRIPTION", 0},
265 {vlc_meta_Description, "COMMENT", 0},
266 {vlc_meta_Rating, "RATING", 0},
267 {vlc_meta_Date, "DATE_RELEASED", 0},
268 {vlc_meta_Date, "DATE_RELEASE", 0},
269 {vlc_meta_Date, "DATE_RECORDED", 0},
270 {vlc_meta_URL, "URL", 0},
271 {vlc_meta_Publisher, "PUBLISHER", 0},
272 {vlc_meta_EncodedBy, "ENCODED_BY", 0},
273 {vlc_meta_TrackTotal, "TOTAL_PARTS", 0},
274 {vlc_meta_Title, NULL, 0},
277 SimpleTag * matroska_segment_c::ParseSimpleTags( KaxTagSimple *tag, int target_type )
280 EbmlParser *ep = new EbmlParser( &es, tag, &sys.demuxer );
281 SimpleTag * p_simple = new SimpleTag;
282 size_t max_size = tag->GetSize();
287 msg_Err( &sys.demuxer, "Couldn't allocate memory for Simple Tag... ignoring it");
292 sys.meta = vlc_meta_New();
294 msg_Dbg( &sys.demuxer, "| + Simple Tag ");
297 while( ( el = ep->Get() ) != NULL && size < max_size)
299 if( unlikely( el->GetSize() >= SIZE_MAX ) )
301 msg_Err( &sys.demuxer, "Error %s too big ignoring the tag", typeid(*el).name() );
306 if( MKV_IS_ID( el, KaxTagName ) )
308 KaxTagName &key = *(KaxTagName*)el;
309 key.ReadData( es.I_O(), SCOPE_ALL_DATA );
310 p_simple->psz_tag_name = strdup( UTFstring( key ).GetUTF8().c_str() );
312 else if( MKV_IS_ID( el, KaxTagString ) )
314 KaxTagString &value = *(KaxTagString*)el;
315 value.ReadData( es.I_O(), SCOPE_ALL_DATA );
316 p_simple->p_value = strdup( UTFstring( value ).GetUTF8().c_str() );
318 else if( MKV_IS_ID( el, KaxTagLangue ) )
320 KaxTagLangue &language = *(KaxTagLangue*) el;
321 language.ReadData( es.I_O(), SCOPE_ALL_DATA );
322 p_simple->psz_lang = strdup( string( language ).c_str());
324 else if( MKV_IS_ID( el, KaxTagDefault ) )
326 KaxTagDefault & dft = *(KaxTagDefault*) el;
327 dft.ReadData( es.I_O(), SCOPE_ALL_DATA );
328 p_simple->b_default = (bool) uint8( dft );
330 /*Tags can be nested*/
331 else if( MKV_IS_ID( el, KaxTagSimple) )
333 SimpleTag * p_st = ParseSimpleTags( (KaxTagSimple*)el, target_type );
335 p_simple->sub_tags.push_back( p_st );
337 /*TODO Handle binary tags*/
338 size += el->HeadSize() + el->GetSize();
343 msg_Err( &sys.demuxer, "Error while reading Tag ");
350 if( !p_simple->psz_tag_name || !p_simple->p_value )
352 msg_Warn( &sys.demuxer, "Invalid MKV SimpleTag found.");
356 for( int i = 0; metadata_map[i].key; i++ )
358 if( !strcmp( p_simple->psz_tag_name, metadata_map[i].key ) &&
359 (metadata_map[i].target_type == 0 || target_type == metadata_map[i].target_type ) )
361 vlc_meta_Set( sys.meta, metadata_map[i].type, p_simple->p_value );
362 msg_Dbg( &sys.demuxer, "| | + Meta %s: %s", p_simple->psz_tag_name, p_simple->p_value);
366 msg_Dbg( &sys.demuxer, "| | + Meta %s: %s", p_simple->psz_tag_name, p_simple->p_value);
367 vlc_meta_AddExtra( sys.meta, p_simple->psz_tag_name, p_simple->p_value);
372 #define PARSE_TAG( type ) \
374 msg_Dbg( &sys.demuxer, "| + " type ); \
376 while( ( el = ep->Get() ) != NULL ) \
378 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() ); \
380 ep->Up(); } while( 0 )
383 void matroska_segment_c::LoadTags( KaxTags *tags )
385 /* Master elements */
386 EbmlParser *ep = new EbmlParser( &es, tags, &sys.demuxer );
389 while( ( el = ep->Get() ) != NULL )
391 if( MKV_IS_ID( el, KaxTag ) )
393 Tag * p_tag = new Tag;
396 msg_Err( &sys.demuxer,"Couldn't allocate memory for tag... ignoring it");
399 msg_Dbg( &sys.demuxer, "+ Tag" );
401 int target_type = 50;
402 while( ( el = ep->Get() ) != NULL )
404 if( MKV_IS_ID( el, KaxTagTargets ) )
406 msg_Dbg( &sys.demuxer, "| + Targets" );
408 while( ( el = ep->Get() ) != NULL )
412 if( unlikely( el->GetSize() >= SIZE_MAX ) )
414 msg_Err( &sys.demuxer, "Invalid size while reading tag");
417 if( MKV_IS_ID( el, KaxTagTargetTypeValue ) )
419 KaxTagTargetTypeValue &value = *(KaxTagTargetTypeValue*)el;
420 value.ReadData( es.I_O() );
422 msg_Dbg( &sys.demuxer, "| | + TargetTypeValue: %u", uint32(value));
423 target_type = uint32(value);
425 if( MKV_IS_ID( el, KaxTagTrackUID ) )
427 p_tag->i_tag_type = TRACK_UID;
428 KaxTagTrackUID &uid = *(KaxTagTrackUID*) el;
429 uid.ReadData( es.I_O() );
430 p_tag->i_uid = uint64( uid );
431 msg_Dbg( &sys.demuxer, "| | + TrackUID: %" PRIu64, p_tag->i_uid);
434 if( MKV_IS_ID( el, KaxTagEditionUID ) )
436 p_tag->i_tag_type = EDITION_UID;
437 KaxTagEditionUID &uid = *(KaxTagEditionUID*) el;
438 uid.ReadData( es.I_O() );
439 p_tag->i_uid = uint64( uid );
440 msg_Dbg( &sys.demuxer, "| | + EditionUID: %" PRIu64, p_tag->i_uid);
442 if( MKV_IS_ID( el, KaxTagChapterUID ) )
444 p_tag->i_tag_type = CHAPTER_UID;
445 KaxTagChapterUID &uid = *(KaxTagChapterUID*) el;
446 uid.ReadData( es.I_O() );
447 p_tag->i_uid = uint64( uid );
448 msg_Dbg( &sys.demuxer, "| | + ChapterUID: %" PRIu64, p_tag->i_uid);
450 if( MKV_IS_ID( el, KaxTagAttachmentUID ) )
452 p_tag->i_tag_type = ATTACHMENT_UID;
453 KaxTagAttachmentUID &uid = *(KaxTagAttachmentUID*) el;
454 uid.ReadData( es.I_O() );
455 p_tag->i_uid = uint64( uid );
456 msg_Dbg( &sys.demuxer, "| | + AttachmentUID: %" PRIu64, p_tag->i_uid);
461 msg_Err( &sys.demuxer, "Error while reading tag");
467 else if( MKV_IS_ID( el, KaxTagSimple ) )
469 SimpleTag * p_simple =
470 ParseSimpleTags( static_cast<KaxTagSimple*>( el ),
473 p_tag->simple_tags.push_back( p_simple );
475 #if 0 // not valid anymore
476 else if( MKV_IS_ID( el, KaxTagGeneral ) )
477 PARSE_TAG( "General" );
478 else if( MKV_IS_ID( el, KaxTagGenres ) )
479 PARSE_TAG( "Genres" );
480 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
481 PARSE_TAG( "Audio Specific" );
482 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
483 PARSE_TAG( "Images Specific" );
484 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
486 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
488 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
490 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
492 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
494 msg_Dbg( &sys.demuxer, "| + Multi Date" );
496 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
498 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
500 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
502 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
504 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
506 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
508 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
510 msg_Dbg( &sys.demuxer, "| + Multi Title" );
515 msg_Dbg( &sys.demuxer, "| + LoadTag Unknown (%s)", typeid( *el ).name() );
519 this->tags.push_back(p_tag);
523 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
528 msg_Dbg( &sys.demuxer, "loading tags done." );
532 /*****************************************************************************
534 *****************************************************************************/
535 void matroska_segment_c::InformationCreate( )
538 sys.meta = vlc_meta_New();
542 vlc_meta_SetTitle( sys.meta, psz_title );
547 vlc_meta_SetDate( sys.meta, psz_date_utc );
550 if( psz_segment_filename )
552 fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
554 if( psz_muxing_application )
556 fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
558 if( psz_writing_application )
560 fprintf( stderr, "***** WARNING: Unhandled meta - Use custom\n" );
563 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
565 // mkv_track_t *tk = tracks[i_track];
566 // vlc_meta_t *mtk = vlc_meta_New();
567 fprintf( stderr, "***** WARNING: Unhandled child meta\n");
571 if( i_tags_position >= 0 )
575 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
585 /*****************************************************************************
587 *****************************************************************************/
589 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
591 #define idx p_indexes[i_index]
593 idx.i_block_number= -1;
594 idx.i_position = cluster->GetElementPosition();
595 idx.i_time = cluster->GlobalTimecode()/ (mtime_t) 1000;
599 if( i_index >= i_index_max )
602 p_indexes = (mkv_index_t*)xrealloc( p_indexes,
603 sizeof( mkv_index_t ) * i_index_max );
608 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
613 for (size_t i=0; i<families.size(); i++)
615 for (size_t j=0; j<of_segment.families.size(); j++)
617 if ( *(families[i]) == *(of_segment.families[j]) )
625 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
629 if ( p_item_a == NULL || p_item_b == NULL )
632 p_tmp = (EbmlBinary *)p_item_a->p_segment_uid;
633 if ( p_item_b->p_prev_segment_uid != NULL
634 && *p_tmp == *p_item_b->p_prev_segment_uid )
637 p_tmp = (EbmlBinary *)p_item_a->p_next_segment_uid;
641 if ( p_item_b->p_segment_uid != NULL
642 && *p_tmp == *p_item_b->p_segment_uid )
645 if ( p_item_b->p_prev_segment_uid != NULL
646 && *p_tmp == *p_item_b->p_prev_segment_uid )
652 bool matroska_segment_c::Preload( )
657 EbmlElement *el = NULL;
659 ep->Reset( &sys.demuxer );
661 while( ( el = ep->Get() ) != NULL )
663 if( MKV_IS_ID( el, KaxSeekHead ) )
665 /* Multiple allowed */
666 /* We bail at 10, to prevent possible recursion */
667 msg_Dbg( &sys.demuxer, "| + Seek head" );
668 if( i_seekhead_count < 10 )
670 i_seekhead_position = (int64_t) es.I_O().getFilePointer();
671 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
674 else if( MKV_IS_ID( el, KaxInfo ) )
676 /* Multiple allowed, mandatory */
677 msg_Dbg( &sys.demuxer, "| + Information" );
678 if( i_info_position < 0 ) // FIXME
679 ParseInfo( static_cast<KaxInfo*>( el ) );
680 i_info_position = (int64_t) es.I_O().getFilePointer();
682 else if( MKV_IS_ID( el, KaxTracks ) )
684 /* Multiple allowed */
685 msg_Dbg( &sys.demuxer, "| + Tracks" );
686 if( i_tracks_position < 0 ) // FIXME
687 ParseTracks( static_cast<KaxTracks*>( el ) );
688 if ( tracks.size() == 0 )
690 msg_Err( &sys.demuxer, "No tracks supported" );
693 i_tracks_position = (int64_t) es.I_O().getFilePointer();
695 else if( MKV_IS_ID( el, KaxCues ) )
697 msg_Dbg( &sys.demuxer, "| + Cues" );
698 if( i_cues_position < 0 )
699 LoadCues( static_cast<KaxCues*>( el ) );
700 i_cues_position = (int64_t) es.I_O().getFilePointer();
702 else if( MKV_IS_ID( el, KaxCluster ) )
704 msg_Dbg( &sys.demuxer, "| + Cluster" );
706 cluster = (KaxCluster*)el;
708 i_cluster_pos = i_start_pos = cluster->GetElementPosition();
712 /* stop pre-parsing the stream */
715 else if( MKV_IS_ID( el, KaxAttachments ) )
717 msg_Dbg( &sys.demuxer, "| + Attachments" );
718 if( i_attachments_position < 0 )
719 ParseAttachments( static_cast<KaxAttachments*>( el ) );
720 i_attachments_position = (int64_t) es.I_O().getFilePointer();
722 else if( MKV_IS_ID( el, KaxChapters ) )
724 msg_Dbg( &sys.demuxer, "| + Chapters" );
725 if( i_chapters_position < 0 )
726 ParseChapters( static_cast<KaxChapters*>( el ) );
727 i_chapters_position = (int64_t) es.I_O().getFilePointer();
729 else if( MKV_IS_ID( el, KaxTag ) )
731 msg_Dbg( &sys.demuxer, "| + Tags" );
732 /*FIXME if( i_tags_position < 0)
733 LoadTags( static_cast<KaxTags*>( el ) );*/
734 i_tags_position = (int64_t) es.I_O().getFilePointer();
736 else if( MKV_IS_ID( el, EbmlVoid ) )
737 msg_Dbg( &sys.demuxer, "| + Void" );
739 msg_Dbg( &sys.demuxer, "| + Preload Unknown (%s)", typeid(*el).name() );
742 ComputeTrackPriority();
749 /* Here we try to load elements that were found in Seek Heads, but not yet parsed */
750 bool matroska_segment_c::LoadSeekHeadItem( const EbmlCallbacks & ClassInfos, int64_t i_element_position )
752 int64_t i_sav_position = (int64_t)es.I_O().getFilePointer();
755 es.I_O().setFilePointer( i_element_position, seek_beginning );
756 el = es.FindNextID( ClassInfos, 0xFFFFFFFFL);
760 msg_Err( &sys.demuxer, "cannot load some cues/chapters/tags etc. (broken seekhead or file)" );
761 es.I_O().setFilePointer( i_sav_position, seek_beginning );
765 if( MKV_IS_ID( el, KaxSeekHead ) )
767 /* Multiple allowed */
768 msg_Dbg( &sys.demuxer, "| + Seek head" );
769 if( i_seekhead_count < 10 )
771 i_seekhead_position = i_element_position;
772 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
775 else if( MKV_IS_ID( el, KaxInfo ) ) // FIXME
777 /* Multiple allowed, mandatory */
778 msg_Dbg( &sys.demuxer, "| + Information" );
779 if( i_info_position < 0 )
780 ParseInfo( static_cast<KaxInfo*>( el ) );
781 i_info_position = i_element_position;
783 else if( MKV_IS_ID( el, KaxTracks ) ) // FIXME
785 /* Multiple allowed */
786 msg_Dbg( &sys.demuxer, "| + Tracks" );
787 if( i_tracks_position < 0 )
788 ParseTracks( static_cast<KaxTracks*>( el ) );
789 if ( tracks.size() == 0 )
791 msg_Err( &sys.demuxer, "No tracks supported" );
793 es.I_O().setFilePointer( i_sav_position, seek_beginning );
796 i_tracks_position = i_element_position;
798 else if( MKV_IS_ID( el, KaxCues ) )
800 msg_Dbg( &sys.demuxer, "| + Cues" );
801 if( i_cues_position < 0 )
802 LoadCues( static_cast<KaxCues*>( el ) );
803 i_cues_position = i_element_position;
805 else if( MKV_IS_ID( el, KaxAttachments ) )
807 msg_Dbg( &sys.demuxer, "| + Attachments" );
808 if( i_attachments_position < 0 )
809 ParseAttachments( static_cast<KaxAttachments*>( el ) );
810 i_attachments_position = i_element_position;
812 else if( MKV_IS_ID( el, KaxChapters ) )
814 msg_Dbg( &sys.demuxer, "| + Chapters" );
815 if( i_chapters_position < 0 )
816 ParseChapters( static_cast<KaxChapters*>( el ) );
817 i_chapters_position = i_element_position;
819 else if( MKV_IS_ID( el, KaxTags ) )
821 msg_Dbg( &sys.demuxer, "| + Tags" );
822 if( i_tags_position < 0 )
823 LoadTags( static_cast<KaxTags*>( el ) );
824 i_tags_position = i_element_position;
828 msg_Dbg( &sys.demuxer, "| + LoadSeekHeadItem Unknown (%s)", typeid(*el).name() );
832 es.I_O().setFilePointer( i_sav_position, seek_beginning );
838 spoint(unsigned int tk, mtime_t date, int64_t pos, int64_t cpos):
839 i_track(tk),i_date(date), i_seek_pos(pos),
840 i_cluster_pos(cpos), p_next(NULL){}
841 unsigned int i_track;
844 int64_t i_cluster_pos;
848 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset, int64_t i_global_position )
851 KaxSimpleBlock *simpleblock;
852 int64_t i_block_duration;
854 int64_t i_seek_position = i_start_pos;
855 int64_t i_seek_time = i_start_time;
857 spoint *p_first = NULL;
858 spoint *p_last = NULL;
860 bool b_has_key = false;
862 for( size_t i = 0; i < tracks.size(); i++)
863 tracks[i]->i_last_dts = VLC_TS_INVALID;
865 if( i_global_position >= 0 )
867 /* Special case for seeking in files with no cues */
868 EbmlElement *el = NULL;
870 /* Start from the last known index instead of the beginning eachtime */
872 es.I_O().setFilePointer( i_start_pos, seek_beginning );
874 es.I_O().setFilePointer( p_indexes[ i_index - 1 ].i_position,
877 ep = new EbmlParser( &es, segment, &sys.demuxer );
880 while( ( el = ep->Get() ) != NULL )
882 if( MKV_IS_ID( el, KaxCluster ) )
884 cluster = (KaxCluster *)el;
885 i_cluster_pos = cluster->GetElementPosition();
888 p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
891 IndexAppendCluster( cluster );
893 if( es.I_O().getFilePointer() >= (unsigned) i_global_position )
899 /* Don't try complex seek if we seek to 0 */
900 if( i_date == 0 && i_time_offset == 0 )
902 es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, VLC_TS_0 );
903 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME,
905 es.I_O().setFilePointer( i_start_pos );
908 ep = new EbmlParser( &es, segment, &sys.demuxer );
920 for( ; i_idx < i_index; i_idx++ )
921 if( p_indexes[i_idx].i_time + i_time_offset > i_date )
927 i_seek_position = p_indexes[i_idx].i_position;
928 i_seek_time = p_indexes[i_idx].i_time;
931 msg_Dbg( &sys.demuxer, "seek got %" PRId64 " - %" PRId64, i_seek_time, i_seek_position );
933 es.I_O().setFilePointer( i_seek_position, seek_beginning );
936 ep = new EbmlParser( &es, segment, &sys.demuxer );
939 sys.i_start_pts = i_date;
941 /* now parse until key frame */
942 const int es_types[3] = { VIDEO_ES, AUDIO_ES, SPU_ES };
944 mtime_t i_seek_preroll = 0;
945 for( int i = 0; i < 2; i_cat = es_types[++i] )
947 for( i_track = 0; i_track < tracks.size(); i_track++ )
949 if( tracks[i_track]->i_seek_preroll )
952 if( es_out_Control( sys.demuxer.out,
954 tracks[i_track]->p_es,
955 &b_enabled ) == VLC_SUCCESS &&
957 i_seek_preroll = __MAX( i_seek_preroll,
958 tracks[i_track]->i_seek_preroll );
960 if( tracks[i_track]->fmt.i_cat == i_cat )
962 spoint * seekpoint = new spoint(i_track, i_seek_time, i_seek_position, i_seek_position);
963 if( unlikely( !seekpoint ) )
965 for( spoint * sp = p_first; sp; )
973 if( unlikely( !p_first ) )
980 p_last->p_next = seekpoint;
985 if( likely( p_first ) )
988 /*Neither video nor audio track... no seek further*/
989 if( unlikely( !p_first ) )
991 es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, i_date );
992 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
995 i_date -= i_seek_preroll;
1001 bool b_discardable_picture;
1002 if( BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration ) )
1004 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
1007 spoint *tmp = p_first;
1008 p_first = p_first->p_next;
1014 /* check if block's track is in our list */
1015 for( i_track = 0; i_track < tracks.size(); i_track++ )
1017 if( (simpleblock && tracks[i_track]->i_number == simpleblock->TrackNum()) ||
1018 (block && tracks[i_track]->i_number == block->TrackNum()) )
1023 i_pts = sys.i_chapter_time + simpleblock->GlobalTimecode() / (mtime_t) 1000;
1025 i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1026 if( i_track < tracks.size() )
1028 if( tracks[i_track]->fmt.i_cat == i_cat && b_key_picture )
1030 /* get the seekpoint */
1032 for( sp = p_first; sp; sp = sp->p_next )
1033 if( sp->i_track == i_track )
1038 sp->i_seek_pos = simpleblock->GetElementPosition();
1040 sp->i_seek_pos = i_block_pos;
1041 sp->i_cluster_pos = i_cluster_pos;
1047 } while( i_pts < i_date );
1048 if( b_has_key || !i_idx )
1051 /* No key picture was found in the cluster seek to previous seekpoint */
1052 i_date = i_time_offset + p_indexes[i_idx].i_time;
1055 es.I_O().setFilePointer( p_indexes[i_idx].i_position );
1057 ep = new EbmlParser( &es, segment, &sys.demuxer );
1061 /* rewind to the last I img */
1063 for( p_min = p_first, p_last = p_first; p_last; p_last = p_last->p_next )
1064 if( p_last->i_date < p_min->i_date )
1067 sys.i_pcr = sys.i_pts = p_min->i_date;
1068 es_out_Control( sys.demuxer.out, ES_OUT_SET_PCR, VLC_TS_0 + sys.i_pcr );
1069 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_date );
1070 cluster = (KaxCluster *) ep->UnGet( p_min->i_seek_pos, p_min->i_cluster_pos );
1072 /* hack use BlockGet to get the cluster then goto the wanted block */
1076 bool b_discardable_picture;
1077 BlockGet( block, simpleblock, &b_key_picture, &b_discardable_picture, &i_block_duration );
1079 cluster = (KaxCluster *) ep->UnGet( p_min->i_seek_pos, p_min->i_cluster_pos );
1085 p_first = p_first->p_next;
1090 int matroska_segment_c::BlockFindTrackIndex( size_t *pi_track,
1091 const KaxBlock *p_block, const KaxSimpleBlock *p_simpleblock )
1094 for( i_track = 0; i_track < tracks.size(); i_track++ )
1096 const mkv_track_t *tk = tracks[i_track];
1098 if( ( p_block != NULL && tk->i_number == p_block->TrackNum() ) ||
1099 ( p_simpleblock != NULL && tk->i_number == p_simpleblock->TrackNum() ) )
1105 if( i_track >= tracks.size() )
1106 return VLC_EGENERIC;
1109 *pi_track = i_track;
1113 void matroska_segment_c::ComputeTrackPriority()
1115 bool b_has_default_video = false;
1116 bool b_has_default_audio = false;
1117 /* check for default */
1118 for(size_t i_track = 0; i_track < tracks.size(); i_track++)
1120 mkv_track_t *p_tk = tracks[i_track];
1121 es_format_t *p_fmt = &p_tk->fmt;
1122 if( p_fmt->i_cat == VIDEO_ES )
1123 b_has_default_video |=
1124 p_tk->b_enabled && ( p_tk->b_default || p_tk->b_forced );
1125 else if( p_fmt->i_cat == AUDIO_ES )
1126 b_has_default_audio |=
1127 p_tk->b_enabled && ( p_tk->b_default || p_tk->b_forced );
1130 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1132 mkv_track_t *p_tk = tracks[i_track];
1133 es_format_t *p_fmt = &p_tk->fmt;
1135 if( unlikely( p_fmt->i_cat == UNKNOWN_ES || !p_tk->psz_codec ) )
1137 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, p_tk->i_number );
1141 else if( unlikely( !b_has_default_video && p_fmt->i_cat == VIDEO_ES ) )
1143 p_tk->b_default = true;
1144 b_has_default_video = true;
1146 else if( unlikely( !b_has_default_audio && p_fmt->i_cat == AUDIO_ES ) )
1148 p_tk->b_default = true;
1149 b_has_default_audio = true;
1151 if( unlikely( !p_tk->b_enabled ) )
1152 p_tk->fmt.i_priority = ES_PRIORITY_NOT_SELECTABLE;
1153 else if( p_tk->b_forced )
1154 p_tk->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 2;
1155 else if( p_tk->b_default )
1156 p_tk->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN + 1;
1158 p_tk->fmt.i_priority = ES_PRIORITY_SELECTABLE_MIN;
1160 /* Avoid multivideo tracks when unnecessary */
1161 if( p_tk->fmt.i_cat == VIDEO_ES )
1162 p_tk->fmt.i_priority--;
1166 bool matroska_segment_c::Select( mtime_t i_start_time )
1169 msg_Dbg( &sys.demuxer, "found %d es", (int)tracks.size() );
1171 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1173 mkv_track_t *p_tk = tracks[i_track];
1174 es_format_t *p_fmt = &p_tk->fmt;
1176 if( unlikely( p_fmt->i_cat == UNKNOWN_ES || !p_tk->psz_codec ) )
1178 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", (int)i_track, p_tk->i_number );
1184 p_tk->p_es = es_out_Add( sys.demuxer.out, &p_tk->fmt );
1186 /* Turn on a subtitles track if it has been flagged as default -
1187 * but only do this if no subtitles track has already been engaged,
1188 * either by an earlier 'default track' (??) or by default
1189 * language choice behaviour.
1191 if( p_tk->b_default || p_tk->b_forced )
1193 es_out_Control( sys.demuxer.out,
1194 ES_OUT_SET_ES_DEFAULT,
1198 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, i_start_time );
1200 sys.i_start_pts = i_start_time;
1201 // reset the stream reading to the first cluster of the segment used
1202 es.I_O().setFilePointer( i_start_pos );
1205 ep = new EbmlParser( &es, segment, &sys.demuxer );
1210 void matroska_segment_c::UnSelect( )
1212 sys.p_ev->ResetPci();
1213 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
1215 if ( tracks[i_track]->p_es != NULL )
1217 // es_format_Clean( &tracks[i_track]->fmt );
1218 es_out_Del( sys.demuxer.out, tracks[i_track]->p_es );
1219 tracks[i_track]->p_es = NULL;
1226 int matroska_segment_c::BlockGet( KaxBlock * & pp_block, KaxSimpleBlock * & pp_simpleblock, bool *pb_key_picture, bool *pb_discardable_picture, int64_t *pi_duration )
1228 pp_simpleblock = NULL;
1231 *pb_key_picture = true;
1232 *pb_discardable_picture = false;
1238 EbmlElement *el = NULL;
1242 return VLC_EGENERIC;
1244 if( pp_simpleblock != NULL || ((el = ep->Get()) == NULL && pp_block != NULL) )
1246 /* Check blocks validity to protect againts broken files */
1247 if( BlockFindTrackIndex( &i_tk, pp_block , pp_simpleblock ) )
1250 pp_simpleblock = NULL;
1254 if( pp_simpleblock != NULL )
1256 *pb_key_picture = pp_simpleblock->IsKeyframe();
1257 *pb_discardable_picture = pp_simpleblock->IsDiscardable();
1259 /* We have block group let's check if the picture is a keyframe */
1260 else if( *pb_key_picture )
1262 switch(tracks[i_tk]->fmt.i_codec)
1264 case VLC_CODEC_THEORA:
1266 DataBuffer *p_data = &pp_block->GetBuffer(0);
1267 size_t sz = p_data->Size();
1268 const uint8_t * p_buff = p_data->Buffer();
1269 /* if the second bit of a Theora frame is 1
1270 it's not a keyframe */
1273 if( p_buff[0] & 0x40 )
1274 *pb_key_picture = false;
1277 *pb_key_picture = false;
1283 /* update the index */
1284 #define idx p_indexes[i_index - 1]
1285 if( i_index > 0 && idx.i_time == -1 )
1287 if ( pp_simpleblock != NULL )
1288 idx.i_time = pp_simpleblock->GlobalTimecode() / (mtime_t)1000;
1290 idx.i_time = (*pp_block).GlobalTimecode() / (mtime_t)1000;
1291 idx.b_key = *pb_key_picture;
1297 i_level = ep->GetLevel();
1306 msg_Warn( &sys.demuxer, "EOF" );
1307 return VLC_EGENERIC;
1310 /* Verify that we are still inside our cluster
1311 * It can happens whith broken files and when seeking
1315 if( cluster && !ep->IsTopPresent( cluster ) )
1317 msg_Warn( &sys.demuxer, "Unexpected escape from current cluster" );
1330 if( MKV_IS_ID( el, KaxCluster ) )
1332 cluster = (KaxCluster*)el;
1333 i_cluster_pos = cluster->GetElementPosition();
1335 // reset silent tracks
1336 for (size_t i=0; i<tracks.size(); i++)
1338 tracks[i]->b_silent = false;
1343 else if( MKV_IS_ID( el, KaxCues ) )
1345 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1346 return VLC_EGENERIC;
1350 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1354 if( unlikely( el->GetSize() >= SIZE_MAX ) )
1356 msg_Err( &sys.demuxer, "Error while reading %s... upping level", typeid(*el).name());
1360 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1362 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1364 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1365 cluster->InitTimecode( uint64( ctc ), i_timescale );
1367 /* add it to the index */
1370 p_indexes[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1371 IndexAppendCluster( cluster );
1373 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1377 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1379 i_block_pos = el->GetElementPosition();
1382 else if( MKV_IS_ID( el, KaxSimpleBlock ) )
1384 pp_simpleblock = (KaxSimpleBlock*)el;
1386 pp_simpleblock->ReadData( es.I_O() );
1387 pp_simpleblock->SetParent( *cluster );
1391 if( unlikely( el->GetSize() >= SIZE_MAX ) )
1393 msg_Err( &sys.demuxer, "Error while reading %s... upping level", typeid(*el).name());
1396 pp_simpleblock = NULL;
1400 if( MKV_IS_ID( el, KaxBlock ) )
1402 pp_block = (KaxBlock*)el;
1404 pp_block->ReadData( es.I_O() );
1405 pp_block->SetParent( *cluster );
1409 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1411 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1413 dur.ReadData( es.I_O() );
1414 *pi_duration = uint64( dur );
1416 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1418 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1420 ref.ReadData( es.I_O() );
1422 if( *pb_key_picture )
1423 *pb_key_picture = false;
1424 else if( int64( ref ) > 0 )
1425 *pb_discardable_picture = true;
1427 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1429 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1430 track_num.ReadData( es.I_O() );
1432 for (size_t i=0; i<tracks.size(); i++)
1434 if ( tracks[i]->i_number == uint32(track_num))
1436 tracks[i]->b_silent = true;
1441 #if LIBMATROSKA_VERSION >= 0x010401
1442 else if( MKV_IS_ID( el, KaxDiscardPadding ) )
1444 KaxDiscardPadding &dp = *(KaxDiscardPadding*) el;
1445 dp.ReadData( es.I_O() );
1446 if ( *pi_duration < int64(dp) )
1449 *pi_duration -= int64(dp);
1454 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1455 return VLC_EGENERIC;
1460 msg_Err( &sys.demuxer, "Error while reading %s... upping level", typeid(*el).name());
1463 pp_simpleblock = NULL;
1469 SimpleTag::~SimpleTag()
1474 for(size_t i = 0; i < sub_tags.size(); i++)
1480 for(size_t i = 0; i < simple_tags.size(); i++)
1481 delete simple_tags[i];