1 /*****************************************************************************
2 * mkv.cpp : matroska demuxer
3 *****************************************************************************
4 * Copyright (C) 2003-2004 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
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 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 General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
28 #include <stdlib.h> /* malloc(), free() */
33 # include <time.h> /* time() */
36 #include <vlc/input.h>
38 #include <codecs.h> /* BITMAPINFOHEADER, WAVEFORMATEX */
53 /* libebml and matroska */
54 #include "ebml/EbmlHead.h"
55 #include "ebml/EbmlSubHead.h"
56 #include "ebml/EbmlStream.h"
57 #include "ebml/EbmlContexts.h"
58 #include "ebml/EbmlVoid.h"
59 #include "ebml/EbmlVersion.h"
60 #include "ebml/StdIOCallback.h"
62 #include "matroska/KaxAttachments.h"
63 #include "matroska/KaxBlock.h"
64 #include "matroska/KaxBlockData.h"
65 #include "matroska/KaxChapters.h"
66 #include "matroska/KaxCluster.h"
67 #include "matroska/KaxClusterData.h"
68 #include "matroska/KaxContexts.h"
69 #include "matroska/KaxCues.h"
70 #include "matroska/KaxCuesData.h"
71 #include "matroska/KaxInfo.h"
72 #include "matroska/KaxInfoData.h"
73 #include "matroska/KaxSeekHead.h"
74 #include "matroska/KaxSegment.h"
75 #include "matroska/KaxTag.h"
76 #include "matroska/KaxTags.h"
77 #include "matroska/KaxTagMulti.h"
78 #include "matroska/KaxTracks.h"
79 #include "matroska/KaxTrackAudio.h"
80 #include "matroska/KaxTrackVideo.h"
81 #include "matroska/KaxTrackEntryData.h"
82 #include "matroska/KaxContentEncoding.h"
84 #include "ebml/StdIOCallback.h"
87 #include "mp4/libmp4.h"
93 #define MATROSKA_COMPRESSION_NONE 0
94 #define MATROSKA_COMPRESSION_ZLIB 1
96 #define MKVD_TIMECODESCALE 1000000
99 * What's between a directory and a filename?
102 #define DIRECTORY_SEPARATOR '\\'
104 #define DIRECTORY_SEPARATOR '/'
107 using namespace LIBMATROSKA_NAMESPACE;
110 /*****************************************************************************
112 *****************************************************************************/
113 static int Open ( vlc_object_t * );
114 static void Close( vlc_object_t * );
117 set_shortname( _("Matroska") );
118 set_description( _("Matroska stream demuxer" ) );
119 set_capability( "demux2", 50 );
120 set_callbacks( Open, Close );
121 set_category( CAT_INPUT );
122 set_subcategory( SUBCAT_INPUT_DEMUX );
124 add_bool( "mkv-use-ordered-chapters", 1, NULL,
125 N_("Ordered chapters"),
126 N_("Play chapters in the specified order as specified in the file"), VLC_TRUE );
128 add_bool( "mkv-use-chapter-codec", 1, NULL,
129 N_("Chapter codecs"),
130 N_("Use chapter codecs found in the file"), VLC_TRUE );
132 add_bool( "mkv-seek-percent", 0, NULL,
133 N_("Seek based on percent not time"),
134 N_("Seek based on percent not time"), VLC_TRUE );
136 add_shortcut( "mka" );
137 add_shortcut( "mkv" );
140 /*****************************************************************************
142 *****************************************************************************/
144 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
145 int result, dstsize, n;
150 d_stream.zalloc = (alloc_func)0;
151 d_stream.zfree = (free_func)0;
152 d_stream.opaque = (voidpf)0;
153 result = inflateInit(&d_stream);
156 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
160 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
161 d_stream.avail_in = p_in_block->i_buffer;
163 p_block = block_New( p_this, 0 );
168 p_block = block_Realloc( p_block, 0, n * 1000 );
169 dst = (unsigned char *)p_block->p_buffer;
170 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
171 d_stream.avail_out = 1000;
172 result = inflate(&d_stream, Z_NO_FLUSH);
173 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
175 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
179 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
180 ( result != Z_STREAM_END ) );
182 dstsize = d_stream.total_out;
183 inflateEnd( &d_stream );
185 p_block = block_Realloc( p_block, 0, dstsize );
186 p_block->i_buffer = dstsize;
187 block_Release( p_in_block );
194 * Helper function to print the mkv parse tree
196 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
201 msg_Err( &demuxer, "too deep tree" );
204 va_start( args, psz_format );
205 static char *psz_foo = "| | | | | | | | | |";
206 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
207 strncpy( psz_foo2, psz_foo, 4 * i_level );
208 psz_foo2[ 4 * i_level ] = '+';
209 psz_foo2[ 4 * i_level + 1 ] = ' ';
210 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
211 __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
216 /*****************************************************************************
218 *****************************************************************************/
219 class vlc_stream_io_callback: public IOCallback
226 vlc_stream_io_callback( stream_t * );
228 virtual uint32 read ( void *p_buffer, size_t i_size);
229 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
230 virtual size_t write ( const void *p_buffer, size_t i_size);
231 virtual uint64 getFilePointer ( void );
232 virtual void close ( void );
235 /*****************************************************************************
237 *****************************************************************************/
241 EbmlParser( EbmlStream *es, EbmlElement *el_start );
247 EbmlElement *Get( void );
250 int GetLevel( void );
255 EbmlElement *m_el[10];
264 /*****************************************************************************
265 * Some functions to manipulate memory
266 *****************************************************************************/
267 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
268 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
270 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
273 /*****************************************************************************
274 * definitions of structures and functions used by this plugins
275 *****************************************************************************/
278 vlc_bool_t b_default;
279 vlc_bool_t b_enabled;
280 unsigned int i_number;
283 uint8_t *p_extra_data;
287 uint64_t i_default_duration;
288 float f_timecodescale;
296 /* data to be send first */
298 uint8_t *p_data_init;
300 /* hack : it's for seek */
301 vlc_bool_t b_search_keyframe;
305 char *psz_codec_name;
306 char *psz_codec_settings;
307 char *psz_codec_info_url;
308 char *psz_codec_download_url;
310 /* encryption/compression */
311 int i_compression_type;
332 ,i_user_start_time(-1)
335 ,b_display_seekpoint(true)
339 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title );
340 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
342 int64_t i_start_time, i_end_time;
343 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
344 std::vector<chapter_item_t> sub_chapters;
347 bool b_display_seekpoint;
348 std::string psz_name;
349 chapter_item_t *psz_parent;
351 bool operator<( const chapter_item_t & item ) const
353 return ( i_user_start_time < item.i_user_start_time || (i_user_start_time == item.i_user_start_time && i_user_end_time < item.i_user_end_time) );
361 class chapter_edition_t
369 void RefreshChapters( input_title_t & title );
370 double Duration() const;
371 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
373 std::vector<chapter_item_t> chapters;
380 class matroska_segment_t
383 matroska_segment_t( demux_sys_t & demuxer, EbmlStream & estream )
386 ,i_timescale(MKVD_TIMECODESCALE)
390 ,i_chapters_position(-1)
397 ,psz_muxing_application(NULL)
398 ,psz_writing_application(NULL)
399 ,psz_segment_filename(NULL)
402 ,i_current_edition(-1)
403 ,psz_current_chapter(NULL)
408 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
411 ~matroska_segment_t()
413 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
415 #define tk tracks[i_track]
416 if( tk->fmt.psz_description )
418 free( tk->fmt.psz_description );
422 free( tk->psz_codec );
424 if( tk->fmt.psz_language )
426 free( tk->fmt.psz_language );
432 if( psz_writing_application )
434 free( psz_writing_application );
436 if( psz_muxing_application )
438 free( psz_muxing_application );
440 if( psz_segment_filename )
442 free( psz_segment_filename );
450 free( psz_date_utc );
462 uint64_t i_timescale;
464 /* duration of the segment */
469 std::vector<mkv_track_t*> tracks;
472 int64_t i_cues_position;
473 int64_t i_chapters_position;
474 int64_t i_tags_position;
478 KaxSegmentUID segment_uid;
479 KaxPrevUID prev_segment_uid;
480 KaxNextUID next_segment_uid;
488 char *psz_muxing_application;
489 char *psz_writing_application;
490 char *psz_segment_filename;
494 std::vector<chapter_edition_t> editions;
495 int i_current_edition;
496 const chapter_item_t *psz_current_chapter;
498 std::vector<KaxSegmentFamily> families;
504 inline chapter_edition_t *Edition()
506 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
507 return &editions[i_current_edition];
512 bool PreloadFamily( const matroska_segment_t & segment );
513 void ParseInfo( EbmlElement *info );
514 void ParseChapters( EbmlElement *chapters );
515 void ParseSeekHead( EbmlElement *seekhead );
516 void ParseTracks( EbmlElement *tracks );
517 void ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters );
518 void ParseTrackEntry( EbmlMaster *m );
519 void ParseCluster( );
520 void IndexAppendCluster( KaxCluster *cluster );
523 void InformationCreate( );
524 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
525 bool Select( mtime_t i_start_time );
527 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
530 // class holding hard-linked segment together in the playback order
531 class virtual_segment_t
534 virtual_segment_t( matroska_segment_t *p_segment )
535 :i_current_segment(0)
537 linked_segments.push_back( p_segment );
539 AppendUID( p_segment->segment_uid );
540 AppendUID( p_segment->prev_segment_uid );
541 AppendUID( p_segment->next_segment_uid );
545 size_t AddSegment( matroska_segment_t *p_segment );
546 void PreloadLinked( );
547 float Duration( ) const;
550 matroska_segment_t * Segment() const
552 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
554 return linked_segments[i_current_segment];
559 if ( i_current_segment < linked_segments.size()-1 )
568 std::vector<matroska_segment_t*> linked_segments;
569 std::vector<const KaxSegmentUID> linked_uids;
570 size_t i_current_segment;
572 void AppendUID( const EbmlBinary & UID );
575 class matroska_stream_t
578 matroska_stream_t( demux_sys_t & demuxer )
593 std::vector<matroska_segment_t*> segments;
597 void PreloadFamily( const matroska_segment_t & segment );
603 demux_sys_t( demux_t & demux )
610 ,p_current_segment(NULL)
616 for (size_t i=0; i<streams.size(); i++)
618 for ( size_t i=0; i<opened_segments.size(); i++ )
619 delete opened_segments[i];
627 mtime_t i_chapter_time;
631 input_title_t *title;
633 std::vector<matroska_stream_t*> streams;
634 std::vector<matroska_segment_t*> opened_segments;
635 virtual_segment_t *p_current_segment;
637 /* duration of the stream */
640 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
641 void PreloadFamily( );
642 void PreloadLinked( matroska_segment_t *p_segment );
643 void PreparePlayback( );
644 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
647 static int Demux ( demux_t * );
648 static int Control( demux_t *, int, va_list );
649 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
651 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
653 static char *UTF8ToStr ( const UTFstring &u );
655 /*****************************************************************************
656 * Open: initializes matroska demux structures
657 *****************************************************************************/
658 static int Open( vlc_object_t * p_this )
660 demux_t *p_demux = (demux_t*)p_this;
662 matroska_stream_t *p_stream;
663 matroska_segment_t *p_segment;
665 std::string s_path, s_filename;
666 vlc_stream_io_callback *p_io_callback;
667 EbmlStream *p_io_stream;
669 /* peek the begining */
670 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
672 /* is a valid file */
673 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
674 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
676 /* Set the demux function */
677 p_demux->pf_demux = Demux;
678 p_demux->pf_control = Control;
679 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
681 p_io_callback = new vlc_stream_io_callback( p_demux->s );
682 p_io_stream = new EbmlStream( *p_io_callback );
684 if( p_io_stream == NULL )
686 msg_Err( p_demux, "failed to create EbmlStream" );
687 delete p_io_callback;
692 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
693 if( p_stream == NULL )
695 msg_Err( p_demux, "cannot find KaxSegment" );
698 p_sys->streams.push_back( p_stream );
700 p_stream->p_in = p_io_callback;
701 p_stream->p_es = p_io_stream;
703 for (size_t i=0; i<p_stream->segments.size(); i++)
705 p_stream->segments[i]->Preload();
708 p_segment = p_stream->segments[0];
709 if( p_segment->cluster == NULL )
711 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
714 // reset the stream reading to the first cluster of the segment used
715 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
717 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
718 /* TODO handle multi-segment files */
719 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
721 // assume it's a regular file
722 // get the directory path
723 s_path = p_demux->psz_path;
724 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
726 s_path = s_path.substr(0,s_path.length()-1);
730 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
732 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
736 struct dirent *p_file_item;
737 DIR *p_src_dir = opendir(s_path.c_str());
739 if (p_src_dir != NULL)
741 while ((p_file_item = (dirent *) readdir(p_src_dir)))
743 if (strlen(p_file_item->d_name) > 4)
745 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
747 if (!s_filename.compare(p_demux->psz_path))
748 continue; // don't reuse the original opened file
750 #if defined(__GNUC__) && (__GNUC__ < 3)
751 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
752 !s_filename.compare("mka", s_filename.length() - 3, 3))
754 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
755 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
758 // test wether this file belongs to the our family
759 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
760 EbmlStream *p_estream = new EbmlStream(*p_file_io);
762 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
763 if ( p_stream == NULL )
765 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
771 p_stream->p_in = p_file_io;
772 p_stream->p_es = p_estream;
773 p_sys->streams.push_back( p_stream );
778 closedir( p_src_dir );
782 p_sys->PreloadFamily( );
783 p_sys->PreloadLinked( p_segment );
784 p_sys->PreparePlayback( );
786 if( !p_segment->b_cues || p_segment->i_index <= 0 )
788 msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
790 p_segment->IndexAppendCluster( p_segment->cluster );
792 p_segment->b_cues = VLC_FALSE;
795 /* add information */
796 p_segment->InformationCreate( );
798 if ( !p_segment->Select( 0 ) )
800 msg_Err( p_demux, "cannot use the segment" );
811 /*****************************************************************************
812 * Close: frees unused data
813 *****************************************************************************/
814 static void Close( vlc_object_t *p_this )
816 demux_t *p_demux = (demux_t*)p_this;
817 demux_sys_t *p_sys = p_demux->p_sys;
822 /*****************************************************************************
824 *****************************************************************************/
825 static int Control( demux_t *p_demux, int i_query, va_list args )
827 demux_sys_t *p_sys = p_demux->p_sys;
828 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
833 vlc_meta_t **pp_meta;
838 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
839 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
842 case DEMUX_GET_LENGTH:
843 pi64 = (int64_t*)va_arg( args, int64_t * );
844 if( p_sys->f_duration > 0.0 )
846 *pi64 = (int64_t)(p_sys->f_duration * 1000);
851 case DEMUX_GET_POSITION:
852 pf = (double*)va_arg( args, double * );
853 if ( p_sys->f_duration > 0.0 )
854 *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
857 case DEMUX_SET_POSITION:
858 f = (double)va_arg( args, double );
859 Seek( p_demux, -1, f, NULL );
863 pi64 = (int64_t*)va_arg( args, int64_t * );
864 *pi64 = p_sys->i_pts;
867 case DEMUX_GET_TITLE_INFO:
868 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
870 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
871 int *pi_int = (int*)va_arg( args, int* );
874 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
876 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
882 case DEMUX_SET_TITLE:
883 /* TODO handle editions as titles & DVD titles as well */
884 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
890 case DEMUX_SET_SEEKPOINT:
891 /* FIXME do a better implementation */
892 i_skp = (int)va_arg( args, int );
894 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
896 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
897 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
898 p_demux->info.i_seekpoint = i_skp;
910 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
921 if( sys.demuxer.b_die )
927 i_level = ep->GetLevel();
929 if( el == NULL && *pp_block != NULL )
931 /* update the index */
932 #define idx index[i_index - 1]
933 if( i_index > 0 && idx.i_time == -1 )
935 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
936 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
944 if( ep->GetLevel() > 1 )
949 msg_Warn( &sys.demuxer, "EOF" );
956 if( MKV_IS_ID( el, KaxCluster ) )
958 cluster = (KaxCluster*)el;
960 /* add it to the index */
962 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
964 IndexAppendCluster( cluster );
967 // reset silent tracks
968 for (size_t i=0; i<tracks.size(); i++)
970 tracks[i]->b_silent = VLC_FALSE;
975 else if( MKV_IS_ID( el, KaxCues ) )
977 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
982 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
985 else if( i_level == 2 )
987 if( MKV_IS_ID( el, KaxClusterTimecode ) )
989 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
991 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
992 cluster->InitTimecode( uint64( ctc ), i_timescale );
994 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
998 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1003 else if( i_level == 3 )
1005 if( MKV_IS_ID( el, KaxBlock ) )
1007 *pp_block = (KaxBlock*)el;
1009 (*pp_block)->ReadData( es.I_O() );
1010 (*pp_block)->SetParent( *cluster );
1014 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1016 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1018 dur.ReadData( es.I_O() );
1019 *pi_duration = uint64( dur );
1021 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1023 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1025 ref.ReadData( es.I_O() );
1026 if( *pi_ref1 == -1 )
1028 *pi_ref1 = int64( ref );
1032 *pi_ref2 = int64( ref );
1035 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1037 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1038 track_num.ReadData( es.I_O() );
1040 for (size_t i=0; i<tracks.size(); i++)
1042 if ( tracks[i]->i_number == uint32(track_num))
1044 tracks[i]->b_silent = VLC_TRUE;
1052 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1053 return VLC_EGENERIC;
1058 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1061 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1062 memcpy( p_block->p_buffer, p_mem, i_mem );
1063 //p_block->i_rate = p_input->stream.control.i_rate;
1067 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1068 mtime_t i_duration )
1070 demux_sys_t *p_sys = p_demux->p_sys;
1071 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1077 #define tk p_segment->tracks[i_track]
1078 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1080 if( tk->i_number == block->TrackNum() )
1086 if( i_track >= p_segment->tracks.size() )
1088 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1091 if( tk->p_es == NULL )
1093 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1096 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1098 return; /* discard audio packets that shouldn't be rendered */
1101 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1104 tk->b_inited = VLC_FALSE;
1108 /* First send init data */
1109 if( !tk->b_inited && tk->i_data_init > 0 )
1113 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1114 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1115 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1117 tk->b_inited = VLC_TRUE;
1120 for( i = 0; i < block->NumberFrames(); i++ )
1123 DataBuffer &data = block->GetBuffer(i);
1125 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1127 if( p_block == NULL )
1132 #if defined(HAVE_ZLIB_H)
1133 if( tk->i_compression_type )
1135 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1139 // TODO implement correct timestamping when B frames are used
1140 if( tk->fmt.i_cat != VIDEO_ES )
1142 p_block->i_dts = p_block->i_pts = i_pts;
1146 p_block->i_dts = i_pts;
1150 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1152 p_block->i_length = i_duration * 1000;
1154 msg_Warn( p_demux, "Sending block %d", p_block );
1155 es_out_Send( p_demux->out, tk->p_es, p_block );
1157 /* use time stamp only for first block */
1164 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1166 int i_upper_lvl = 0;
1168 EbmlElement *p_l0, *p_l1, *p_l2;
1169 bool b_keep_stream = false, b_keep_segment;
1171 // verify the EBML Header
1172 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1177 p_l0->SkipData(*p_estream, EbmlHead_Context);
1180 // find all segments in this file
1181 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1187 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1191 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1194 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1195 b_keep_segment = false;
1197 ep = new EbmlParser(p_estream, p_l0);
1198 p_segment1->ep = ep;
1199 p_segment1->segment = (KaxSegment*)p_l0;
1201 while ((p_l1 = ep->Get()))
1203 if (MKV_IS_ID(p_l1, KaxInfo))
1205 // find the families of this segment
1206 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1208 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1209 for( i = 0; i < p_info->ListSize(); i++ )
1211 EbmlElement *l = (*p_info)[i];
1213 if( MKV_IS_ID( l, KaxSegmentUID ) )
1215 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1216 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1217 if ( !b_keep_segment )
1218 break; // this segment is already known
1219 opened_segments.push_back( p_segment1 );
1220 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1222 else if( MKV_IS_ID( l, KaxPrevUID ) )
1224 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1226 else if( MKV_IS_ID( l, KaxNextUID ) )
1228 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1230 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1232 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1233 std::vector<KaxSegmentFamily>::iterator iter;
1234 p_segment1->families.push_back( *p_fam );
1240 if ( b_keep_segment )
1242 b_keep_stream = true;
1243 p_stream1->segments.push_back( p_segment1 );
1249 p_l0->SkipData(*p_estream, EbmlHead_Context);
1250 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1253 if ( !b_keep_stream )
1262 bool matroska_segment_t::Select( mtime_t i_start_time )
1267 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1268 for( i_track = 0; i_track < tracks.size(); i_track++ )
1270 #define tk tracks[i_track]
1271 if( tk->fmt.i_cat == UNKNOWN_ES )
1273 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1278 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1280 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1282 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1283 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1287 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1289 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1290 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1291 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1293 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1294 if( tk->fmt.i_extra > 0 )
1296 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1297 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1301 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1302 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1304 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1306 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1308 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1310 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1312 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1314 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1315 tk->fmt.b_packetized = VLC_FALSE;
1316 tk->fmt.i_extra = tk->i_extra_data;
1317 tk->fmt.p_extra = malloc( tk->i_extra_data );
1318 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1322 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1325 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1327 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1328 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1331 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1332 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1333 tk->fmt.i_codec = p_box->i_type;
1334 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1335 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1336 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1337 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1338 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1339 MP4_FreeBox_sample_vide( p_box );
1340 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1342 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1344 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1346 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1347 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1351 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1353 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1355 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1356 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1357 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1358 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1359 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1361 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1362 if( tk->fmt.i_extra > 0 )
1364 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1365 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1369 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1370 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1371 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1373 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1375 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1377 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1379 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1381 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1383 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1385 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1386 tk->fmt.i_extra = tk->i_extra_data;
1387 tk->fmt.p_extra = malloc( tk->i_extra_data );
1388 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1390 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1392 int i, i_offset = 1, i_size[3], i_extra;
1395 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1397 /* Split the 3 headers */
1398 if( tk->p_extra_data[0] != 0x02 )
1399 msg_Err( &sys.demuxer, "invalid vorbis header" );
1401 for( i = 0; i < 2; i++ )
1404 while( i_offset < tk->i_extra_data )
1406 i_size[i] += tk->p_extra_data[i_offset];
1407 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1411 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1412 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1413 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1415 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1416 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1417 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1418 for( i = 0; i < 3; i++ )
1420 *(p_extra++) = i_size[i] >> 8;
1421 *(p_extra++) = i_size[i] & 0xFF;
1422 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1424 p_extra += i_size[i];
1425 i_extra += i_size[i];
1428 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1429 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1431 int i_profile, i_srate;
1432 static unsigned int i_sample_rates[] =
1434 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1435 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1438 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1439 /* create data for faad (MP4DecSpecificDescrTag)*/
1441 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1445 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1449 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1458 for( i_srate = 0; i_srate < 13; i_srate++ )
1460 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1465 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1467 tk->fmt.i_extra = 2;
1468 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1469 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1470 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1472 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1473 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1474 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1476 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1478 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1482 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1484 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1486 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1488 /* FIXME: support this codec */
1489 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1490 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1492 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1494 /* FIXME: support this codec */
1495 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1496 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1498 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1500 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1501 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1503 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1504 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1505 !strcmp( tk->psz_codec, "S_SSA" ) ||
1506 !strcmp( tk->psz_codec, "S_ASS" ))
1508 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1509 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1511 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1513 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1514 if( tk->i_extra_data )
1517 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1518 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1519 p_buf[tk->i_extra_data] = '\0';
1521 p_start = strstr( p_buf, "size:" );
1522 if( sscanf( p_start, "size: %dx%d",
1523 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1525 msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d", tk->fmt.subs.spu.i_original_frame_width, tk->fmt.subs.spu.i_original_frame_height );
1529 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1534 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1536 /* FIXME: support this codec */
1537 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1538 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1542 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1543 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1547 tk->fmt.i_priority = 1000;
1550 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1552 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1556 sys.i_start_pts = i_start_time;
1559 // reset the stream reading to the first cluster of the segment used
1560 es.I_O().setFilePointer( i_start_pos );
1565 void matroska_segment_t::UnSelect( )
1569 for( i_track = 0; i_track < tracks.size(); i_track++ )
1571 #define tk tracks[i_track]
1572 if ( tk->p_es != NULL )
1574 es_out_Del( sys.demuxer.out, tk->p_es );
1581 static void UpdateCurrentToChapter( demux_t & demux )
1583 demux_sys_t & sys = *demux.p_sys;
1584 matroska_segment_t *p_segment = sys.p_current_segment->Segment();
1585 const chapter_item_t *psz_curr_chapter;
1587 /* update current chapter/seekpoint */
1588 if ( p_segment->editions.size())
1590 /* 1st, we need to know in which chapter we are */
1591 psz_curr_chapter = p_segment->editions[p_segment->i_current_edition].FindTimecode( sys.i_pts );
1593 /* we have moved to a new chapter */
1594 if (p_segment->psz_current_chapter != NULL && psz_curr_chapter != NULL && p_segment->psz_current_chapter != psz_curr_chapter)
1596 if (p_segment->psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1598 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1599 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1602 if (p_segment->editions[p_segment->i_current_edition].b_ordered )
1604 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1605 if (p_segment->psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1606 Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
1607 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1608 /* only seek after each duration >= end timecode of the current chapter */
1611 // p_segment->i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1612 // p_segment->i_start_pts = psz_curr_chapter->i_user_start_time;
1614 p_segment->psz_current_chapter = psz_curr_chapter;
1618 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
1620 demux_sys_t *p_sys = p_demux->p_sys;
1621 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1622 mtime_t i_time_offset = 0;
1625 int64_t i_block_duration;
1626 int64_t i_block_ref1;
1627 int64_t i_block_ref2;
1630 int i_track_skipping;
1633 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1634 if( i_date < 0 && f_percent < 0 )
1636 msg_Warn( p_demux, "cannot seek nowhere !" );
1639 if( f_percent > 1.0 )
1641 msg_Warn( p_demux, "cannot seek so far !" );
1645 delete p_segment->ep;
1646 p_segment->ep = new EbmlParser( &p_segment->es, p_segment->segment );
1647 p_segment->cluster = NULL;
1649 /* seek without index or without date */
1650 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1652 if (p_sys->f_duration >= 0)
1654 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1658 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1660 msg_Dbg( p_demux, "inacurate way of seeking" );
1661 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1663 if( p_segment->index[i_index].i_position >= i_pos)
1668 if( i_index == p_segment->i_index )
1673 i_date = p_segment->index[i_index].i_time;
1676 if( p_segment->index[i_index].i_position < i_pos )
1680 msg_Warn( p_demux, "searching for cluster, could take some time" );
1682 /* search a cluster */
1683 while( ( el = p_sys->ep->Get() ) != NULL )
1685 if( MKV_IS_ID( el, KaxCluster ) )
1687 KaxCluster *cluster = (KaxCluster*)el;
1689 /* add it to the index */
1690 p_segment->IndexAppendCluster( cluster );
1692 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1694 p_sys->cluster = cluster;
1705 // find the actual time for an ordered edition
1706 if ( psz_chapter == NULL )
1708 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered )
1710 /* 1st, we need to know in which chapter we are */
1711 psz_chapter = p_segment->editions[p_segment->i_current_edition].FindTimecode( i_date );
1715 if ( psz_chapter != NULL )
1717 p_segment->psz_current_chapter = psz_chapter;
1718 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
1719 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1720 p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
1723 for( ; i_index < p_segment->i_index; i_index++ )
1725 if( p_segment->index[i_index].i_time + i_time_offset > i_date )
1736 msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1737 p_segment->index[i_index].i_time,
1738 (int)( 100 * p_segment->index[i_index].i_position /
1739 stream_Size( p_demux->s ) ) );
1741 p_segment->es.I_O().setFilePointer( p_segment->index[i_index].i_position,
1744 p_sys->i_start_pts = i_date;
1746 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1748 /* now parse until key frame */
1749 #define tk p_segment->tracks[i_track]
1750 i_track_skipping = 0;
1751 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1753 if( tk->fmt.i_cat == VIDEO_ES )
1755 tk->b_search_keyframe = VLC_TRUE;
1758 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
1762 while( i_track_skipping > 0 )
1764 if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1766 msg_Warn( p_demux, "cannot get block EOF?" );
1771 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1773 if( tk->i_number == block->TrackNum() )
1779 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1781 if( i_track < p_segment->tracks.size() )
1783 if( p_sys->i_pts >= p_sys->i_start_pts )
1785 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1786 i_track_skipping = 0;
1788 else if( tk->fmt.i_cat == VIDEO_ES )
1790 if( i_block_ref1 == -1 && tk->b_search_keyframe )
1792 tk->b_search_keyframe = VLC_FALSE;
1795 if( !tk->b_search_keyframe )
1797 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1807 /*****************************************************************************
1808 * Demux: reads and demuxes data packets
1809 *****************************************************************************
1810 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1811 *****************************************************************************/
1812 static int Demux( demux_t *p_demux)
1814 demux_sys_t *p_sys = p_demux->p_sys;
1815 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1816 if ( p_segment == NULL ) return 0;
1817 int i_block_count = 0;
1820 int64_t i_block_duration;
1821 int64_t i_block_ref1;
1822 int64_t i_block_ref2;
1826 if( p_sys->i_pts >= p_sys->i_start_pts )
1827 UpdateCurrentToChapter( *p_demux );
1829 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered && p_segment->psz_current_chapter == NULL )
1831 /* nothing left to read in this ordered edition */
1832 if ( !p_sys->p_current_segment->SelectNext() )
1834 p_segment->UnSelect( );
1836 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1838 /* switch to the next segment */
1839 p_segment = p_sys->p_current_segment->Segment();
1840 if ( !p_segment->Select( 0 ) )
1842 msg_Err( p_demux, "Failed to select new segment" );
1848 if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1850 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered )
1852 // check if there are more chapters to read
1853 if ( p_segment->psz_current_chapter != NULL )
1855 p_sys->i_pts = p_segment->psz_current_chapter->i_user_end_time;
1861 msg_Warn( p_demux, "cannot get block EOF?" );
1862 p_segment->UnSelect( );
1864 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1866 /* switch to the next segment */
1867 if ( !p_sys->p_current_segment->SelectNext() )
1868 // no more segments in this stream
1870 p_segment = p_sys->p_current_segment->Segment();
1871 if ( !p_segment->Select( 0 ) )
1873 msg_Err( p_demux, "Failed to select new segment" );
1880 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1882 if( p_sys->i_pts >= p_sys->i_start_pts )
1884 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1887 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1892 // TODO optimize when there is need to leave or when seeking has been called
1893 if( i_block_count > 5 )
1902 /*****************************************************************************
1904 *****************************************************************************/
1905 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1911 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1913 if( i_size <= 0 || mb_eof )
1918 return stream_Read( s, p_buffer, i_size );
1920 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1926 case seek_beginning:
1930 i_pos = stream_Size( s ) - i_offset;
1933 i_pos= stream_Tell( s ) + i_offset;
1937 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1944 if( stream_Seek( s, i_pos ) )
1950 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1954 uint64 vlc_stream_io_callback::getFilePointer( void )
1956 return stream_Tell( s );
1958 void vlc_stream_io_callback::close( void )
1964 /*****************************************************************************
1965 * Ebml Stream parser
1966 *****************************************************************************/
1967 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1975 for( i = 1; i < 6; i++ )
1981 mb_keep = VLC_FALSE;
1984 EbmlParser::~EbmlParser( void )
1988 for( i = 1; i < mi_level; i++ )
1994 mb_keep = VLC_FALSE;
1998 void EbmlParser::Up( void )
2000 if( mi_user_level == mi_level )
2002 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2008 void EbmlParser::Down( void )
2014 void EbmlParser::Keep( void )
2019 int EbmlParser::GetLevel( void )
2021 return mi_user_level;
2024 void EbmlParser::Reset( void )
2026 while ( mi_level > 0)
2028 delete m_el[mi_level];
2029 m_el[mi_level] = NULL;
2032 mi_user_level = mi_level = 1;
2033 #if LIBEBML_VERSION >= 0x000704
2034 // a little faster and cleaner
2035 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2037 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2041 EbmlElement *EbmlParser::Get( void )
2045 if( mi_user_level != mi_level )
2051 EbmlElement *ret = m_got;
2057 if( m_el[mi_level] )
2059 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2062 delete m_el[mi_level];
2064 mb_keep = VLC_FALSE;
2067 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
2078 delete m_el[mi_level - 1];
2079 m_got = m_el[mi_level -1] = m_el[mi_level];
2080 m_el[mi_level] = NULL;
2087 else if( m_el[mi_level] == NULL )
2089 fprintf( stderr," m_el[mi_level] == NULL\n" );
2092 return m_el[mi_level];
2096 /*****************************************************************************
2098 * * LoadCues : load the cues element and update index
2100 * * LoadTags : load ... the tags element
2102 * * InformationCreate : create all information, load tags if present
2104 *****************************************************************************/
2105 void matroska_segment_t::LoadCues( )
2107 int64_t i_sav_position = es.I_O().getFilePointer();
2109 EbmlElement *el, *cues;
2111 /* *** Load the cue if found *** */
2112 if( i_cues_position < 0 )
2115 vlc_bool_t b_seekable;
2117 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2121 msg_Dbg( &sys.demuxer, "loading cues" );
2122 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2123 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2127 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2128 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2132 ep = new EbmlParser( &es, cues );
2133 while( ( el = ep->Get() ) != NULL )
2135 if( MKV_IS_ID( el, KaxCuePoint ) )
2137 #define idx index[i_index]
2140 idx.i_block_number= -1;
2141 idx.i_position = -1;
2143 idx.b_key = VLC_TRUE;
2146 while( ( el = ep->Get() ) != NULL )
2148 if( MKV_IS_ID( el, KaxCueTime ) )
2150 KaxCueTime &ctime = *(KaxCueTime*)el;
2152 ctime.ReadData( es.I_O() );
2154 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2156 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2159 while( ( el = ep->Get() ) != NULL )
2161 if( MKV_IS_ID( el, KaxCueTrack ) )
2163 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2165 ctrack.ReadData( es.I_O() );
2166 idx.i_track = uint16( ctrack );
2168 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2170 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2172 ccpos.ReadData( es.I_O() );
2173 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2175 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2177 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2179 cbnum.ReadData( es.I_O() );
2180 idx.i_block_number = uint32( cbnum );
2184 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2191 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2197 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2198 " track=%d bnum=%d", idx.i_time, idx.i_position,
2199 idx.i_track, idx.i_block_number );
2203 if( i_index >= i_index_max )
2205 i_index_max += 1024;
2206 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2212 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2220 msg_Dbg( &sys.demuxer, "loading cues done." );
2221 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2224 void matroska_segment_t::LoadTags( )
2226 int64_t i_sav_position = es.I_O().getFilePointer();
2228 EbmlElement *el, *tags;
2230 msg_Dbg( &sys.demuxer, "loading tags" );
2231 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2232 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2236 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2237 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2241 msg_Dbg( &sys.demuxer, "Tags" );
2242 ep = new EbmlParser( &es, tags );
2243 while( ( el = ep->Get() ) != NULL )
2245 if( MKV_IS_ID( el, KaxTag ) )
2247 msg_Dbg( &sys.demuxer, "+ Tag" );
2249 while( ( el = ep->Get() ) != NULL )
2251 if( MKV_IS_ID( el, KaxTagTargets ) )
2253 msg_Dbg( &sys.demuxer, "| + Targets" );
2255 while( ( el = ep->Get() ) != NULL )
2257 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2261 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2263 msg_Dbg( &sys.demuxer, "| + General" );
2265 while( ( el = ep->Get() ) != NULL )
2267 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2271 else if( MKV_IS_ID( el, KaxTagGenres ) )
2273 msg_Dbg( &sys.demuxer, "| + Genres" );
2275 while( ( el = ep->Get() ) != NULL )
2277 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2281 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2283 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2285 while( ( el = ep->Get() ) != NULL )
2287 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2291 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2293 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2295 while( ( el = ep->Get() ) != NULL )
2297 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2301 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2303 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2305 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2307 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2309 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2311 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2313 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2315 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2317 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2319 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2321 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2323 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2325 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2327 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2331 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2338 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2344 msg_Dbg( &sys.demuxer, "loading tags done." );
2345 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2348 /*****************************************************************************
2350 *****************************************************************************/
2351 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2356 int i_upper_level = 0;
2358 msg_Dbg( &sys.demuxer, "| + Seek head" );
2360 /* Master elements */
2361 m = static_cast<EbmlMaster *>(seekhead);
2362 m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2364 for( i = 0; i < m->ListSize(); i++ )
2366 EbmlElement *l = (*m)[i];
2368 if( MKV_IS_ID( l, KaxSeek ) )
2370 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2371 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2376 for( j = 0; j < sk->ListSize(); j++ )
2378 EbmlElement *l = (*sk)[j];
2380 if( MKV_IS_ID( l, KaxSeekID ) )
2382 KaxSeekID &sid = *(KaxSeekID*)l;
2383 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2385 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2387 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2388 i_pos = uint64( spos );
2392 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2398 if( id == KaxCues::ClassInfos.GlobalId )
2400 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2401 i_cues_position = segment->GetGlobalPosition( i_pos );
2403 else if( id == KaxChapters::ClassInfos.GlobalId )
2405 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2406 i_chapters_position = segment->GetGlobalPosition( i_pos );
2408 else if( id == KaxTags::ClassInfos.GlobalId )
2410 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2411 i_tags_position = segment->GetGlobalPosition( i_pos );
2417 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2422 /*****************************************************************************
2424 *****************************************************************************/
2425 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2431 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2433 tk = new mkv_track_t();
2434 tracks.push_back( tk );
2436 /* Init the track */
2437 memset( tk, 0, sizeof( mkv_track_t ) );
2439 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2440 tk->fmt.psz_language = strdup("English");
2441 tk->fmt.psz_description = NULL;
2443 tk->b_default = VLC_TRUE;
2444 tk->b_enabled = VLC_TRUE;
2445 tk->b_silent = VLC_FALSE;
2446 tk->i_number = tracks.size() - 1;
2447 tk->i_extra_data = 0;
2448 tk->p_extra_data = NULL;
2449 tk->psz_codec = NULL;
2450 tk->i_default_duration = 0;
2451 tk->f_timecodescale = 1.0;
2453 tk->b_inited = VLC_FALSE;
2454 tk->i_data_init = 0;
2455 tk->p_data_init = NULL;
2457 tk->psz_codec_name = NULL;
2458 tk->psz_codec_settings = NULL;
2459 tk->psz_codec_info_url = NULL;
2460 tk->psz_codec_download_url = NULL;
2462 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2464 for( i = 0; i < m->ListSize(); i++ )
2466 EbmlElement *l = (*m)[i];
2468 if( MKV_IS_ID( l, KaxTrackNumber ) )
2470 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2472 tk->i_number = uint32( tnum );
2473 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2475 else if( MKV_IS_ID( l, KaxTrackUID ) )
2477 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2479 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2481 else if( MKV_IS_ID( l, KaxTrackType ) )
2484 KaxTrackType &ttype = *(KaxTrackType*)l;
2486 switch( uint8(ttype) )
2490 tk->fmt.i_cat = AUDIO_ES;
2494 tk->fmt.i_cat = VIDEO_ES;
2496 case track_subtitle:
2497 psz_type = "subtitle";
2498 tk->fmt.i_cat = SPU_ES;
2501 psz_type = "unknown";
2502 tk->fmt.i_cat = UNKNOWN_ES;
2506 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2508 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2510 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2512 // tk->b_enabled = uint32( fenb );
2513 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2514 // uint32( fenb ) );
2516 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2518 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2520 tk->b_default = uint32( fdef );
2521 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2523 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2525 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2527 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2529 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2531 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2533 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2535 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2537 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2539 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2541 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2543 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2545 tk->i_default_duration = uint64(defd);
2546 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2548 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2550 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2552 tk->f_timecodescale = float( ttcs );
2553 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2555 else if( MKV_IS_ID( l, KaxTrackName ) )
2557 KaxTrackName &tname = *(KaxTrackName*)l;
2559 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2560 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2562 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2564 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2566 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2567 msg_Dbg( &sys.demuxer,
2568 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2570 else if( MKV_IS_ID( l, KaxCodecID ) )
2572 KaxCodecID &codecid = *(KaxCodecID*)l;
2574 tk->psz_codec = strdup( string( codecid ).c_str() );
2575 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2577 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2579 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2581 tk->i_extra_data = cpriv.GetSize();
2582 if( tk->i_extra_data > 0 )
2584 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2585 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2587 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2589 else if( MKV_IS_ID( l, KaxCodecName ) )
2591 KaxCodecName &cname = *(KaxCodecName*)l;
2593 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2594 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2596 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2598 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2599 MkvTree( sys.demuxer, 3, "Content Encodings" );
2600 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2602 EbmlElement *l2 = (*cencs)[i];
2603 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2605 MkvTree( sys.demuxer, 4, "Content Encoding" );
2606 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2607 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2609 EbmlElement *l3 = (*cenc)[i];
2610 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2612 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2613 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2615 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2617 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2618 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2620 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2622 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2623 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2625 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2627 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2628 MkvTree( sys.demuxer, 5, "Content Compression" );
2629 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2631 EbmlElement *l4 = (*compr)[i];
2632 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2634 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2635 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2636 if( uint32( compalg ) == 0 )
2638 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2643 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2650 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2657 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2662 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2664 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2666 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2667 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2669 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2671 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2673 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2674 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2676 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2678 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2680 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2681 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2683 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2685 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2687 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2689 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2691 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2693 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2695 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2697 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2700 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2703 for( j = 0; j < tkv->ListSize(); j++ )
2705 EbmlElement *l = (*tkv)[j];
2706 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2708 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2710 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2712 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2714 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2716 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2719 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2721 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2723 tk->fmt.video.i_width = uint16( vwidth );
2724 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2726 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2728 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2730 tk->fmt.video.i_height = uint16( vheight );
2731 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2733 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2735 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2737 tk->fmt.video.i_visible_width = uint16( vwidth );
2738 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2740 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2742 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2744 tk->fmt.video.i_visible_height = uint16( vheight );
2745 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2747 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2749 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2751 tk->f_fps = float( vfps );
2752 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2754 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2756 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2758 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2759 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2761 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2763 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2765 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2767 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2769 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2771 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2775 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2778 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2779 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2781 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2783 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2786 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2788 for( j = 0; j < tka->ListSize(); j++ )
2790 EbmlElement *l = (*tka)[j];
2792 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2794 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2796 tk->fmt.audio.i_rate = (int)float( afreq );
2797 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2799 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2801 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2803 tk->fmt.audio.i_channels = uint8( achan );
2804 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2806 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2808 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2810 tk->fmt.audio.i_bitspersample = uint8( abits );
2811 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2815 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2821 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2822 typeid(*l).name() );
2827 /*****************************************************************************
2829 *****************************************************************************/
2830 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2835 int i_upper_level = 0;
2837 msg_Dbg( &sys.demuxer, "| + Tracks" );
2839 /* Master elements */
2840 m = static_cast<EbmlMaster *>(tracks);
2841 m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2843 for( i = 0; i < m->ListSize(); i++ )
2845 EbmlElement *l = (*m)[i];
2847 if( MKV_IS_ID( l, KaxTrackEntry ) )
2849 ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2853 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2858 /*****************************************************************************
2860 *****************************************************************************/
2861 void matroska_segment_t::ParseInfo( EbmlElement *info )
2866 int i_upper_level = 0;
2868 msg_Dbg( &sys.demuxer, "| + Information" );
2870 /* Master elements */
2871 m = static_cast<EbmlMaster *>(info);
2872 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2874 for( i = 0; i < m->ListSize(); i++ )
2876 EbmlElement *l = (*m)[i];
2878 if( MKV_IS_ID( l, KaxSegmentUID ) )
2880 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2882 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2884 else if( MKV_IS_ID( l, KaxPrevUID ) )
2886 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2888 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2890 else if( MKV_IS_ID( l, KaxNextUID ) )
2892 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2894 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2896 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2898 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2900 i_timescale = uint64(tcs);
2902 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2905 else if( MKV_IS_ID( l, KaxDuration ) )
2907 KaxDuration &dur = *(KaxDuration*)l;
2909 f_duration = float(dur);
2911 msg_Dbg( &sys.demuxer, "| | + Duration=%f",
2914 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2916 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2918 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2920 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2921 psz_muxing_application );
2923 else if( MKV_IS_ID( l, KaxWritingApp ) )
2925 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2927 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2929 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2930 psz_writing_application );
2932 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2934 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2936 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2938 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2939 psz_segment_filename );
2941 else if( MKV_IS_ID( l, KaxTitle ) )
2943 KaxTitle &title = *(KaxTitle*)l;
2945 psz_title = UTF8ToStr( UTFstring( title ) );
2947 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2949 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2951 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2953 families.push_back(*uid);
2955 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2957 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2958 else if( MKV_IS_ID( l, KaxDateUTC ) )
2960 KaxDateUTC &date = *(KaxDateUTC*)l;
2965 i_date = date.GetEpochDate();
2966 memset( buffer, 0, 256 );
2967 if( gmtime_r( &i_date, &tmres ) &&
2968 asctime_r( &tmres, buffer ) )
2970 buffer[strlen( buffer)-1]= '\0';
2971 psz_date_utc = strdup( buffer );
2972 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
2978 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2982 f_duration *= i_timescale / 1000000.0;
2986 /*****************************************************************************
2988 *****************************************************************************/
2989 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2993 if( sys.title == NULL )
2995 sys.title = vlc_input_title_New();
2998 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
2999 for( i = 0; i < ca->ListSize(); i++ )
3001 EbmlElement *l = (*ca)[i];
3003 if( MKV_IS_ID( l, KaxChapterUID ) )
3005 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3006 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3008 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3010 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3011 chapters.b_display_seekpoint = uint8( flag ) == 0;
3013 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3015 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3017 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3018 chapters.i_start_time = uint64( start ) / I64C(1000);
3020 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3022 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3024 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3025 chapters.i_end_time = uint64( end ) / I64C(1000);
3027 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3029 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3031 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3034 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3035 for( j = 0; j < cd->ListSize(); j++ )
3037 EbmlElement *l= (*cd)[j];
3039 if( MKV_IS_ID( l, KaxChapterString ) )
3043 KaxChapterString &name =*(KaxChapterString*)l;
3044 for (k = 0; k < i_level; k++)
3045 chapters.psz_name += '+';
3046 chapters.psz_name += ' ';
3047 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3049 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3051 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3053 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3054 const char *psz = string( lang ).c_str();
3056 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3058 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3060 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3061 const char *psz = string( ct ).c_str();
3063 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3067 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3069 chapter_item_t new_sub_chapter;
3070 ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
3071 new_sub_chapter.psz_parent = &chapters;
3072 chapters.sub_chapters.push_back( new_sub_chapter );
3077 /*****************************************************************************
3079 *****************************************************************************/
3080 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
3085 int i_upper_level = 0;
3086 int i_default_edition = 0;
3089 /* Master elements */
3090 m = static_cast<EbmlMaster *>(chapters);
3091 m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3093 for( i = 0; i < m->ListSize(); i++ )
3095 EbmlElement *l = (*m)[i];
3097 if( MKV_IS_ID( l, KaxEditionEntry ) )
3099 chapter_edition_t edition;
3101 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3103 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3104 for( j = 0; j < E->ListSize(); j++ )
3106 EbmlElement *l = (*E)[j];
3108 if( MKV_IS_ID( l, KaxChapterAtom ) )
3110 chapter_item_t new_sub_chapter;
3111 ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3112 edition.chapters.push_back( new_sub_chapter );
3114 else if( MKV_IS_ID( l, KaxEditionUID ) )
3116 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3118 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3120 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3122 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3124 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3125 i_default_edition = editions.size();
3129 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3132 editions.push_back( edition );
3136 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3140 for( i = 0; i < editions.size(); i++ )
3142 editions[i].RefreshChapters( *sys.title );
3145 i_current_edition = i_default_edition;
3147 if ( editions[i_default_edition].b_ordered )
3149 /* update the duration of the segment according to the sum of all sub chapters */
3150 f_dur = editions[i_default_edition].Duration() / I64C(1000);
3156 void matroska_segment_t::ParseCluster( )
3161 int i_upper_level = 0;
3163 /* Master elements */
3164 m = static_cast<EbmlMaster *>( cluster );
3165 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3167 for( i = 0; i < m->ListSize(); i++ )
3169 EbmlElement *l = (*m)[i];
3171 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3173 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3175 cluster->InitTimecode( uint64( ctc ), i_timescale );
3180 f_start_time = cluster->GlobalTimecode() / 1000000.0;
3183 /*****************************************************************************
3184 * InformationCreate:
3185 *****************************************************************************/
3186 void matroska_segment_t::InformationCreate( )
3190 sys.meta = vlc_meta_New();
3194 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3198 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3200 if( psz_segment_filename )
3202 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3204 if( psz_muxing_application )
3206 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3208 if( psz_writing_application )
3210 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3213 for( i_track = 0; i_track < tracks.size(); i_track++ )
3215 mkv_track_t *tk = tracks[i_track];
3216 vlc_meta_t *mtk = vlc_meta_New();
3218 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3219 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3220 sys.meta->track[sys.meta->i_track++] = mtk;
3222 if( tk->fmt.psz_description )
3224 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3226 if( tk->psz_codec_name )
3228 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3230 if( tk->psz_codec_settings )
3232 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3234 if( tk->psz_codec_info_url )
3236 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3238 if( tk->psz_codec_download_url )
3240 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3244 if( i_tags_position >= 0 )
3246 vlc_bool_t b_seekable;
3248 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3257 /*****************************************************************************
3259 *****************************************************************************/
3261 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3263 #define idx index[i_index]
3265 idx.i_block_number= -1;
3266 idx.i_position = cluster->GetElementPosition();
3268 idx.b_key = VLC_TRUE;
3271 if( i_index >= i_index_max )
3273 i_index_max += 1024;
3274 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3279 static char * UTF8ToStr( const UTFstring &u )
3288 p = dst = (char*)malloc( i_src + 1);
3307 void chapter_edition_t::RefreshChapters( input_title_t & title )
3309 int64_t i_prev_user_time = 0;
3310 std::vector<chapter_item_t>::iterator index = chapters.begin();
3312 while ( index != chapters.end() )
3314 i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3319 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3321 int64_t i_user_time = i_prev_user_time;
3323 // first the sub-chapters, and then ourself
3324 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3325 while ( index != sub_chapters.end() )
3327 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3333 i_user_start_time = i_prev_user_time;
3334 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3336 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3340 i_user_end_time = i_user_time;
3345 std::sort( sub_chapters.begin(), sub_chapters.end() );
3346 i_user_start_time = i_start_time;
3347 i_user_end_time = i_end_time;
3350 if (b_display_seekpoint)
3352 seekpoint_t *sk = vlc_seekpoint_New();
3354 // sk->i_level = i_level;
3355 sk->i_time_offset = i_start_time;
3356 sk->psz_name = strdup( psz_name.c_str() );
3358 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3359 title.i_seekpoint++;
3360 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3361 title.seekpoint[title.i_seekpoint-1] = sk;
3364 i_seekpoint_num = title.i_seekpoint;
3366 return i_user_end_time;
3369 double chapter_edition_t::Duration() const
3371 double f_result = 0.0;
3373 if ( chapters.size() )
3375 std::vector<chapter_item_t>::const_iterator index = chapters.end();
3377 f_result = (*index).i_user_end_time;
3383 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3385 const chapter_item_t *psz_result = NULL;
3387 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3389 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3390 while ( index != sub_chapters.end() && psz_result == NULL )
3392 psz_result = (*index).FindTimecode( i_user_timecode );
3396 if ( psz_result == NULL )
3403 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3405 const chapter_item_t *psz_result = NULL;
3407 std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3408 while ( index != chapters.end() && psz_result == NULL )
3410 psz_result = (*index).FindTimecode( i_user_timecode );
3417 void demux_sys_t::PreloadFamily( )
3419 /* family handling disabled for the moment
3420 matroska_stream_t *p_stream = Stream();
3423 matroska_segment_t *p_segment = p_stream->Segment();
3426 for (size_t i=0; i<streams.size(); i++)
3428 streams[i]->PreloadFamily( *p_segment );
3435 void matroska_stream_t::PreloadFamily( const matroska_segment_t & of_segment )
3437 for (size_t i=0; i<segments.size(); i++)
3439 segments[i]->PreloadFamily( of_segment );
3443 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3448 for (size_t i=0; i<families.size(); i++)
3450 for (size_t j=0; j<of_segment.families.size(); j++)
3452 if ( families[i] == of_segment.families[j] )
3460 // preload all the linked segments for all preloaded segments
3461 void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
3463 size_t i_preloaded, i;
3465 delete p_current_segment;
3466 p_current_segment = new virtual_segment_t( p_segment );
3468 // fill our current virtual segment with all hard linked segments
3471 for ( i=0; i< opened_segments.size(); i++ )
3473 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3475 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3477 p_current_segment->Sort( );
3479 p_current_segment->PreloadLinked( );
3482 void demux_sys_t::PreparePlayback( )
3484 f_duration = p_current_segment->Duration();
3485 p_current_segment->LoadCues();
3488 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3490 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3491 if ( *p_itema == p_item_b->prev_segment_uid )
3494 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3495 if ( *p_itema == p_item_b->segment_uid )
3498 if ( *p_itema == p_item_b->prev_segment_uid )
3504 bool matroska_segment_t::Preload( )
3509 EbmlElement *el = NULL;
3513 while( ( el = ep->Get() ) != NULL )
3515 if( MKV_IS_ID( el, KaxInfo ) )
3519 else if( MKV_IS_ID( el, KaxTracks ) )
3523 else if( MKV_IS_ID( el, KaxSeekHead ) )
3525 ParseSeekHead( el );
3527 else if( MKV_IS_ID( el, KaxCues ) )
3529 msg_Dbg( &sys.demuxer, "| + Cues" );
3531 else if( MKV_IS_ID( el, KaxCluster ) )
3533 msg_Dbg( &sys.demuxer, "| + Cluster" );
3535 cluster = (KaxCluster*)el;
3537 i_start_pos = cluster->GetElementPosition();
3540 /* stop parsing the stream */
3543 else if( MKV_IS_ID( el, KaxAttachments ) )
3545 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3547 else if( MKV_IS_ID( el, KaxChapters ) )
3549 msg_Dbg( &sys.demuxer, "| + Chapters" );
3550 ParseChapters( el );
3552 else if( MKV_IS_ID( el, KaxTag ) )
3554 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3558 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3567 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3569 for (size_t i=0; i<opened_segments.size(); i++)
3571 if ( opened_segments[i]->segment_uid == uid )
3572 return opened_segments[i];
3577 void virtual_segment_t::Sort()
3579 // keep the current segment index
3580 matroska_segment_t *p_segment = linked_segments[i_current_segment];
3582 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
3584 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3585 if ( linked_segments[i_current_segment] == p_segment )
3589 size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
3592 // check if it's not already in here
3593 for ( i=0; i<linked_segments.size(); i++ )
3595 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3599 // find possible mates
3600 for ( i=0; i<linked_uids.size(); i++ )
3602 if ( p_segment->segment_uid == linked_uids[i]
3603 || p_segment->prev_segment_uid == linked_uids[i]
3604 || p_segment->next_segment_uid == linked_uids[i] )
3606 linked_segments.push_back( p_segment );
3608 AppendUID( p_segment->prev_segment_uid );
3609 AppendUID( p_segment->next_segment_uid );
3617 void virtual_segment_t::PreloadLinked( )
3619 for ( size_t i=0; i<linked_segments.size(); i++ )
3621 linked_segments[i]->Preload( );
3625 float virtual_segment_t::Duration() const
3628 if ( linked_segments.size() == 0 )
3631 matroska_segment_t *p_last_segment = linked_segments[linked_segments.size()-1];
3632 p_last_segment->ParseCluster( );
3634 f_duration = p_last_segment->f_start_time + p_last_segment->f_duration;
3639 void virtual_segment_t::LoadCues( )
3641 for ( size_t i=0; i<linked_segments.size(); i++ )
3643 linked_segments[i]->LoadCues();
3647 void virtual_segment_t::AppendUID( const EbmlBinary & UID )
3649 if ( UID.GetBuffer() == NULL )
3652 for (size_t i=0; i<linked_uids.size(); i++)
3654 if ( UID == linked_uids[i] )
3657 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );