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)
389 ,i_chapters_position(-1)
396 ,psz_muxing_application(NULL)
397 ,psz_writing_application(NULL)
398 ,psz_segment_filename(NULL)
401 ,i_current_edition(-1)
402 ,psz_current_chapter(NULL)
407 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
410 ~matroska_segment_t()
412 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
414 #define tk tracks[i_track]
415 if( tk->fmt.psz_description )
417 free( tk->fmt.psz_description );
421 free( tk->psz_codec );
423 if( tk->fmt.psz_language )
425 free( tk->fmt.psz_language );
431 if( psz_writing_application )
433 free( psz_writing_application );
435 if( psz_muxing_application )
437 free( psz_muxing_application );
439 if( psz_segment_filename )
441 free( psz_segment_filename );
449 free( psz_date_utc );
461 uint64_t i_timescale;
463 /* duration of the segment */
467 std::vector<mkv_track_t*> tracks;
470 int64_t i_cues_position;
471 int64_t i_chapters_position;
472 int64_t i_tags_position;
476 KaxSegmentUID segment_uid;
477 KaxPrevUID prev_segment_uid;
478 KaxNextUID next_segment_uid;
486 char *psz_muxing_application;
487 char *psz_writing_application;
488 char *psz_segment_filename;
492 std::vector<chapter_edition_t> editions;
493 int i_current_edition;
494 const chapter_item_t *psz_current_chapter;
496 std::vector<KaxSegmentFamily> families;
502 inline chapter_edition_t *Edition()
504 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
505 return &editions[i_current_edition];
510 bool PreloadFamily( const matroska_segment_t & segment );
511 size_t PreloadLinked( const demux_sys_t & of_sys, std::vector<matroska_segment_t*> & segments );
512 void ParseInfo( EbmlElement *info );
513 void ParseChapters( EbmlElement *chapters );
514 void ParseSeekHead( EbmlElement *seekhead );
515 void ParseTracks( EbmlElement *tracks );
516 void ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters );
517 void ParseTrackEntry( EbmlMaster *m );
518 void IndexAppendCluster( KaxCluster *cluster );
519 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
520 bool Select( mtime_t i_start_time );
522 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
525 class matroska_stream_t
528 matroska_stream_t( demux_sys_t & demuxer )
531 ,i_current_segment(-1)
538 for ( size_t i=0; i<segments.size(); i++ )
547 std::vector<matroska_segment_t*> segments;
548 size_t i_current_segment;
552 /* duration of the stream */
555 inline matroska_segment_t *Segment()
557 if ( i_current_segment >= 0 && size_t(i_current_segment) < segments.size() )
558 return segments[i_current_segment];
562 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
564 void PreloadFamily( const matroska_segment_t & segment );
565 size_t PreloadLinked( const demux_sys_t & of_sys );
566 void PreparePlayback( );
572 demux_sys_t( demux_t & demux )
579 ,i_current_stream(-1)
584 for (size_t i=0; i<streams.size(); i++)
593 mtime_t i_chapter_time;
597 input_title_t *title;
599 std::vector<matroska_stream_t*> streams;
600 int i_current_stream;
602 inline matroska_stream_t *Stream()
604 if ( i_current_stream >= 0 && size_t(i_current_stream) < streams.size() )
605 return streams[i_current_stream];
609 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
610 void PreloadFamily( );
611 void PreloadLinked( );
612 void PreparePlayback( );
613 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
616 static int Demux ( demux_t * );
617 static int Control( demux_t *, int, va_list );
618 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
620 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
622 static char *UTF8ToStr ( const UTFstring &u );
623 static void LoadCues ( demux_t * );
624 static void InformationCreate ( demux_t * );
626 /*****************************************************************************
627 * Open: initializes matroska demux structures
628 *****************************************************************************/
629 static int Open( vlc_object_t * p_this )
631 demux_t *p_demux = (demux_t*)p_this;
633 matroska_stream_t *p_stream;
634 matroska_segment_t *p_segment;
636 std::string s_path, s_filename;
637 vlc_stream_io_callback *p_io_callback;
638 EbmlStream *p_io_stream;
640 /* peek the begining */
641 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
643 /* is a valid file */
644 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
645 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
647 /* Set the demux function */
648 p_demux->pf_demux = Demux;
649 p_demux->pf_control = Control;
650 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
652 p_io_callback = new vlc_stream_io_callback( p_demux->s );
653 p_io_stream = new EbmlStream( *p_io_callback );
655 if( p_io_stream == NULL )
657 msg_Err( p_demux, "failed to create EbmlStream" );
658 delete p_io_callback;
663 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
664 if( p_stream == NULL )
666 msg_Err( p_demux, "cannot find KaxSegment" );
669 p_sys->streams.push_back( p_stream );
670 p_sys->i_current_stream = 0;
672 p_stream->p_in = p_io_callback;
673 p_stream->p_es = p_io_stream;
675 for (size_t i=0; i<p_stream->segments.size(); i++)
677 p_stream->segments[i]->Preload();
679 p_stream->i_current_segment = 0;
681 p_segment = p_stream->Segment();
682 if( p_segment->cluster == NULL )
684 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
687 // reset the stream reading to the first cluster of the segment used
688 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
690 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
691 /* TODO handle multi-segment files */
692 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
694 // assume it's a regular file
695 // get the directory path
696 s_path = p_demux->psz_path;
697 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
699 s_path = s_path.substr(0,s_path.length()-1);
703 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
705 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
709 struct dirent *p_file_item;
710 DIR *p_src_dir = opendir(s_path.c_str());
712 if (p_src_dir != NULL)
714 while ((p_file_item = (dirent *) readdir(p_src_dir)))
716 if (strlen(p_file_item->d_name) > 4)
718 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
720 if (!s_filename.compare(p_demux->psz_path))
721 continue; // don't reuse the original opened file
723 #if defined(__GNUC__) && (__GNUC__ < 3)
724 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
725 !s_filename.compare("mka", s_filename.length() - 3, 3))
727 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
728 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
731 // test wether this file belongs to the our family
732 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
733 EbmlStream *p_estream = new EbmlStream(*p_file_io);
735 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
736 if ( p_stream == NULL )
738 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
744 p_stream->p_in = p_file_io;
745 p_stream->p_es = p_estream;
746 p_sys->streams.push_back( p_stream );
751 closedir( p_src_dir );
755 p_sys->PreloadFamily( );
756 p_sys->PreloadLinked( );
757 p_sys->PreparePlayback( );
759 /* *** Load the cue if found *** */
760 if( p_segment->i_cues_position >= 0 )
762 vlc_bool_t b_seekable;
764 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
771 if( !p_segment->b_cues || p_segment->i_index <= 0 )
773 msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
775 p_segment->IndexAppendCluster( p_segment->cluster );
777 p_segment->b_cues = VLC_FALSE;
780 /* add information */
781 InformationCreate( p_demux );
783 if ( !p_segment->Select( 0 ) )
785 msg_Err( p_demux, "cannot use the segment" );
796 /*****************************************************************************
797 * Close: frees unused data
798 *****************************************************************************/
799 static void Close( vlc_object_t *p_this )
801 demux_t *p_demux = (demux_t*)p_this;
802 demux_sys_t *p_sys = p_demux->p_sys;
803 matroska_stream_t *p_stream = p_sys->Stream();
804 if ( p_stream != NULL )
806 matroska_segment_t *p_segment = p_stream->Segment();
809 delete p_segment->segment;
815 /*****************************************************************************
817 *****************************************************************************/
818 static int Control( demux_t *p_demux, int i_query, va_list args )
820 demux_sys_t *p_sys = p_demux->p_sys;
821 matroska_stream_t *p_stream = p_sys->Stream();
822 if ( p_stream == NULL ) return VLC_EGENERIC;
823 matroska_segment_t *p_segment = p_stream->Segment();
828 vlc_meta_t **pp_meta;
833 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
834 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
837 case DEMUX_GET_LENGTH:
838 pi64 = (int64_t*)va_arg( args, int64_t * );
839 if( p_stream->f_duration > 0.0 )
841 *pi64 = (int64_t)(p_stream->f_duration * 1000);
846 case DEMUX_GET_POSITION:
847 pf = (double*)va_arg( args, double * );
848 if ( p_stream->f_duration > 0.0 )
849 *pf = (double)p_sys->i_pts / (1000.0 * p_stream->f_duration);
852 case DEMUX_SET_POSITION:
853 f = (double)va_arg( args, double );
854 Seek( p_demux, -1, f, NULL );
858 pi64 = (int64_t*)va_arg( args, int64_t * );
859 *pi64 = p_sys->i_pts;
862 case DEMUX_GET_TITLE_INFO:
863 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
865 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
866 int *pi_int = (int*)va_arg( args, int* );
869 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
871 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
877 case DEMUX_SET_TITLE:
878 /* TODO handle editions as titles & DVD titles as well */
879 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
885 case DEMUX_SET_SEEKPOINT:
886 /* FIXME do a better implementation */
887 i_skp = (int)va_arg( args, int );
889 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
891 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
892 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
893 p_demux->info.i_seekpoint = i_skp;
905 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
916 if( sys.demuxer.b_die )
922 i_level = ep->GetLevel();
924 if( el == NULL && *pp_block != NULL )
926 /* update the index */
927 #define idx index[i_index - 1]
928 if( i_index > 0 && idx.i_time == -1 )
930 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
931 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
939 if( ep->GetLevel() > 1 )
944 msg_Warn( &sys.demuxer, "EOF" );
951 if( MKV_IS_ID( el, KaxCluster ) )
953 cluster = (KaxCluster*)el;
955 /* add it to the index */
957 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
959 IndexAppendCluster( cluster );
962 // reset silent tracks
963 for (size_t i=0; i<tracks.size(); i++)
965 tracks[i]->b_silent = VLC_FALSE;
970 else if( MKV_IS_ID( el, KaxCues ) )
972 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
977 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
980 else if( i_level == 2 )
982 if( MKV_IS_ID( el, KaxClusterTimecode ) )
984 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
986 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
987 cluster->InitTimecode( uint64( ctc ), i_timescale );
989 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
993 else if( MKV_IS_ID( el, KaxBlockGroup ) )
998 else if( i_level == 3 )
1000 if( MKV_IS_ID( el, KaxBlock ) )
1002 *pp_block = (KaxBlock*)el;
1004 (*pp_block)->ReadData( es.I_O() );
1005 (*pp_block)->SetParent( *cluster );
1009 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1011 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1013 dur.ReadData( es.I_O() );
1014 *pi_duration = uint64( dur );
1016 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1018 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1020 ref.ReadData( es.I_O() );
1021 if( *pi_ref1 == -1 )
1023 *pi_ref1 = int64( ref );
1027 *pi_ref2 = int64( ref );
1030 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1032 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1033 track_num.ReadData( es.I_O() );
1035 for (size_t i=0; i<tracks.size(); i++)
1037 if ( tracks[i]->i_number == uint32(track_num))
1039 tracks[i]->b_silent = VLC_TRUE;
1047 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1048 return VLC_EGENERIC;
1053 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1056 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1057 memcpy( p_block->p_buffer, p_mem, i_mem );
1058 //p_block->i_rate = p_input->stream.control.i_rate;
1062 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1063 mtime_t i_duration )
1065 demux_sys_t *p_sys = p_demux->p_sys;
1066 matroska_stream_t *p_stream = p_sys->Stream();
1067 matroska_segment_t *p_segment = p_stream->Segment();
1073 #define tk p_segment->tracks[i_track]
1074 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1076 if( tk->i_number == block->TrackNum() )
1082 if( i_track >= p_segment->tracks.size() )
1084 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1087 if( tk->p_es == NULL )
1089 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1092 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1094 return; /* discard audio packets that shouldn't be rendered */
1097 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1100 tk->b_inited = VLC_FALSE;
1104 /* First send init data */
1105 if( !tk->b_inited && tk->i_data_init > 0 )
1109 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1110 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1111 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1113 tk->b_inited = VLC_TRUE;
1116 for( i = 0; i < block->NumberFrames(); i++ )
1119 DataBuffer &data = block->GetBuffer(i);
1121 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1123 if( p_block == NULL )
1128 #if defined(HAVE_ZLIB_H)
1129 if( tk->i_compression_type )
1131 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1135 // TODO implement correct timestamping when B frames are used
1136 if( tk->fmt.i_cat != VIDEO_ES )
1138 p_block->i_dts = p_block->i_pts = i_pts;
1142 p_block->i_dts = i_pts;
1146 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1148 p_block->i_length = i_duration * 1000;
1150 msg_Warn( p_demux, "Sending block %d", p_block );
1151 es_out_Send( p_demux->out, tk->p_es, p_block );
1153 /* use time stamp only for first block */
1160 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1162 int i_upper_lvl = 0;
1164 EbmlElement *p_l0, *p_l1, *p_l2;
1165 bool b_keep_stream = false, b_keep_segment;
1167 // verify the EBML Header
1168 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1173 p_l0->SkipData(*p_estream, EbmlHead_Context);
1176 // find all segments in this file
1177 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1183 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1187 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1190 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1191 b_keep_segment = false;
1193 ep = new EbmlParser(p_estream, p_l0);
1194 p_segment1->ep = ep;
1195 p_segment1->segment = (KaxSegment*)p_l0;
1197 while ((p_l1 = ep->Get()))
1199 if (MKV_IS_ID(p_l1, KaxInfo))
1201 // find the families of this segment
1202 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1204 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1205 for( i = 0; i < p_info->ListSize(); i++ )
1207 EbmlElement *l = (*p_info)[i];
1209 if( MKV_IS_ID( l, KaxSegmentUID ) )
1211 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1212 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1213 if ( !b_keep_segment )
1214 break; // this segment is already known
1215 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1217 else if( MKV_IS_ID( l, KaxPrevUID ) )
1219 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1221 else if( MKV_IS_ID( l, KaxNextUID ) )
1223 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1225 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1227 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1228 std::vector<KaxSegmentFamily>::iterator iter;
1229 p_segment1->families.push_back( *p_fam );
1235 if ( b_keep_segment )
1237 b_keep_stream = true;
1238 p_stream1->segments.push_back( p_segment1 );
1244 p_l0->SkipData(*p_estream, EbmlHead_Context);
1245 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1248 if ( !b_keep_stream )
1257 bool matroska_segment_t::Select( mtime_t i_start_time )
1262 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1263 for( i_track = 0; i_track < tracks.size(); i_track++ )
1265 #define tk tracks[i_track]
1266 if( tk->fmt.i_cat == UNKNOWN_ES )
1268 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1273 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1275 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1277 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1278 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1282 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1284 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1285 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1286 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1288 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1289 if( tk->fmt.i_extra > 0 )
1291 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1292 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1296 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1297 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1299 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1301 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1303 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1305 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1307 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1309 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1310 tk->fmt.b_packetized = VLC_FALSE;
1311 tk->fmt.i_extra = tk->i_extra_data;
1312 tk->fmt.p_extra = malloc( tk->i_extra_data );
1313 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1317 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1320 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1322 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1323 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1326 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1327 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1328 tk->fmt.i_codec = p_box->i_type;
1329 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1330 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1331 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1332 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1333 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1334 MP4_FreeBox_sample_vide( p_box );
1335 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1337 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1339 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1341 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1342 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1346 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1348 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1350 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1351 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1352 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1353 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1354 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1356 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1357 if( tk->fmt.i_extra > 0 )
1359 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1360 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1364 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1365 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1366 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1368 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1370 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1372 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1374 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1376 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1378 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1380 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1381 tk->fmt.i_extra = tk->i_extra_data;
1382 tk->fmt.p_extra = malloc( tk->i_extra_data );
1383 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1385 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1387 int i, i_offset = 1, i_size[3], i_extra;
1390 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1392 /* Split the 3 headers */
1393 if( tk->p_extra_data[0] != 0x02 )
1394 msg_Err( &sys.demuxer, "invalid vorbis header" );
1396 for( i = 0; i < 2; i++ )
1399 while( i_offset < tk->i_extra_data )
1401 i_size[i] += tk->p_extra_data[i_offset];
1402 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1406 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1407 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1408 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1410 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1411 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1412 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1413 for( i = 0; i < 3; i++ )
1415 *(p_extra++) = i_size[i] >> 8;
1416 *(p_extra++) = i_size[i] & 0xFF;
1417 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1419 p_extra += i_size[i];
1420 i_extra += i_size[i];
1423 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1424 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1426 int i_profile, i_srate;
1427 static unsigned int i_sample_rates[] =
1429 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1430 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1433 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1434 /* create data for faad (MP4DecSpecificDescrTag)*/
1436 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1440 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1444 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1453 for( i_srate = 0; i_srate < 13; i_srate++ )
1455 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1460 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1462 tk->fmt.i_extra = 2;
1463 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1464 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1465 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1467 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1468 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1469 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1471 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1473 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1477 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1479 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1481 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1483 /* FIXME: support this codec */
1484 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1485 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1487 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1489 /* FIXME: support this codec */
1490 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1491 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1493 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1495 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1496 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1498 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1499 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1500 !strcmp( tk->psz_codec, "S_SSA" ) ||
1501 !strcmp( tk->psz_codec, "S_ASS" ))
1503 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1504 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1506 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1508 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1509 if( tk->i_extra_data )
1512 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1513 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1514 p_buf[tk->i_extra_data] = '\0';
1516 p_start = strstr( p_buf, "size:" );
1517 if( sscanf( p_start, "size: %dx%d",
1518 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1520 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 );
1524 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1529 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1531 /* FIXME: support this codec */
1532 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1533 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1537 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1538 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1542 tk->fmt.i_priority = 1000;
1545 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1547 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1551 sys.i_start_pts = i_start_time;
1554 // reset the stream reading to the first cluster of the segment used
1555 es.I_O().setFilePointer( i_start_pos );
1560 void matroska_segment_t::UnSelect( )
1564 for( i_track = 0; i_track < tracks.size(); i_track++ )
1566 #define tk tracks[i_track]
1567 if ( tk->p_es != NULL )
1569 es_out_Del( sys.demuxer.out, tk->p_es );
1576 static void UpdateCurrentToChapter( demux_t & demux )
1578 demux_sys_t & sys = *demux.p_sys;
1579 matroska_stream_t *p_stream = sys.Stream();
1580 matroska_segment_t *p_segment = p_stream->Segment();
1581 const chapter_item_t *psz_curr_chapter;
1583 /* update current chapter/seekpoint */
1584 if ( p_segment->editions.size())
1586 /* 1st, we need to know in which chapter we are */
1587 psz_curr_chapter = p_segment->editions[p_segment->i_current_edition].FindTimecode( sys.i_pts );
1589 /* we have moved to a new chapter */
1590 if (p_segment->psz_current_chapter != NULL && psz_curr_chapter != NULL && p_segment->psz_current_chapter != psz_curr_chapter)
1592 if (p_segment->psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1594 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1595 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1598 if (p_segment->editions[p_segment->i_current_edition].b_ordered )
1600 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1601 if (p_segment->psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1602 Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
1603 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1604 /* only seek after each duration >= end timecode of the current chapter */
1607 // p_segment->i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1608 // p_segment->i_start_pts = psz_curr_chapter->i_user_start_time;
1610 p_segment->psz_current_chapter = psz_curr_chapter;
1614 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
1616 demux_sys_t *p_sys = p_demux->p_sys;
1617 matroska_stream_t *p_stream = p_sys->Stream();
1618 matroska_segment_t *p_segment = p_stream->Segment();
1619 mtime_t i_time_offset = 0;
1622 int64_t i_block_duration;
1623 int64_t i_block_ref1;
1624 int64_t i_block_ref2;
1627 int i_track_skipping;
1630 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1631 if( i_date < 0 && f_percent < 0 )
1633 msg_Warn( p_demux, "cannot seek nowhere !" );
1636 if( f_percent > 1.0 )
1638 msg_Warn( p_demux, "cannot seek so far !" );
1642 delete p_segment->ep;
1643 p_segment->ep = new EbmlParser( p_stream->p_es, p_segment->segment );
1644 p_segment->cluster = NULL;
1646 /* seek without index or without date */
1647 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1649 if (p_stream->f_duration >= 0)
1651 i_date = int64_t( f_percent * p_stream->f_duration * 1000.0 );
1655 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1657 msg_Dbg( p_demux, "inacurate way of seeking" );
1658 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1660 if( p_segment->index[i_index].i_position >= i_pos)
1665 if( i_index == p_segment->i_index )
1670 i_date = p_segment->index[i_index].i_time;
1673 if( p_segment->index[i_index].i_position < i_pos )
1677 msg_Warn( p_demux, "searching for cluster, could take some time" );
1679 /* search a cluster */
1680 while( ( el = p_sys->ep->Get() ) != NULL )
1682 if( MKV_IS_ID( el, KaxCluster ) )
1684 KaxCluster *cluster = (KaxCluster*)el;
1686 /* add it to the index */
1687 p_segment->IndexAppendCluster( cluster );
1689 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1691 p_sys->cluster = cluster;
1702 // find the actual time for an ordered edition
1703 if ( psz_chapter == NULL )
1705 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered )
1707 /* 1st, we need to know in which chapter we are */
1708 psz_chapter = p_segment->editions[p_segment->i_current_edition].FindTimecode( i_date );
1712 if ( psz_chapter != NULL )
1714 p_segment->psz_current_chapter = psz_chapter;
1715 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
1716 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1717 p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
1720 for( ; i_index < p_segment->i_index; i_index++ )
1722 if( p_segment->index[i_index].i_time + i_time_offset > i_date )
1733 msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1734 p_segment->index[i_index].i_time,
1735 (int)( 100 * p_segment->index[i_index].i_position /
1736 stream_Size( p_demux->s ) ) );
1738 p_stream->p_in->setFilePointer( p_segment->index[i_index].i_position,
1741 p_sys->i_start_pts = i_date;
1743 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1745 /* now parse until key frame */
1746 #define tk p_segment->tracks[i_track]
1747 i_track_skipping = 0;
1748 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1750 if( tk->fmt.i_cat == VIDEO_ES )
1752 tk->b_search_keyframe = VLC_TRUE;
1755 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
1759 while( i_track_skipping > 0 )
1761 if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1763 msg_Warn( p_demux, "cannot get block EOF?" );
1768 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1770 if( tk->i_number == block->TrackNum() )
1776 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1778 if( i_track < p_segment->tracks.size() )
1780 if( p_sys->i_pts >= p_sys->i_start_pts )
1782 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1783 i_track_skipping = 0;
1785 else if( tk->fmt.i_cat == VIDEO_ES )
1787 if( i_block_ref1 == -1 && tk->b_search_keyframe )
1789 tk->b_search_keyframe = VLC_FALSE;
1792 if( !tk->b_search_keyframe )
1794 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1804 /*****************************************************************************
1805 * Demux: reads and demuxes data packets
1806 *****************************************************************************
1807 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1808 *****************************************************************************/
1809 static int Demux( demux_t *p_demux)
1811 demux_sys_t *p_sys = p_demux->p_sys;
1812 matroska_stream_t *p_stream = p_sys->Stream();
1813 matroska_segment_t *p_segment = p_stream->Segment();
1814 int i_block_count = 0;
1817 int64_t i_block_duration;
1818 int64_t i_block_ref1;
1819 int64_t i_block_ref2;
1823 if( p_sys->i_pts >= p_sys->i_start_pts )
1824 UpdateCurrentToChapter( *p_demux );
1826 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered && p_segment->psz_current_chapter == NULL )
1828 /* nothing left to read in this ordered edition */
1829 if ( p_stream->i_current_segment == p_stream->segments.size() - 1)
1831 p_segment->UnSelect( );
1833 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1835 /* switch to the next segment (TODO update the duration) */
1836 p_stream->i_current_segment++;
1837 p_segment = p_stream->Segment();
1838 if ( !p_segment || !p_segment->Select( 0 ) )
1843 if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1845 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered )
1847 // check if there are more chapters to read
1848 if ( p_segment->psz_current_chapter != NULL )
1850 p_sys->i_pts = p_segment->psz_current_chapter->i_user_end_time;
1856 msg_Warn( p_demux, "cannot get block EOF?" );
1857 p_segment->UnSelect( );
1859 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1861 /* switch to the next segment (TODO update the duration) */
1862 p_stream->i_current_segment++;
1863 p_segment = p_stream->Segment();
1864 if ( !p_segment || !p_segment->Select( 0 ) )
1868 p_sys->i_current_stream++;
1869 p_stream = p_sys->Stream();
1872 p_segment = p_stream->Segment();
1873 if ( p_segment && p_segment->Select( 0 ) )
1883 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1885 if( p_sys->i_pts >= p_sys->i_start_pts )
1887 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1890 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1895 // TODO optimize when there is need to leave or when seeking has been called
1896 if( i_block_count > 5 )
1905 /*****************************************************************************
1907 *****************************************************************************/
1908 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1914 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1916 if( i_size <= 0 || mb_eof )
1921 return stream_Read( s, p_buffer, i_size );
1923 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1929 case seek_beginning:
1933 i_pos = stream_Size( s ) - i_offset;
1936 i_pos= stream_Tell( s ) + i_offset;
1940 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1947 if( stream_Seek( s, i_pos ) )
1953 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1957 uint64 vlc_stream_io_callback::getFilePointer( void )
1959 return stream_Tell( s );
1961 void vlc_stream_io_callback::close( void )
1967 /*****************************************************************************
1968 * Ebml Stream parser
1969 *****************************************************************************/
1970 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1978 for( i = 1; i < 6; i++ )
1984 mb_keep = VLC_FALSE;
1987 EbmlParser::~EbmlParser( void )
1991 for( i = 1; i < mi_level; i++ )
1997 mb_keep = VLC_FALSE;
2001 void EbmlParser::Up( void )
2003 if( mi_user_level == mi_level )
2005 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2011 void EbmlParser::Down( void )
2017 void EbmlParser::Keep( void )
2022 int EbmlParser::GetLevel( void )
2024 return mi_user_level;
2027 void EbmlParser::Reset( void )
2029 while ( mi_level > 0)
2031 delete m_el[mi_level];
2032 m_el[mi_level] = NULL;
2035 mi_user_level = mi_level = 1;
2036 #if LIBEBML_VERSION >= 0x000704
2037 // a little faster and cleaner
2038 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2040 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2044 EbmlElement *EbmlParser::Get( void )
2048 if( mi_user_level != mi_level )
2054 EbmlElement *ret = m_got;
2060 if( m_el[mi_level] )
2062 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2065 delete m_el[mi_level];
2067 mb_keep = VLC_FALSE;
2070 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
2081 delete m_el[mi_level - 1];
2082 m_got = m_el[mi_level -1] = m_el[mi_level];
2083 m_el[mi_level] = NULL;
2090 else if( m_el[mi_level] == NULL )
2092 fprintf( stderr," m_el[mi_level] == NULL\n" );
2095 return m_el[mi_level];
2099 /*****************************************************************************
2101 * * LoadCues : load the cues element and update index
2103 * * LoadTags : load ... the tags element
2105 * * InformationCreate : create all information, load tags if present
2107 *****************************************************************************/
2108 static void LoadCues( demux_t *p_demux )
2110 demux_sys_t *p_sys = p_demux->p_sys;
2111 matroska_stream_t *p_stream = p_sys->Stream();
2112 matroska_segment_t *p_segment = p_stream->Segment();
2113 int64_t i_sav_position = p_stream->p_in->getFilePointer();
2115 EbmlElement *el, *cues;
2117 msg_Dbg( p_demux, "loading cues" );
2118 p_stream->p_in->setFilePointer( p_segment->i_cues_position, seek_beginning );
2119 cues = p_stream->p_es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2123 msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
2124 p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
2128 ep = new EbmlParser( p_stream->p_es, cues );
2129 while( ( el = ep->Get() ) != NULL )
2131 if( MKV_IS_ID( el, KaxCuePoint ) )
2133 #define idx p_segment->index[p_segment->i_index]
2136 idx.i_block_number= -1;
2137 idx.i_position = -1;
2139 idx.b_key = VLC_TRUE;
2142 while( ( el = ep->Get() ) != NULL )
2144 if( MKV_IS_ID( el, KaxCueTime ) )
2146 KaxCueTime &ctime = *(KaxCueTime*)el;
2148 ctime.ReadData( p_stream->p_es->I_O() );
2150 idx.i_time = uint64( ctime ) * p_segment->i_timescale / (mtime_t)1000;
2152 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2155 while( ( el = ep->Get() ) != NULL )
2157 if( MKV_IS_ID( el, KaxCueTrack ) )
2159 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2161 ctrack.ReadData( p_stream->p_es->I_O() );
2162 idx.i_track = uint16( ctrack );
2164 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2166 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2168 ccpos.ReadData( p_stream->p_es->I_O() );
2169 idx.i_position = p_segment->segment->GetGlobalPosition( uint64( ccpos ) );
2171 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2173 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2175 cbnum.ReadData( p_stream->p_es->I_O() );
2176 idx.i_block_number = uint32( cbnum );
2180 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2187 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2193 msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
2194 " track=%d bnum=%d", idx.i_time, idx.i_position,
2195 idx.i_track, idx.i_block_number );
2198 p_segment->i_index++;
2199 if( p_segment->i_index >= p_segment->i_index_max )
2201 p_segment->i_index_max += 1024;
2202 p_segment->index = (mkv_index_t*)realloc( p_segment->index, sizeof( mkv_index_t ) * p_segment->i_index_max );
2208 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2214 p_segment->b_cues = VLC_TRUE;
2216 msg_Dbg( p_demux, "loading cues done." );
2217 p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
2220 static void LoadTags( demux_t *p_demux )
2222 demux_sys_t *p_sys = p_demux->p_sys;
2223 matroska_stream_t *p_stream = p_sys->Stream();
2224 matroska_segment_t *p_segment = p_stream->Segment();
2225 int64_t i_sav_position = p_stream->p_in->getFilePointer();
2227 EbmlElement *el, *tags;
2229 msg_Dbg( p_demux, "loading tags" );
2230 p_stream->p_in->setFilePointer( p_segment->i_tags_position, seek_beginning );
2231 tags = p_stream->p_es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2235 msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
2236 p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
2240 msg_Dbg( p_demux, "Tags" );
2241 ep = new EbmlParser( p_stream->p_es, tags );
2242 while( ( el = ep->Get() ) != NULL )
2244 if( MKV_IS_ID( el, KaxTag ) )
2246 msg_Dbg( p_demux, "+ Tag" );
2248 while( ( el = ep->Get() ) != NULL )
2250 if( MKV_IS_ID( el, KaxTagTargets ) )
2252 msg_Dbg( p_demux, "| + Targets" );
2254 while( ( el = ep->Get() ) != NULL )
2256 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2260 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2262 msg_Dbg( p_demux, "| + General" );
2264 while( ( el = ep->Get() ) != NULL )
2266 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2270 else if( MKV_IS_ID( el, KaxTagGenres ) )
2272 msg_Dbg( p_demux, "| + Genres" );
2274 while( ( el = ep->Get() ) != NULL )
2276 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2280 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2282 msg_Dbg( p_demux, "| + Audio Specific" );
2284 while( ( el = ep->Get() ) != NULL )
2286 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2290 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2292 msg_Dbg( p_demux, "| + Images Specific" );
2294 while( ( el = ep->Get() ) != NULL )
2296 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2300 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2302 msg_Dbg( p_demux, "| + Multi Comment" );
2304 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2306 msg_Dbg( p_demux, "| + Multi Commercial" );
2308 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2310 msg_Dbg( p_demux, "| + Multi Date" );
2312 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2314 msg_Dbg( p_demux, "| + Multi Entity" );
2316 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2318 msg_Dbg( p_demux, "| + Multi Identifier" );
2320 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2322 msg_Dbg( p_demux, "| + Multi Legal" );
2324 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2326 msg_Dbg( p_demux, "| + Multi Title" );
2330 msg_Dbg( p_demux, "| + Unknown (%s)", typeid( *el ).name() );
2337 msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
2343 msg_Dbg( p_demux, "loading tags done." );
2344 p_stream->p_in->setFilePointer( i_sav_position, seek_beginning );
2347 /*****************************************************************************
2349 *****************************************************************************/
2350 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2355 int i_upper_level = 0;
2357 msg_Dbg( &sys.demuxer, "| + Seek head" );
2359 /* Master elements */
2360 m = static_cast<EbmlMaster *>(seekhead);
2361 m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2363 for( i = 0; i < m->ListSize(); i++ )
2365 EbmlElement *l = (*m)[i];
2367 if( MKV_IS_ID( l, KaxSeek ) )
2369 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2370 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2375 for( j = 0; j < sk->ListSize(); j++ )
2377 EbmlElement *l = (*sk)[j];
2379 if( MKV_IS_ID( l, KaxSeekID ) )
2381 KaxSeekID &sid = *(KaxSeekID*)l;
2382 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2384 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2386 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2387 i_pos = uint64( spos );
2391 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2397 if( id == KaxCues::ClassInfos.GlobalId )
2399 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2400 i_cues_position = segment->GetGlobalPosition( i_pos );
2402 else if( id == KaxChapters::ClassInfos.GlobalId )
2404 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2405 i_chapters_position = segment->GetGlobalPosition( i_pos );
2407 else if( id == KaxTags::ClassInfos.GlobalId )
2409 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2410 i_tags_position = segment->GetGlobalPosition( i_pos );
2416 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2421 /*****************************************************************************
2423 *****************************************************************************/
2424 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2430 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2432 tk = new mkv_track_t();
2433 tracks.push_back( tk );
2435 /* Init the track */
2436 memset( tk, 0, sizeof( mkv_track_t ) );
2438 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2439 tk->fmt.psz_language = strdup("English");
2440 tk->fmt.psz_description = NULL;
2442 tk->b_default = VLC_TRUE;
2443 tk->b_enabled = VLC_TRUE;
2444 tk->b_silent = VLC_FALSE;
2445 tk->i_number = tracks.size() - 1;
2446 tk->i_extra_data = 0;
2447 tk->p_extra_data = NULL;
2448 tk->psz_codec = NULL;
2449 tk->i_default_duration = 0;
2450 tk->f_timecodescale = 1.0;
2452 tk->b_inited = VLC_FALSE;
2453 tk->i_data_init = 0;
2454 tk->p_data_init = NULL;
2456 tk->psz_codec_name = NULL;
2457 tk->psz_codec_settings = NULL;
2458 tk->psz_codec_info_url = NULL;
2459 tk->psz_codec_download_url = NULL;
2461 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2463 for( i = 0; i < m->ListSize(); i++ )
2465 EbmlElement *l = (*m)[i];
2467 if( MKV_IS_ID( l, KaxTrackNumber ) )
2469 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2471 tk->i_number = uint32( tnum );
2472 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2474 else if( MKV_IS_ID( l, KaxTrackUID ) )
2476 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2478 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2480 else if( MKV_IS_ID( l, KaxTrackType ) )
2483 KaxTrackType &ttype = *(KaxTrackType*)l;
2485 switch( uint8(ttype) )
2489 tk->fmt.i_cat = AUDIO_ES;
2493 tk->fmt.i_cat = VIDEO_ES;
2495 case track_subtitle:
2496 psz_type = "subtitle";
2497 tk->fmt.i_cat = SPU_ES;
2500 psz_type = "unknown";
2501 tk->fmt.i_cat = UNKNOWN_ES;
2505 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2507 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2509 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2511 // tk->b_enabled = uint32( fenb );
2512 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2513 // uint32( fenb ) );
2515 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2517 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2519 tk->b_default = uint32( fdef );
2520 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2522 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2524 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2526 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2528 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2530 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2532 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2534 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2536 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2538 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2540 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2542 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2544 tk->i_default_duration = uint64(defd);
2545 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2547 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2549 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2551 tk->f_timecodescale = float( ttcs );
2552 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2554 else if( MKV_IS_ID( l, KaxTrackName ) )
2556 KaxTrackName &tname = *(KaxTrackName*)l;
2558 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2559 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2561 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2563 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2565 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2566 msg_Dbg( &sys.demuxer,
2567 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2569 else if( MKV_IS_ID( l, KaxCodecID ) )
2571 KaxCodecID &codecid = *(KaxCodecID*)l;
2573 tk->psz_codec = strdup( string( codecid ).c_str() );
2574 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2576 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2578 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2580 tk->i_extra_data = cpriv.GetSize();
2581 if( tk->i_extra_data > 0 )
2583 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2584 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2586 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2588 else if( MKV_IS_ID( l, KaxCodecName ) )
2590 KaxCodecName &cname = *(KaxCodecName*)l;
2592 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2593 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2595 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2597 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2598 MkvTree( sys.demuxer, 3, "Content Encodings" );
2599 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2601 EbmlElement *l2 = (*cencs)[i];
2602 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2604 MkvTree( sys.demuxer, 4, "Content Encoding" );
2605 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2606 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2608 EbmlElement *l3 = (*cenc)[i];
2609 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2611 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2612 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2614 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2616 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2617 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2619 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2621 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2622 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2624 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2626 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2627 MkvTree( sys.demuxer, 5, "Content Compression" );
2628 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2630 EbmlElement *l4 = (*compr)[i];
2631 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2633 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2634 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2635 if( uint32( compalg ) == 0 )
2637 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2642 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2649 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2656 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2661 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2663 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2665 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2666 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2668 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2670 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2672 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2673 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2675 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2677 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2679 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2680 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2682 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2684 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2686 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2688 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2690 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2692 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2694 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2696 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2699 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2702 for( j = 0; j < tkv->ListSize(); j++ )
2704 EbmlElement *l = (*tkv)[j];
2705 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2707 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2709 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2711 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2713 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2715 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2718 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2720 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2722 tk->fmt.video.i_width = uint16( vwidth );
2723 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2725 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2727 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2729 tk->fmt.video.i_height = uint16( vheight );
2730 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2732 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2734 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2736 tk->fmt.video.i_visible_width = uint16( vwidth );
2737 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2739 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2741 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2743 tk->fmt.video.i_visible_height = uint16( vheight );
2744 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2746 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2748 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2750 tk->f_fps = float( vfps );
2751 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2753 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2755 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2757 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2758 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2760 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2762 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2764 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2766 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2768 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2770 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2774 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2777 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2778 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2780 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2782 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2785 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2787 for( j = 0; j < tka->ListSize(); j++ )
2789 EbmlElement *l = (*tka)[j];
2791 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2793 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2795 tk->fmt.audio.i_rate = (int)float( afreq );
2796 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2798 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2800 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2802 tk->fmt.audio.i_channels = uint8( achan );
2803 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2805 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2807 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2809 tk->fmt.audio.i_bitspersample = uint8( abits );
2810 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2814 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2820 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2821 typeid(*l).name() );
2826 /*****************************************************************************
2828 *****************************************************************************/
2829 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2834 int i_upper_level = 0;
2836 msg_Dbg( &sys.demuxer, "| + Tracks" );
2838 /* Master elements */
2839 m = static_cast<EbmlMaster *>(tracks);
2840 m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2842 for( i = 0; i < m->ListSize(); i++ )
2844 EbmlElement *l = (*m)[i];
2846 if( MKV_IS_ID( l, KaxTrackEntry ) )
2848 ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2852 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2857 /*****************************************************************************
2859 *****************************************************************************/
2860 void matroska_segment_t::ParseInfo( EbmlElement *info )
2865 int i_upper_level = 0;
2867 msg_Dbg( &sys.demuxer, "| + Information" );
2869 /* Master elements */
2870 m = static_cast<EbmlMaster *>(info);
2871 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2873 for( i = 0; i < m->ListSize(); i++ )
2875 EbmlElement *l = (*m)[i];
2877 if( MKV_IS_ID( l, KaxSegmentUID ) )
2879 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2881 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2883 else if( MKV_IS_ID( l, KaxPrevUID ) )
2885 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2887 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2889 else if( MKV_IS_ID( l, KaxNextUID ) )
2891 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2893 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2895 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2897 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2899 i_timescale = uint64(tcs);
2901 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2904 else if( MKV_IS_ID( l, KaxDuration ) )
2906 KaxDuration &dur = *(KaxDuration*)l;
2908 f_duration = float(dur);
2910 msg_Dbg( &sys.demuxer, "| | + Duration=%f",
2913 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2915 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2917 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2919 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2920 psz_muxing_application );
2922 else if( MKV_IS_ID( l, KaxWritingApp ) )
2924 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2926 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2928 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2929 psz_writing_application );
2931 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2933 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2935 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2937 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2938 psz_segment_filename );
2940 else if( MKV_IS_ID( l, KaxTitle ) )
2942 KaxTitle &title = *(KaxTitle*)l;
2944 psz_title = UTF8ToStr( UTFstring( title ) );
2946 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2948 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2950 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2952 families.push_back(*uid);
2954 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2956 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2957 else if( MKV_IS_ID( l, KaxDateUTC ) )
2959 KaxDateUTC &date = *(KaxDateUTC*)l;
2964 i_date = date.GetEpochDate();
2965 memset( buffer, 0, 256 );
2966 if( gmtime_r( &i_date, &tmres ) &&
2967 asctime_r( &tmres, buffer ) )
2969 buffer[strlen( buffer)-1]= '\0';
2970 psz_date_utc = strdup( buffer );
2971 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
2977 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2981 f_duration *= i_timescale / 1000000.0;
2985 /*****************************************************************************
2987 *****************************************************************************/
2988 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2992 if( sys.title == NULL )
2994 sys.title = vlc_input_title_New();
2997 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
2998 for( i = 0; i < ca->ListSize(); i++ )
3000 EbmlElement *l = (*ca)[i];
3002 if( MKV_IS_ID( l, KaxChapterUID ) )
3004 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3005 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3007 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3009 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3010 chapters.b_display_seekpoint = uint8( flag ) == 0;
3012 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3014 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3016 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3017 chapters.i_start_time = uint64( start ) / I64C(1000);
3019 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3021 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3023 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3024 chapters.i_end_time = uint64( end ) / I64C(1000);
3026 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3028 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3030 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3033 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3034 for( j = 0; j < cd->ListSize(); j++ )
3036 EbmlElement *l= (*cd)[j];
3038 if( MKV_IS_ID( l, KaxChapterString ) )
3042 KaxChapterString &name =*(KaxChapterString*)l;
3043 for (k = 0; k < i_level; k++)
3044 chapters.psz_name += '+';
3045 chapters.psz_name += ' ';
3046 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3048 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3050 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3052 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3053 const char *psz = string( lang ).c_str();
3055 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3057 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3059 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3060 const char *psz = string( ct ).c_str();
3062 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3066 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3068 chapter_item_t new_sub_chapter;
3069 ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
3070 new_sub_chapter.psz_parent = &chapters;
3071 chapters.sub_chapters.push_back( new_sub_chapter );
3076 /*****************************************************************************
3078 *****************************************************************************/
3079 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
3084 int i_upper_level = 0;
3085 int i_default_edition = 0;
3088 /* Master elements */
3089 m = static_cast<EbmlMaster *>(chapters);
3090 m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3092 for( i = 0; i < m->ListSize(); i++ )
3094 EbmlElement *l = (*m)[i];
3096 if( MKV_IS_ID( l, KaxEditionEntry ) )
3098 chapter_edition_t edition;
3100 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3102 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3103 for( j = 0; j < E->ListSize(); j++ )
3105 EbmlElement *l = (*E)[j];
3107 if( MKV_IS_ID( l, KaxChapterAtom ) )
3109 chapter_item_t new_sub_chapter;
3110 ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3111 edition.chapters.push_back( new_sub_chapter );
3113 else if( MKV_IS_ID( l, KaxEditionUID ) )
3115 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3117 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3119 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3121 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3123 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3124 i_default_edition = editions.size();
3128 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3131 editions.push_back( edition );
3135 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3139 for( i = 0; i < editions.size(); i++ )
3141 editions[i].RefreshChapters( *sys.title );
3144 i_current_edition = i_default_edition;
3146 if ( editions[i_default_edition].b_ordered )
3148 /* update the duration of the segment according to the sum of all sub chapters */
3149 f_dur = editions[i_default_edition].Duration() / I64C(1000);
3155 /*****************************************************************************
3156 * InformationCreate:
3157 *****************************************************************************/
3158 static void InformationCreate( demux_t *p_demux )
3160 demux_sys_t *p_sys = p_demux->p_sys;
3161 matroska_stream_t *p_stream = p_sys->Stream();
3162 matroska_segment_t *p_segment = p_stream->Segment();
3165 p_sys->meta = vlc_meta_New();
3167 if( p_segment->psz_title )
3169 vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_segment->psz_title );
3171 if( p_segment->psz_date_utc )
3173 vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_segment->psz_date_utc );
3175 if( p_segment->psz_segment_filename )
3177 vlc_meta_Add( p_sys->meta, _("Segment filename"), p_segment->psz_segment_filename );
3179 if( p_segment->psz_muxing_application )
3181 vlc_meta_Add( p_sys->meta, _("Muxing application"), p_segment->psz_muxing_application );
3183 if( p_segment->psz_writing_application )
3185 vlc_meta_Add( p_sys->meta, _("Writing application"), p_segment->psz_writing_application );
3188 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
3190 mkv_track_t *tk = p_segment->tracks[i_track];
3191 vlc_meta_t *mtk = vlc_meta_New();
3193 p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
3194 sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
3195 p_sys->meta->track[p_sys->meta->i_track++] = mtk;
3197 if( tk->fmt.psz_description )
3199 vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3201 if( tk->psz_codec_name )
3203 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3205 if( tk->psz_codec_settings )
3207 vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
3209 if( tk->psz_codec_info_url )
3211 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3213 if( tk->psz_codec_download_url )
3215 vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
3219 if( p_segment->i_tags_position >= 0 )
3221 vlc_bool_t b_seekable;
3223 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
3226 LoadTags( p_demux );
3232 /*****************************************************************************
3234 *****************************************************************************/
3236 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3238 #define idx index[i_index]
3240 idx.i_block_number= -1;
3241 idx.i_position = cluster->GetElementPosition();
3243 idx.b_key = VLC_TRUE;
3246 if( i_index >= i_index_max )
3248 i_index_max += 1024;
3249 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3254 static char * UTF8ToStr( const UTFstring &u )
3263 p = dst = (char*)malloc( i_src + 1);
3282 void chapter_edition_t::RefreshChapters( input_title_t & title )
3284 int64_t i_prev_user_time = 0;
3285 std::vector<chapter_item_t>::iterator index = chapters.begin();
3287 while ( index != chapters.end() )
3289 i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3294 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3296 int64_t i_user_time = i_prev_user_time;
3298 // first the sub-chapters, and then ourself
3299 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3300 while ( index != sub_chapters.end() )
3302 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3308 i_user_start_time = i_prev_user_time;
3309 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3311 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3315 i_user_end_time = i_user_time;
3320 std::sort( sub_chapters.begin(), sub_chapters.end() );
3321 i_user_start_time = i_start_time;
3322 i_user_end_time = i_end_time;
3325 if (b_display_seekpoint)
3327 seekpoint_t *sk = vlc_seekpoint_New();
3329 // sk->i_level = i_level;
3330 sk->i_time_offset = i_start_time;
3331 sk->psz_name = strdup( psz_name.c_str() );
3333 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3334 title.i_seekpoint++;
3335 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3336 title.seekpoint[title.i_seekpoint-1] = sk;
3339 i_seekpoint_num = title.i_seekpoint;
3341 return i_user_end_time;
3344 double chapter_edition_t::Duration() const
3346 double f_result = 0.0;
3348 if ( chapters.size() )
3350 std::vector<chapter_item_t>::const_iterator index = chapters.end();
3352 f_result = (*index).i_user_end_time;
3358 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3360 const chapter_item_t *psz_result = NULL;
3362 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3364 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3365 while ( index != sub_chapters.end() && psz_result == NULL )
3367 psz_result = (*index).FindTimecode( i_user_timecode );
3371 if ( psz_result == NULL )
3378 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3380 const chapter_item_t *psz_result = NULL;
3382 std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3383 while ( index != chapters.end() && psz_result == NULL )
3385 psz_result = (*index).FindTimecode( i_user_timecode );
3392 void demux_sys_t::PreloadFamily( )
3394 matroska_stream_t *p_stream = Stream();
3397 matroska_segment_t *p_segment = p_stream->Segment();
3400 for (size_t i=0; i<streams.size(); i++)
3402 streams[i]->PreloadFamily( *p_segment );
3408 void matroska_stream_t::PreloadFamily( const matroska_segment_t & of_segment )
3410 for (size_t i=0; i<segments.size(); i++)
3412 segments[i]->PreloadFamily( of_segment );
3416 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3421 for (size_t i=0; i<families.size(); i++)
3423 for (size_t j=0; j<of_segment.families.size(); j++)
3425 if ( families[i] == of_segment.families[j] )
3433 // preload all the linked segments for all preloaded segments
3434 void demux_sys_t::PreloadLinked( )
3436 size_t i_prealoaded;
3439 for (size_t i=0; i<streams.size(); i++)
3441 i_prealoaded += streams[i]->PreloadLinked( *this );
3443 } while ( i_prealoaded ); // worst case: will stop when all segments are preloaded
3446 size_t matroska_stream_t::PreloadLinked( const demux_sys_t & of_sys )
3448 size_t i_result = 0;
3449 for (size_t i=0; i<segments.size(); i++)
3451 i_result += segments[i]->PreloadLinked( of_sys, segments );
3457 size_t matroska_segment_t::PreloadLinked( const demux_sys_t & of_sys, std::vector<matroska_segment_t*> & segments )
3459 size_t i_result = 0;
3460 if ( prev_segment_uid.GetBuffer() )
3462 matroska_segment_t *p_segment = of_sys.FindSegment( prev_segment_uid );
3465 if ( p_segment->Preload( ) )
3467 segments.push_back( p_segment );
3472 if ( next_segment_uid.GetBuffer() )
3474 matroska_segment_t *p_segment = of_sys.FindSegment( next_segment_uid );
3477 if ( p_segment->Preload( ) )
3479 segments.push_back( p_segment );
3487 void demux_sys_t::PreparePlayback( )
3489 matroska_stream_t *p_stream = Stream();
3492 p_stream->PreparePlayback( );
3496 void matroska_stream_t::PreparePlayback( )
3502 for (i=0; i<segments.size(); i++)
3504 f_duration += segments[i]->f_duration;
3507 // sort segment order
3508 std::sort( segments.begin(), segments.end(), matroska_segment_t::CompareSegmentUIDs );
3511 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3513 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3514 if ( *p_itema == p_item_b->prev_segment_uid )
3517 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3518 if ( *p_itema == p_item_b->segment_uid )
3524 bool matroska_segment_t::Preload( )
3529 EbmlElement *el = NULL;
3533 while( ( el = ep->Get() ) != NULL )
3535 if( MKV_IS_ID( el, KaxInfo ) )
3539 else if( MKV_IS_ID( el, KaxTracks ) )
3543 else if( MKV_IS_ID( el, KaxSeekHead ) )
3545 ParseSeekHead( el );
3547 else if( MKV_IS_ID( el, KaxCues ) )
3549 msg_Dbg( &sys.demuxer, "| + Cues" );
3551 else if( MKV_IS_ID( el, KaxCluster ) )
3553 msg_Dbg( &sys.demuxer, "| + Cluster" );
3555 cluster = (KaxCluster*)el;
3557 i_start_pos = cluster->GetElementPosition();
3560 /* stop parsing the stream */
3563 else if( MKV_IS_ID( el, KaxAttachments ) )
3565 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3567 else if( MKV_IS_ID( el, KaxChapters ) )
3569 msg_Dbg( &sys.demuxer, "| + Chapters" );
3570 ParseChapters( el );
3572 else if( MKV_IS_ID( el, KaxTag ) )
3574 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3578 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3587 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3589 matroska_segment_t *p_segment = NULL;
3590 for (size_t i=0; i<streams.size() && p_segment == NULL; i++)
3592 p_segment = streams[i]->FindSegment( uid );
3597 matroska_segment_t *matroska_stream_t::FindSegment( const EbmlBinary & uid ) const
3599 for (size_t i=0; i<segments.size(); i++)
3601 if ( segments[i]->segment_uid == uid )