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 );
521 void InformationCreate( );
522 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
523 bool Select( mtime_t i_start_time );
525 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
528 class matroska_stream_t
531 matroska_stream_t( demux_sys_t & demuxer )
534 ,i_current_segment(-1)
548 std::vector<matroska_segment_t*> segments;
549 size_t i_current_segment;
553 /* duration of the stream */
556 inline matroska_segment_t *Segment()
558 if ( i_current_segment >= 0 && size_t(i_current_segment) < segments.size() )
559 return segments[i_current_segment];
563 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
565 void PreloadFamily( const matroska_segment_t & segment );
566 size_t PreloadLinked( const demux_sys_t & of_sys );
567 void PreparePlayback( );
573 demux_sys_t( demux_t & demux )
580 ,i_current_stream(-1)
585 for (size_t i=0; i<streams.size(); i++)
587 for ( size_t i=0; i<opened_segments.size(); i++ )
588 delete opened_segments[i];
596 mtime_t i_chapter_time;
600 input_title_t *title;
602 std::vector<matroska_stream_t*> streams;
603 int i_current_stream;
604 std::vector<matroska_segment_t*> opened_segments;
606 inline matroska_stream_t *Stream()
608 if ( i_current_stream >= 0 && size_t(i_current_stream) < streams.size() )
609 return streams[i_current_stream];
613 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
614 void PreloadFamily( );
615 void PreloadLinked( );
616 void PreparePlayback( );
617 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
620 static int Demux ( demux_t * );
621 static int Control( demux_t *, int, va_list );
622 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
624 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
626 static char *UTF8ToStr ( const UTFstring &u );
628 /*****************************************************************************
629 * Open: initializes matroska demux structures
630 *****************************************************************************/
631 static int Open( vlc_object_t * p_this )
633 demux_t *p_demux = (demux_t*)p_this;
635 matroska_stream_t *p_stream;
636 matroska_segment_t *p_segment;
638 std::string s_path, s_filename;
639 vlc_stream_io_callback *p_io_callback;
640 EbmlStream *p_io_stream;
642 /* peek the begining */
643 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
645 /* is a valid file */
646 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
647 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
649 /* Set the demux function */
650 p_demux->pf_demux = Demux;
651 p_demux->pf_control = Control;
652 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
654 p_io_callback = new vlc_stream_io_callback( p_demux->s );
655 p_io_stream = new EbmlStream( *p_io_callback );
657 if( p_io_stream == NULL )
659 msg_Err( p_demux, "failed to create EbmlStream" );
660 delete p_io_callback;
665 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
666 if( p_stream == NULL )
668 msg_Err( p_demux, "cannot find KaxSegment" );
671 p_sys->streams.push_back( p_stream );
672 p_sys->i_current_stream = 0;
674 p_stream->p_in = p_io_callback;
675 p_stream->p_es = p_io_stream;
677 for (size_t i=0; i<p_stream->segments.size(); i++)
679 p_stream->segments[i]->Preload();
681 p_stream->i_current_segment = 0;
683 p_segment = p_stream->Segment();
684 if( p_segment->cluster == NULL )
686 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
689 // reset the stream reading to the first cluster of the segment used
690 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
692 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
693 /* TODO handle multi-segment files */
694 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
696 // assume it's a regular file
697 // get the directory path
698 s_path = p_demux->psz_path;
699 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
701 s_path = s_path.substr(0,s_path.length()-1);
705 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
707 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
711 struct dirent *p_file_item;
712 DIR *p_src_dir = opendir(s_path.c_str());
714 if (p_src_dir != NULL)
716 while ((p_file_item = (dirent *) readdir(p_src_dir)))
718 if (strlen(p_file_item->d_name) > 4)
720 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
722 if (!s_filename.compare(p_demux->psz_path))
723 continue; // don't reuse the original opened file
725 #if defined(__GNUC__) && (__GNUC__ < 3)
726 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
727 !s_filename.compare("mka", s_filename.length() - 3, 3))
729 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
730 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
733 // test wether this file belongs to the our family
734 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
735 EbmlStream *p_estream = new EbmlStream(*p_file_io);
737 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
738 if ( p_stream == NULL )
740 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
746 p_stream->p_in = p_file_io;
747 p_stream->p_es = p_estream;
748 p_sys->streams.push_back( p_stream );
753 closedir( p_src_dir );
757 p_sys->PreloadFamily( );
758 p_sys->PreloadLinked( );
759 p_sys->PreparePlayback( );
761 if( !p_segment->b_cues || p_segment->i_index <= 0 )
763 msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
765 p_segment->IndexAppendCluster( p_segment->cluster );
767 p_segment->b_cues = VLC_FALSE;
770 /* add information */
771 p_segment->InformationCreate( );
773 if ( !p_segment->Select( 0 ) )
775 msg_Err( p_demux, "cannot use the segment" );
786 /*****************************************************************************
787 * Close: frees unused data
788 *****************************************************************************/
789 static void Close( vlc_object_t *p_this )
791 demux_t *p_demux = (demux_t*)p_this;
792 demux_sys_t *p_sys = p_demux->p_sys;
797 /*****************************************************************************
799 *****************************************************************************/
800 static int Control( demux_t *p_demux, int i_query, va_list args )
802 demux_sys_t *p_sys = p_demux->p_sys;
803 matroska_stream_t *p_stream = p_sys->Stream();
804 if ( p_stream == NULL ) return VLC_EGENERIC;
805 matroska_segment_t *p_segment = p_stream->Segment();
810 vlc_meta_t **pp_meta;
815 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
816 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
819 case DEMUX_GET_LENGTH:
820 pi64 = (int64_t*)va_arg( args, int64_t * );
821 if( p_stream->f_duration > 0.0 )
823 *pi64 = (int64_t)(p_stream->f_duration * 1000);
828 case DEMUX_GET_POSITION:
829 pf = (double*)va_arg( args, double * );
830 if ( p_stream->f_duration > 0.0 )
831 *pf = (double)p_sys->i_pts / (1000.0 * p_stream->f_duration);
834 case DEMUX_SET_POSITION:
835 f = (double)va_arg( args, double );
836 Seek( p_demux, -1, f, NULL );
840 pi64 = (int64_t*)va_arg( args, int64_t * );
841 *pi64 = p_sys->i_pts;
844 case DEMUX_GET_TITLE_INFO:
845 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
847 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
848 int *pi_int = (int*)va_arg( args, int* );
851 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
853 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
859 case DEMUX_SET_TITLE:
860 /* TODO handle editions as titles & DVD titles as well */
861 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
867 case DEMUX_SET_SEEKPOINT:
868 /* FIXME do a better implementation */
869 i_skp = (int)va_arg( args, int );
871 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
873 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
874 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
875 p_demux->info.i_seekpoint = i_skp;
887 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
898 if( sys.demuxer.b_die )
904 i_level = ep->GetLevel();
906 if( el == NULL && *pp_block != NULL )
908 /* update the index */
909 #define idx index[i_index - 1]
910 if( i_index > 0 && idx.i_time == -1 )
912 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
913 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
921 if( ep->GetLevel() > 1 )
926 msg_Warn( &sys.demuxer, "EOF" );
933 if( MKV_IS_ID( el, KaxCluster ) )
935 cluster = (KaxCluster*)el;
937 /* add it to the index */
939 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
941 IndexAppendCluster( cluster );
944 // reset silent tracks
945 for (size_t i=0; i<tracks.size(); i++)
947 tracks[i]->b_silent = VLC_FALSE;
952 else if( MKV_IS_ID( el, KaxCues ) )
954 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
959 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
962 else if( i_level == 2 )
964 if( MKV_IS_ID( el, KaxClusterTimecode ) )
966 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
968 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
969 cluster->InitTimecode( uint64( ctc ), i_timescale );
971 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
975 else if( MKV_IS_ID( el, KaxBlockGroup ) )
980 else if( i_level == 3 )
982 if( MKV_IS_ID( el, KaxBlock ) )
984 *pp_block = (KaxBlock*)el;
986 (*pp_block)->ReadData( es.I_O() );
987 (*pp_block)->SetParent( *cluster );
991 else if( MKV_IS_ID( el, KaxBlockDuration ) )
993 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
995 dur.ReadData( es.I_O() );
996 *pi_duration = uint64( dur );
998 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1000 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1002 ref.ReadData( es.I_O() );
1003 if( *pi_ref1 == -1 )
1005 *pi_ref1 = int64( ref );
1009 *pi_ref2 = int64( ref );
1012 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1014 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1015 track_num.ReadData( es.I_O() );
1017 for (size_t i=0; i<tracks.size(); i++)
1019 if ( tracks[i]->i_number == uint32(track_num))
1021 tracks[i]->b_silent = VLC_TRUE;
1029 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1030 return VLC_EGENERIC;
1035 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1038 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1039 memcpy( p_block->p_buffer, p_mem, i_mem );
1040 //p_block->i_rate = p_input->stream.control.i_rate;
1044 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1045 mtime_t i_duration )
1047 demux_sys_t *p_sys = p_demux->p_sys;
1048 matroska_stream_t *p_stream = p_sys->Stream();
1049 matroska_segment_t *p_segment = p_stream->Segment();
1055 #define tk p_segment->tracks[i_track]
1056 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1058 if( tk->i_number == block->TrackNum() )
1064 if( i_track >= p_segment->tracks.size() )
1066 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1069 if( tk->p_es == NULL )
1071 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1074 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1076 return; /* discard audio packets that shouldn't be rendered */
1079 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1082 tk->b_inited = VLC_FALSE;
1086 /* First send init data */
1087 if( !tk->b_inited && tk->i_data_init > 0 )
1091 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1092 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1093 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1095 tk->b_inited = VLC_TRUE;
1098 for( i = 0; i < block->NumberFrames(); i++ )
1101 DataBuffer &data = block->GetBuffer(i);
1103 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1105 if( p_block == NULL )
1110 #if defined(HAVE_ZLIB_H)
1111 if( tk->i_compression_type )
1113 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1117 // TODO implement correct timestamping when B frames are used
1118 if( tk->fmt.i_cat != VIDEO_ES )
1120 p_block->i_dts = p_block->i_pts = i_pts;
1124 p_block->i_dts = i_pts;
1128 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1130 p_block->i_length = i_duration * 1000;
1132 msg_Warn( p_demux, "Sending block %d", p_block );
1133 es_out_Send( p_demux->out, tk->p_es, p_block );
1135 /* use time stamp only for first block */
1142 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1144 int i_upper_lvl = 0;
1146 EbmlElement *p_l0, *p_l1, *p_l2;
1147 bool b_keep_stream = false, b_keep_segment;
1149 // verify the EBML Header
1150 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1155 p_l0->SkipData(*p_estream, EbmlHead_Context);
1158 // find all segments in this file
1159 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1165 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1169 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1172 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1173 b_keep_segment = false;
1175 ep = new EbmlParser(p_estream, p_l0);
1176 p_segment1->ep = ep;
1177 p_segment1->segment = (KaxSegment*)p_l0;
1179 while ((p_l1 = ep->Get()))
1181 if (MKV_IS_ID(p_l1, KaxInfo))
1183 // find the families of this segment
1184 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1186 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1187 for( i = 0; i < p_info->ListSize(); i++ )
1189 EbmlElement *l = (*p_info)[i];
1191 if( MKV_IS_ID( l, KaxSegmentUID ) )
1193 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1194 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1195 if ( !b_keep_segment )
1196 break; // this segment is already known
1197 opened_segments.push_back( p_segment1 );
1198 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1200 else if( MKV_IS_ID( l, KaxPrevUID ) )
1202 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1204 else if( MKV_IS_ID( l, KaxNextUID ) )
1206 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1208 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1210 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1211 std::vector<KaxSegmentFamily>::iterator iter;
1212 p_segment1->families.push_back( *p_fam );
1218 if ( b_keep_segment )
1220 b_keep_stream = true;
1221 p_stream1->segments.push_back( p_segment1 );
1227 p_l0->SkipData(*p_estream, EbmlHead_Context);
1228 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1231 if ( !b_keep_stream )
1240 bool matroska_segment_t::Select( mtime_t i_start_time )
1245 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1246 for( i_track = 0; i_track < tracks.size(); i_track++ )
1248 #define tk tracks[i_track]
1249 if( tk->fmt.i_cat == UNKNOWN_ES )
1251 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1256 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1258 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1260 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1261 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1265 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1267 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1268 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1269 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1271 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1272 if( tk->fmt.i_extra > 0 )
1274 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1275 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1279 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1280 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1282 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1284 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1286 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1288 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1290 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1292 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1293 tk->fmt.b_packetized = VLC_FALSE;
1294 tk->fmt.i_extra = tk->i_extra_data;
1295 tk->fmt.p_extra = malloc( tk->i_extra_data );
1296 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1300 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1303 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1305 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1306 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1309 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1310 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1311 tk->fmt.i_codec = p_box->i_type;
1312 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1313 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1314 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1315 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1316 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1317 MP4_FreeBox_sample_vide( p_box );
1318 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1320 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1322 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1324 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1325 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1329 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1331 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1333 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1334 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1335 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1336 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1337 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1339 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1340 if( tk->fmt.i_extra > 0 )
1342 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1343 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1347 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1348 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1349 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1351 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1353 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1355 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1357 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1359 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1361 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1363 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1364 tk->fmt.i_extra = tk->i_extra_data;
1365 tk->fmt.p_extra = malloc( tk->i_extra_data );
1366 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1368 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1370 int i, i_offset = 1, i_size[3], i_extra;
1373 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1375 /* Split the 3 headers */
1376 if( tk->p_extra_data[0] != 0x02 )
1377 msg_Err( &sys.demuxer, "invalid vorbis header" );
1379 for( i = 0; i < 2; i++ )
1382 while( i_offset < tk->i_extra_data )
1384 i_size[i] += tk->p_extra_data[i_offset];
1385 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1389 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1390 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1391 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1393 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1394 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1395 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1396 for( i = 0; i < 3; i++ )
1398 *(p_extra++) = i_size[i] >> 8;
1399 *(p_extra++) = i_size[i] & 0xFF;
1400 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1402 p_extra += i_size[i];
1403 i_extra += i_size[i];
1406 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1407 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1409 int i_profile, i_srate;
1410 static unsigned int i_sample_rates[] =
1412 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1413 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1416 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1417 /* create data for faad (MP4DecSpecificDescrTag)*/
1419 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1423 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1427 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1436 for( i_srate = 0; i_srate < 13; i_srate++ )
1438 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1443 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1445 tk->fmt.i_extra = 2;
1446 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1447 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1448 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1450 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1451 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1452 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1454 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1456 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1460 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1462 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1464 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1466 /* FIXME: support this codec */
1467 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1468 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1470 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1472 /* FIXME: support this codec */
1473 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1474 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1476 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1478 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1479 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1481 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1482 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1483 !strcmp( tk->psz_codec, "S_SSA" ) ||
1484 !strcmp( tk->psz_codec, "S_ASS" ))
1486 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1487 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1489 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1491 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1492 if( tk->i_extra_data )
1495 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1496 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1497 p_buf[tk->i_extra_data] = '\0';
1499 p_start = strstr( p_buf, "size:" );
1500 if( sscanf( p_start, "size: %dx%d",
1501 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1503 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 );
1507 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1512 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1514 /* FIXME: support this codec */
1515 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1516 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1520 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1521 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1525 tk->fmt.i_priority = 1000;
1528 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1530 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1534 sys.i_start_pts = i_start_time;
1537 // reset the stream reading to the first cluster of the segment used
1538 es.I_O().setFilePointer( i_start_pos );
1543 void matroska_segment_t::UnSelect( )
1547 for( i_track = 0; i_track < tracks.size(); i_track++ )
1549 #define tk tracks[i_track]
1550 if ( tk->p_es != NULL )
1552 es_out_Del( sys.demuxer.out, tk->p_es );
1559 static void UpdateCurrentToChapter( demux_t & demux )
1561 demux_sys_t & sys = *demux.p_sys;
1562 matroska_stream_t *p_stream = sys.Stream();
1563 matroska_segment_t *p_segment = p_stream->Segment();
1564 const chapter_item_t *psz_curr_chapter;
1566 /* update current chapter/seekpoint */
1567 if ( p_segment->editions.size())
1569 /* 1st, we need to know in which chapter we are */
1570 psz_curr_chapter = p_segment->editions[p_segment->i_current_edition].FindTimecode( sys.i_pts );
1572 /* we have moved to a new chapter */
1573 if (p_segment->psz_current_chapter != NULL && psz_curr_chapter != NULL && p_segment->psz_current_chapter != psz_curr_chapter)
1575 if (p_segment->psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1577 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1578 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1581 if (p_segment->editions[p_segment->i_current_edition].b_ordered )
1583 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1584 if (p_segment->psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1585 Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
1586 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1587 /* only seek after each duration >= end timecode of the current chapter */
1590 // p_segment->i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1591 // p_segment->i_start_pts = psz_curr_chapter->i_user_start_time;
1593 p_segment->psz_current_chapter = psz_curr_chapter;
1597 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
1599 demux_sys_t *p_sys = p_demux->p_sys;
1600 matroska_stream_t *p_stream = p_sys->Stream();
1601 matroska_segment_t *p_segment = p_stream->Segment();
1602 mtime_t i_time_offset = 0;
1605 int64_t i_block_duration;
1606 int64_t i_block_ref1;
1607 int64_t i_block_ref2;
1610 int i_track_skipping;
1613 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1614 if( i_date < 0 && f_percent < 0 )
1616 msg_Warn( p_demux, "cannot seek nowhere !" );
1619 if( f_percent > 1.0 )
1621 msg_Warn( p_demux, "cannot seek so far !" );
1625 delete p_segment->ep;
1626 p_segment->ep = new EbmlParser( p_stream->p_es, p_segment->segment );
1627 p_segment->cluster = NULL;
1629 /* seek without index or without date */
1630 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1632 if (p_stream->f_duration >= 0)
1634 i_date = int64_t( f_percent * p_stream->f_duration * 1000.0 );
1638 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1640 msg_Dbg( p_demux, "inacurate way of seeking" );
1641 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1643 if( p_segment->index[i_index].i_position >= i_pos)
1648 if( i_index == p_segment->i_index )
1653 i_date = p_segment->index[i_index].i_time;
1656 if( p_segment->index[i_index].i_position < i_pos )
1660 msg_Warn( p_demux, "searching for cluster, could take some time" );
1662 /* search a cluster */
1663 while( ( el = p_sys->ep->Get() ) != NULL )
1665 if( MKV_IS_ID( el, KaxCluster ) )
1667 KaxCluster *cluster = (KaxCluster*)el;
1669 /* add it to the index */
1670 p_segment->IndexAppendCluster( cluster );
1672 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1674 p_sys->cluster = cluster;
1685 // find the actual time for an ordered edition
1686 if ( psz_chapter == NULL )
1688 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered )
1690 /* 1st, we need to know in which chapter we are */
1691 psz_chapter = p_segment->editions[p_segment->i_current_edition].FindTimecode( i_date );
1695 if ( psz_chapter != NULL )
1697 p_segment->psz_current_chapter = psz_chapter;
1698 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
1699 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1700 p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
1703 for( ; i_index < p_segment->i_index; i_index++ )
1705 if( p_segment->index[i_index].i_time + i_time_offset > i_date )
1716 msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1717 p_segment->index[i_index].i_time,
1718 (int)( 100 * p_segment->index[i_index].i_position /
1719 stream_Size( p_demux->s ) ) );
1721 p_stream->p_in->setFilePointer( p_segment->index[i_index].i_position,
1724 p_sys->i_start_pts = i_date;
1726 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1728 /* now parse until key frame */
1729 #define tk p_segment->tracks[i_track]
1730 i_track_skipping = 0;
1731 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1733 if( tk->fmt.i_cat == VIDEO_ES )
1735 tk->b_search_keyframe = VLC_TRUE;
1738 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
1742 while( i_track_skipping > 0 )
1744 if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1746 msg_Warn( p_demux, "cannot get block EOF?" );
1751 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1753 if( tk->i_number == block->TrackNum() )
1759 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1761 if( i_track < p_segment->tracks.size() )
1763 if( p_sys->i_pts >= p_sys->i_start_pts )
1765 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1766 i_track_skipping = 0;
1768 else if( tk->fmt.i_cat == VIDEO_ES )
1770 if( i_block_ref1 == -1 && tk->b_search_keyframe )
1772 tk->b_search_keyframe = VLC_FALSE;
1775 if( !tk->b_search_keyframe )
1777 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1787 /*****************************************************************************
1788 * Demux: reads and demuxes data packets
1789 *****************************************************************************
1790 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1791 *****************************************************************************/
1792 static int Demux( demux_t *p_demux)
1794 demux_sys_t *p_sys = p_demux->p_sys;
1795 matroska_stream_t *p_stream = p_sys->Stream();
1796 matroska_segment_t *p_segment = p_stream->Segment();
1797 if ( p_segment == NULL ) return 0;
1798 int i_block_count = 0;
1801 int64_t i_block_duration;
1802 int64_t i_block_ref1;
1803 int64_t i_block_ref2;
1807 if( p_sys->i_pts >= p_sys->i_start_pts )
1808 UpdateCurrentToChapter( *p_demux );
1810 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered && p_segment->psz_current_chapter == NULL )
1812 /* nothing left to read in this ordered edition */
1813 if ( p_stream->i_current_segment == p_stream->segments.size() - 1)
1815 p_segment->UnSelect( );
1817 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1819 /* switch to the next segment (TODO update the duration) */
1820 p_stream->i_current_segment++;
1821 p_segment = p_stream->Segment();
1822 if ( !p_segment || !p_segment->Select( 0 ) )
1827 if( p_segment->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1829 if ( p_segment->editions.size() && p_segment->editions[p_segment->i_current_edition].b_ordered )
1831 // check if there are more chapters to read
1832 if ( p_segment->psz_current_chapter != NULL )
1834 p_sys->i_pts = p_segment->psz_current_chapter->i_user_end_time;
1840 msg_Warn( p_demux, "cannot get block EOF?" );
1841 p_segment->UnSelect( );
1843 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1845 /* switch to the next segment */
1846 p_stream->i_current_segment++;
1847 p_segment = p_stream->Segment();
1848 if ( !p_segment || !p_segment->Select( 0 ) )
1849 // no more segments in this stream
1855 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1857 if( p_sys->i_pts >= p_sys->i_start_pts )
1859 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1862 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1867 // TODO optimize when there is need to leave or when seeking has been called
1868 if( i_block_count > 5 )
1877 /*****************************************************************************
1879 *****************************************************************************/
1880 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1886 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1888 if( i_size <= 0 || mb_eof )
1893 return stream_Read( s, p_buffer, i_size );
1895 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1901 case seek_beginning:
1905 i_pos = stream_Size( s ) - i_offset;
1908 i_pos= stream_Tell( s ) + i_offset;
1912 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1919 if( stream_Seek( s, i_pos ) )
1925 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1929 uint64 vlc_stream_io_callback::getFilePointer( void )
1931 return stream_Tell( s );
1933 void vlc_stream_io_callback::close( void )
1939 /*****************************************************************************
1940 * Ebml Stream parser
1941 *****************************************************************************/
1942 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1950 for( i = 1; i < 6; i++ )
1956 mb_keep = VLC_FALSE;
1959 EbmlParser::~EbmlParser( void )
1963 for( i = 1; i < mi_level; i++ )
1969 mb_keep = VLC_FALSE;
1973 void EbmlParser::Up( void )
1975 if( mi_user_level == mi_level )
1977 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1983 void EbmlParser::Down( void )
1989 void EbmlParser::Keep( void )
1994 int EbmlParser::GetLevel( void )
1996 return mi_user_level;
1999 void EbmlParser::Reset( void )
2001 while ( mi_level > 0)
2003 delete m_el[mi_level];
2004 m_el[mi_level] = NULL;
2007 mi_user_level = mi_level = 1;
2008 #if LIBEBML_VERSION >= 0x000704
2009 // a little faster and cleaner
2010 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2012 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2016 EbmlElement *EbmlParser::Get( void )
2020 if( mi_user_level != mi_level )
2026 EbmlElement *ret = m_got;
2032 if( m_el[mi_level] )
2034 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2037 delete m_el[mi_level];
2039 mb_keep = VLC_FALSE;
2042 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
2053 delete m_el[mi_level - 1];
2054 m_got = m_el[mi_level -1] = m_el[mi_level];
2055 m_el[mi_level] = NULL;
2062 else if( m_el[mi_level] == NULL )
2064 fprintf( stderr," m_el[mi_level] == NULL\n" );
2067 return m_el[mi_level];
2071 /*****************************************************************************
2073 * * LoadCues : load the cues element and update index
2075 * * LoadTags : load ... the tags element
2077 * * InformationCreate : create all information, load tags if present
2079 *****************************************************************************/
2080 void matroska_segment_t::LoadCues( )
2082 int64_t i_sav_position = es.I_O().getFilePointer();
2084 EbmlElement *el, *cues;
2086 /* *** Load the cue if found *** */
2087 if( i_cues_position < 0 )
2090 vlc_bool_t b_seekable;
2092 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2096 msg_Dbg( &sys.demuxer, "loading cues" );
2097 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2098 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2102 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2103 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2107 ep = new EbmlParser( &es, cues );
2108 while( ( el = ep->Get() ) != NULL )
2110 if( MKV_IS_ID( el, KaxCuePoint ) )
2112 #define idx index[i_index]
2115 idx.i_block_number= -1;
2116 idx.i_position = -1;
2118 idx.b_key = VLC_TRUE;
2121 while( ( el = ep->Get() ) != NULL )
2123 if( MKV_IS_ID( el, KaxCueTime ) )
2125 KaxCueTime &ctime = *(KaxCueTime*)el;
2127 ctime.ReadData( es.I_O() );
2129 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2131 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2134 while( ( el = ep->Get() ) != NULL )
2136 if( MKV_IS_ID( el, KaxCueTrack ) )
2138 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2140 ctrack.ReadData( es.I_O() );
2141 idx.i_track = uint16( ctrack );
2143 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2145 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2147 ccpos.ReadData( es.I_O() );
2148 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2150 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2152 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2154 cbnum.ReadData( es.I_O() );
2155 idx.i_block_number = uint32( cbnum );
2159 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2166 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2172 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2173 " track=%d bnum=%d", idx.i_time, idx.i_position,
2174 idx.i_track, idx.i_block_number );
2178 if( i_index >= i_index_max )
2180 i_index_max += 1024;
2181 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2187 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2195 msg_Dbg( &sys.demuxer, "loading cues done." );
2196 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2199 void matroska_segment_t::LoadTags( )
2201 int64_t i_sav_position = es.I_O().getFilePointer();
2203 EbmlElement *el, *tags;
2205 msg_Dbg( &sys.demuxer, "loading tags" );
2206 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2207 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2211 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2212 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2216 msg_Dbg( &sys.demuxer, "Tags" );
2217 ep = new EbmlParser( &es, tags );
2218 while( ( el = ep->Get() ) != NULL )
2220 if( MKV_IS_ID( el, KaxTag ) )
2222 msg_Dbg( &sys.demuxer, "+ Tag" );
2224 while( ( el = ep->Get() ) != NULL )
2226 if( MKV_IS_ID( el, KaxTagTargets ) )
2228 msg_Dbg( &sys.demuxer, "| + Targets" );
2230 while( ( el = ep->Get() ) != NULL )
2232 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2236 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2238 msg_Dbg( &sys.demuxer, "| + General" );
2240 while( ( el = ep->Get() ) != NULL )
2242 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2246 else if( MKV_IS_ID( el, KaxTagGenres ) )
2248 msg_Dbg( &sys.demuxer, "| + Genres" );
2250 while( ( el = ep->Get() ) != NULL )
2252 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2256 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2258 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2260 while( ( el = ep->Get() ) != NULL )
2262 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2266 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2268 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2270 while( ( el = ep->Get() ) != NULL )
2272 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2276 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2278 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2280 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2282 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2284 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2286 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2288 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2290 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2292 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2294 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2296 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2298 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2300 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2302 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2306 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2313 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2319 msg_Dbg( &sys.demuxer, "loading tags done." );
2320 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2323 /*****************************************************************************
2325 *****************************************************************************/
2326 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2331 int i_upper_level = 0;
2333 msg_Dbg( &sys.demuxer, "| + Seek head" );
2335 /* Master elements */
2336 m = static_cast<EbmlMaster *>(seekhead);
2337 m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2339 for( i = 0; i < m->ListSize(); i++ )
2341 EbmlElement *l = (*m)[i];
2343 if( MKV_IS_ID( l, KaxSeek ) )
2345 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2346 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2351 for( j = 0; j < sk->ListSize(); j++ )
2353 EbmlElement *l = (*sk)[j];
2355 if( MKV_IS_ID( l, KaxSeekID ) )
2357 KaxSeekID &sid = *(KaxSeekID*)l;
2358 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2360 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2362 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2363 i_pos = uint64( spos );
2367 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2373 if( id == KaxCues::ClassInfos.GlobalId )
2375 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2376 i_cues_position = segment->GetGlobalPosition( i_pos );
2378 else if( id == KaxChapters::ClassInfos.GlobalId )
2380 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2381 i_chapters_position = segment->GetGlobalPosition( i_pos );
2383 else if( id == KaxTags::ClassInfos.GlobalId )
2385 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2386 i_tags_position = segment->GetGlobalPosition( i_pos );
2392 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2397 /*****************************************************************************
2399 *****************************************************************************/
2400 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2406 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2408 tk = new mkv_track_t();
2409 tracks.push_back( tk );
2411 /* Init the track */
2412 memset( tk, 0, sizeof( mkv_track_t ) );
2414 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2415 tk->fmt.psz_language = strdup("English");
2416 tk->fmt.psz_description = NULL;
2418 tk->b_default = VLC_TRUE;
2419 tk->b_enabled = VLC_TRUE;
2420 tk->b_silent = VLC_FALSE;
2421 tk->i_number = tracks.size() - 1;
2422 tk->i_extra_data = 0;
2423 tk->p_extra_data = NULL;
2424 tk->psz_codec = NULL;
2425 tk->i_default_duration = 0;
2426 tk->f_timecodescale = 1.0;
2428 tk->b_inited = VLC_FALSE;
2429 tk->i_data_init = 0;
2430 tk->p_data_init = NULL;
2432 tk->psz_codec_name = NULL;
2433 tk->psz_codec_settings = NULL;
2434 tk->psz_codec_info_url = NULL;
2435 tk->psz_codec_download_url = NULL;
2437 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2439 for( i = 0; i < m->ListSize(); i++ )
2441 EbmlElement *l = (*m)[i];
2443 if( MKV_IS_ID( l, KaxTrackNumber ) )
2445 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2447 tk->i_number = uint32( tnum );
2448 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2450 else if( MKV_IS_ID( l, KaxTrackUID ) )
2452 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2454 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2456 else if( MKV_IS_ID( l, KaxTrackType ) )
2459 KaxTrackType &ttype = *(KaxTrackType*)l;
2461 switch( uint8(ttype) )
2465 tk->fmt.i_cat = AUDIO_ES;
2469 tk->fmt.i_cat = VIDEO_ES;
2471 case track_subtitle:
2472 psz_type = "subtitle";
2473 tk->fmt.i_cat = SPU_ES;
2476 psz_type = "unknown";
2477 tk->fmt.i_cat = UNKNOWN_ES;
2481 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2483 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2485 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2487 // tk->b_enabled = uint32( fenb );
2488 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2489 // uint32( fenb ) );
2491 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2493 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2495 tk->b_default = uint32( fdef );
2496 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2498 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2500 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2502 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2504 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2506 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2508 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2510 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2512 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2514 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2516 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2518 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2520 tk->i_default_duration = uint64(defd);
2521 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2523 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2525 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2527 tk->f_timecodescale = float( ttcs );
2528 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2530 else if( MKV_IS_ID( l, KaxTrackName ) )
2532 KaxTrackName &tname = *(KaxTrackName*)l;
2534 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2535 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2537 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2539 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2541 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2542 msg_Dbg( &sys.demuxer,
2543 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2545 else if( MKV_IS_ID( l, KaxCodecID ) )
2547 KaxCodecID &codecid = *(KaxCodecID*)l;
2549 tk->psz_codec = strdup( string( codecid ).c_str() );
2550 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2552 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2554 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2556 tk->i_extra_data = cpriv.GetSize();
2557 if( tk->i_extra_data > 0 )
2559 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2560 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2562 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2564 else if( MKV_IS_ID( l, KaxCodecName ) )
2566 KaxCodecName &cname = *(KaxCodecName*)l;
2568 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2569 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2571 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2573 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2574 MkvTree( sys.demuxer, 3, "Content Encodings" );
2575 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2577 EbmlElement *l2 = (*cencs)[i];
2578 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2580 MkvTree( sys.demuxer, 4, "Content Encoding" );
2581 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2582 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2584 EbmlElement *l3 = (*cenc)[i];
2585 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2587 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2588 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2590 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2592 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2593 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2595 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2597 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2598 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2600 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2602 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2603 MkvTree( sys.demuxer, 5, "Content Compression" );
2604 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2606 EbmlElement *l4 = (*compr)[i];
2607 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2609 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2610 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2611 if( uint32( compalg ) == 0 )
2613 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2618 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2625 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2632 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2637 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2639 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2641 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2642 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2644 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2646 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2648 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2649 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2651 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2653 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2655 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2656 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2658 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2660 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2662 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2664 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2666 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2668 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2670 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2672 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2675 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2678 for( j = 0; j < tkv->ListSize(); j++ )
2680 EbmlElement *l = (*tkv)[j];
2681 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2683 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2685 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2687 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2689 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2691 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2694 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2696 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2698 tk->fmt.video.i_width = uint16( vwidth );
2699 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2701 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2703 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2705 tk->fmt.video.i_height = uint16( vheight );
2706 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2708 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2710 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2712 tk->fmt.video.i_visible_width = uint16( vwidth );
2713 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2715 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2717 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2719 tk->fmt.video.i_visible_height = uint16( vheight );
2720 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2722 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2724 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2726 tk->f_fps = float( vfps );
2727 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2729 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2731 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2733 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2734 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2736 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2738 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2740 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2742 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2744 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2746 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2750 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2753 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2754 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2756 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2758 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2761 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2763 for( j = 0; j < tka->ListSize(); j++ )
2765 EbmlElement *l = (*tka)[j];
2767 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2769 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2771 tk->fmt.audio.i_rate = (int)float( afreq );
2772 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2774 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2776 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2778 tk->fmt.audio.i_channels = uint8( achan );
2779 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2781 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2783 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2785 tk->fmt.audio.i_bitspersample = uint8( abits );
2786 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2790 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2796 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2797 typeid(*l).name() );
2802 /*****************************************************************************
2804 *****************************************************************************/
2805 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2810 int i_upper_level = 0;
2812 msg_Dbg( &sys.demuxer, "| + Tracks" );
2814 /* Master elements */
2815 m = static_cast<EbmlMaster *>(tracks);
2816 m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2818 for( i = 0; i < m->ListSize(); i++ )
2820 EbmlElement *l = (*m)[i];
2822 if( MKV_IS_ID( l, KaxTrackEntry ) )
2824 ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2828 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2833 /*****************************************************************************
2835 *****************************************************************************/
2836 void matroska_segment_t::ParseInfo( EbmlElement *info )
2841 int i_upper_level = 0;
2843 msg_Dbg( &sys.demuxer, "| + Information" );
2845 /* Master elements */
2846 m = static_cast<EbmlMaster *>(info);
2847 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2849 for( i = 0; i < m->ListSize(); i++ )
2851 EbmlElement *l = (*m)[i];
2853 if( MKV_IS_ID( l, KaxSegmentUID ) )
2855 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2857 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2859 else if( MKV_IS_ID( l, KaxPrevUID ) )
2861 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2863 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2865 else if( MKV_IS_ID( l, KaxNextUID ) )
2867 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2869 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2871 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2873 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2875 i_timescale = uint64(tcs);
2877 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2880 else if( MKV_IS_ID( l, KaxDuration ) )
2882 KaxDuration &dur = *(KaxDuration*)l;
2884 f_duration = float(dur);
2886 msg_Dbg( &sys.demuxer, "| | + Duration=%f",
2889 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2891 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2893 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2895 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2896 psz_muxing_application );
2898 else if( MKV_IS_ID( l, KaxWritingApp ) )
2900 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2902 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2904 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2905 psz_writing_application );
2907 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2909 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2911 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2913 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2914 psz_segment_filename );
2916 else if( MKV_IS_ID( l, KaxTitle ) )
2918 KaxTitle &title = *(KaxTitle*)l;
2920 psz_title = UTF8ToStr( UTFstring( title ) );
2922 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2924 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2926 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2928 families.push_back(*uid);
2930 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2932 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2933 else if( MKV_IS_ID( l, KaxDateUTC ) )
2935 KaxDateUTC &date = *(KaxDateUTC*)l;
2940 i_date = date.GetEpochDate();
2941 memset( buffer, 0, 256 );
2942 if( gmtime_r( &i_date, &tmres ) &&
2943 asctime_r( &tmres, buffer ) )
2945 buffer[strlen( buffer)-1]= '\0';
2946 psz_date_utc = strdup( buffer );
2947 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
2953 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2957 f_duration *= i_timescale / 1000000.0;
2961 /*****************************************************************************
2963 *****************************************************************************/
2964 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2968 if( sys.title == NULL )
2970 sys.title = vlc_input_title_New();
2973 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
2974 for( i = 0; i < ca->ListSize(); i++ )
2976 EbmlElement *l = (*ca)[i];
2978 if( MKV_IS_ID( l, KaxChapterUID ) )
2980 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
2981 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
2983 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2985 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2986 chapters.b_display_seekpoint = uint8( flag ) == 0;
2988 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
2990 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2992 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2993 chapters.i_start_time = uint64( start ) / I64C(1000);
2995 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
2997 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2999 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3000 chapters.i_end_time = uint64( end ) / I64C(1000);
3002 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3004 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3006 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3009 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3010 for( j = 0; j < cd->ListSize(); j++ )
3012 EbmlElement *l= (*cd)[j];
3014 if( MKV_IS_ID( l, KaxChapterString ) )
3018 KaxChapterString &name =*(KaxChapterString*)l;
3019 for (k = 0; k < i_level; k++)
3020 chapters.psz_name += '+';
3021 chapters.psz_name += ' ';
3022 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3024 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3026 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3028 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3029 const char *psz = string( lang ).c_str();
3031 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3033 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3035 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3036 const char *psz = string( ct ).c_str();
3038 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3042 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3044 chapter_item_t new_sub_chapter;
3045 ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
3046 new_sub_chapter.psz_parent = &chapters;
3047 chapters.sub_chapters.push_back( new_sub_chapter );
3052 /*****************************************************************************
3054 *****************************************************************************/
3055 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
3060 int i_upper_level = 0;
3061 int i_default_edition = 0;
3064 /* Master elements */
3065 m = static_cast<EbmlMaster *>(chapters);
3066 m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3068 for( i = 0; i < m->ListSize(); i++ )
3070 EbmlElement *l = (*m)[i];
3072 if( MKV_IS_ID( l, KaxEditionEntry ) )
3074 chapter_edition_t edition;
3076 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3078 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3079 for( j = 0; j < E->ListSize(); j++ )
3081 EbmlElement *l = (*E)[j];
3083 if( MKV_IS_ID( l, KaxChapterAtom ) )
3085 chapter_item_t new_sub_chapter;
3086 ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3087 edition.chapters.push_back( new_sub_chapter );
3089 else if( MKV_IS_ID( l, KaxEditionUID ) )
3091 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3093 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3095 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3097 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3099 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3100 i_default_edition = editions.size();
3104 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3107 editions.push_back( edition );
3111 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3115 for( i = 0; i < editions.size(); i++ )
3117 editions[i].RefreshChapters( *sys.title );
3120 i_current_edition = i_default_edition;
3122 if ( editions[i_default_edition].b_ordered )
3124 /* update the duration of the segment according to the sum of all sub chapters */
3125 f_dur = editions[i_default_edition].Duration() / I64C(1000);
3131 /*****************************************************************************
3132 * InformationCreate:
3133 *****************************************************************************/
3134 void matroska_segment_t::InformationCreate( )
3138 sys.meta = vlc_meta_New();
3142 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3146 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3148 if( psz_segment_filename )
3150 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3152 if( psz_muxing_application )
3154 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3156 if( psz_writing_application )
3158 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3161 for( i_track = 0; i_track < tracks.size(); i_track++ )
3163 mkv_track_t *tk = tracks[i_track];
3164 vlc_meta_t *mtk = vlc_meta_New();
3166 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3167 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3168 sys.meta->track[sys.meta->i_track++] = mtk;
3170 if( tk->fmt.psz_description )
3172 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3174 if( tk->psz_codec_name )
3176 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3178 if( tk->psz_codec_settings )
3180 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3182 if( tk->psz_codec_info_url )
3184 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3186 if( tk->psz_codec_download_url )
3188 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3192 if( i_tags_position >= 0 )
3194 vlc_bool_t b_seekable;
3196 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3205 /*****************************************************************************
3207 *****************************************************************************/
3209 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3211 #define idx index[i_index]
3213 idx.i_block_number= -1;
3214 idx.i_position = cluster->GetElementPosition();
3216 idx.b_key = VLC_TRUE;
3219 if( i_index >= i_index_max )
3221 i_index_max += 1024;
3222 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3227 static char * UTF8ToStr( const UTFstring &u )
3236 p = dst = (char*)malloc( i_src + 1);
3255 void chapter_edition_t::RefreshChapters( input_title_t & title )
3257 int64_t i_prev_user_time = 0;
3258 std::vector<chapter_item_t>::iterator index = chapters.begin();
3260 while ( index != chapters.end() )
3262 i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3267 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3269 int64_t i_user_time = i_prev_user_time;
3271 // first the sub-chapters, and then ourself
3272 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3273 while ( index != sub_chapters.end() )
3275 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3281 i_user_start_time = i_prev_user_time;
3282 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3284 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3288 i_user_end_time = i_user_time;
3293 std::sort( sub_chapters.begin(), sub_chapters.end() );
3294 i_user_start_time = i_start_time;
3295 i_user_end_time = i_end_time;
3298 if (b_display_seekpoint)
3300 seekpoint_t *sk = vlc_seekpoint_New();
3302 // sk->i_level = i_level;
3303 sk->i_time_offset = i_start_time;
3304 sk->psz_name = strdup( psz_name.c_str() );
3306 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3307 title.i_seekpoint++;
3308 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3309 title.seekpoint[title.i_seekpoint-1] = sk;
3312 i_seekpoint_num = title.i_seekpoint;
3314 return i_user_end_time;
3317 double chapter_edition_t::Duration() const
3319 double f_result = 0.0;
3321 if ( chapters.size() )
3323 std::vector<chapter_item_t>::const_iterator index = chapters.end();
3325 f_result = (*index).i_user_end_time;
3331 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3333 const chapter_item_t *psz_result = NULL;
3335 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3337 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3338 while ( index != sub_chapters.end() && psz_result == NULL )
3340 psz_result = (*index).FindTimecode( i_user_timecode );
3344 if ( psz_result == NULL )
3351 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3353 const chapter_item_t *psz_result = NULL;
3355 std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3356 while ( index != chapters.end() && psz_result == NULL )
3358 psz_result = (*index).FindTimecode( i_user_timecode );
3365 void demux_sys_t::PreloadFamily( )
3367 matroska_stream_t *p_stream = Stream();
3370 matroska_segment_t *p_segment = p_stream->Segment();
3373 for (size_t i=0; i<streams.size(); i++)
3375 streams[i]->PreloadFamily( *p_segment );
3381 void matroska_stream_t::PreloadFamily( const matroska_segment_t & of_segment )
3383 for (size_t i=0; i<segments.size(); i++)
3385 segments[i]->PreloadFamily( of_segment );
3389 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3394 for (size_t i=0; i<families.size(); i++)
3396 for (size_t j=0; j<of_segment.families.size(); j++)
3398 if ( families[i] == of_segment.families[j] )
3406 // preload all the linked segments for all preloaded segments
3407 void demux_sys_t::PreloadLinked( )
3409 size_t i_prealoaded;
3412 for (size_t i=0; i<streams.size(); i++)
3414 i_prealoaded += streams[i]->PreloadLinked( *this );
3416 } while ( i_prealoaded ); // worst case: will stop when all segments are preloaded
3419 size_t matroska_stream_t::PreloadLinked( const demux_sys_t & of_sys )
3421 size_t i_result = 0;
3422 for (size_t i=0; i<segments.size(); i++)
3424 i_result += segments[i]->PreloadLinked( of_sys, segments );
3430 size_t matroska_segment_t::PreloadLinked( const demux_sys_t & of_sys, std::vector<matroska_segment_t*> & segments )
3432 size_t i_result = 0;
3433 if ( prev_segment_uid.GetBuffer() )
3435 matroska_segment_t *p_segment = of_sys.FindSegment( prev_segment_uid );
3438 if ( p_segment->Preload( ) )
3440 segments.push_back( p_segment );
3445 if ( next_segment_uid.GetBuffer() )
3447 matroska_segment_t *p_segment = of_sys.FindSegment( next_segment_uid );
3450 if ( p_segment->Preload( ) )
3452 segments.push_back( p_segment );
3460 void demux_sys_t::PreparePlayback( )
3462 matroska_stream_t *p_stream = Stream();
3465 p_stream->PreparePlayback( );
3469 void matroska_stream_t::PreparePlayback( )
3475 for (i=0; i<segments.size(); i++)
3477 f_duration += segments[i]->f_duration;
3479 segments[i]->LoadCues( );
3482 // sort segment order
3483 std::sort( segments.begin(), segments.end(), matroska_segment_t::CompareSegmentUIDs );
3486 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3488 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3489 if ( *p_itema == p_item_b->prev_segment_uid )
3492 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3493 if ( *p_itema == p_item_b->segment_uid )
3499 bool matroska_segment_t::Preload( )
3504 EbmlElement *el = NULL;
3508 while( ( el = ep->Get() ) != NULL )
3510 if( MKV_IS_ID( el, KaxInfo ) )
3514 else if( MKV_IS_ID( el, KaxTracks ) )
3518 else if( MKV_IS_ID( el, KaxSeekHead ) )
3520 ParseSeekHead( el );
3522 else if( MKV_IS_ID( el, KaxCues ) )
3524 msg_Dbg( &sys.demuxer, "| + Cues" );
3526 else if( MKV_IS_ID( el, KaxCluster ) )
3528 msg_Dbg( &sys.demuxer, "| + Cluster" );
3530 cluster = (KaxCluster*)el;
3532 i_start_pos = cluster->GetElementPosition();
3535 /* stop parsing the stream */
3538 else if( MKV_IS_ID( el, KaxAttachments ) )
3540 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3542 else if( MKV_IS_ID( el, KaxChapters ) )
3544 msg_Dbg( &sys.demuxer, "| + Chapters" );
3545 ParseChapters( el );
3547 else if( MKV_IS_ID( el, KaxTag ) )
3549 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3553 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3562 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3564 matroska_segment_t *p_segment = NULL;
3565 for (size_t i=0; i<streams.size() && p_segment == NULL; i++)
3567 p_segment = streams[i]->FindSegment( uid );
3572 matroska_segment_t *matroska_stream_t::FindSegment( const EbmlBinary & uid ) const
3574 for (size_t i=0; i<segments.size(); i++)
3576 if ( segments[i]->segment_uid == uid )