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"
83 #include "matroska/KaxVersion.h"
85 #include "ebml/StdIOCallback.h"
88 #include "mp4/libmp4.h"
94 #define MATROSKA_COMPRESSION_NONE 0
95 #define MATROSKA_COMPRESSION_ZLIB 1
97 #define MKVD_TIMECODESCALE 1000000
100 * What's between a directory and a filename?
103 #define DIRECTORY_SEPARATOR '\\'
105 #define DIRECTORY_SEPARATOR '/'
108 using namespace LIBMATROSKA_NAMESPACE;
111 /*****************************************************************************
113 *****************************************************************************/
114 static int Open ( vlc_object_t * );
115 static void Close( vlc_object_t * );
118 set_shortname( _("Matroska") );
119 set_description( _("Matroska stream demuxer" ) );
120 set_capability( "demux2", 50 );
121 set_callbacks( Open, Close );
122 set_category( CAT_INPUT );
123 set_subcategory( SUBCAT_INPUT_DEMUX );
125 add_bool( "mkv-use-ordered-chapters", 1, NULL,
126 N_("Ordered chapters"),
127 N_("Play ordered chapters as specified in the segment"), VLC_TRUE );
129 add_bool( "mkv-use-chapter-codec", 1, NULL,
130 N_("Chapter codecs"),
131 N_("Use chapter codecs found in the segment"), VLC_TRUE );
133 add_bool( "mkv-seek-percent", 0, NULL,
134 N_("Seek based on percent not time"),
135 N_("Seek based on percent not time"), VLC_TRUE );
137 add_bool( "mkv-use-dummy", 0, NULL,
138 N_("Dummy Elements"),
139 N_("Read and discard unknown EBML elements (not good for broken files)"), VLC_TRUE );
141 add_shortcut( "mka" );
142 add_shortcut( "mkv" );
145 /*****************************************************************************
147 *****************************************************************************/
149 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
150 int result, dstsize, n;
155 d_stream.zalloc = (alloc_func)0;
156 d_stream.zfree = (free_func)0;
157 d_stream.opaque = (voidpf)0;
158 result = inflateInit(&d_stream);
161 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
165 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
166 d_stream.avail_in = p_in_block->i_buffer;
168 p_block = block_New( p_this, 0 );
173 p_block = block_Realloc( p_block, 0, n * 1000 );
174 dst = (unsigned char *)p_block->p_buffer;
175 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
176 d_stream.avail_out = 1000;
177 result = inflate(&d_stream, Z_NO_FLUSH);
178 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
180 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
184 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
185 ( result != Z_STREAM_END ) );
187 dstsize = d_stream.total_out;
188 inflateEnd( &d_stream );
190 p_block = block_Realloc( p_block, 0, dstsize );
191 p_block->i_buffer = dstsize;
192 block_Release( p_in_block );
199 * Helper function to print the mkv parse tree
201 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
206 msg_Err( &demuxer, "too deep tree" );
209 va_start( args, psz_format );
210 static char *psz_foo = "| | | | | | | | | |";
211 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
212 strncpy( psz_foo2, psz_foo, 4 * i_level );
213 psz_foo2[ 4 * i_level ] = '+';
214 psz_foo2[ 4 * i_level + 1 ] = ' ';
215 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
216 __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
221 /*****************************************************************************
223 *****************************************************************************/
224 class vlc_stream_io_callback: public IOCallback
231 vlc_stream_io_callback( stream_t * );
233 virtual uint32 read ( void *p_buffer, size_t i_size);
234 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
235 virtual size_t write ( const void *p_buffer, size_t i_size);
236 virtual uint64 getFilePointer ( void );
237 virtual void close ( void );
240 /*****************************************************************************
242 *****************************************************************************/
246 EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
247 virtual ~EbmlParser( void );
251 void Reset( demux_t *p_demux );
252 EbmlElement *Get( void );
255 int GetLevel( void );
260 EbmlElement *m_el[10];
261 int64_t mi_remain_size[10];
271 /*****************************************************************************
272 * Some functions to manipulate memory
273 *****************************************************************************/
274 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
275 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
277 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
280 /*****************************************************************************
281 * definitions of structures and functions used by this plugins
282 *****************************************************************************/
285 vlc_bool_t b_default;
286 vlc_bool_t b_enabled;
287 unsigned int i_number;
290 uint8_t *p_extra_data;
294 uint64_t i_default_duration;
295 float f_timecodescale;
303 /* data to be send first */
305 uint8_t *p_data_init;
307 /* hack : it's for seek */
308 vlc_bool_t b_search_keyframe;
312 char *psz_codec_name;
313 char *psz_codec_settings;
314 char *psz_codec_info_url;
315 char *psz_codec_download_url;
317 /* encryption/compression */
318 int i_compression_type;
335 const binary MATROSKA_DVD_LEVEL_SS = 0x30;
336 const binary MATROSKA_DVD_LEVEL_LU = 0x2A;
337 const binary MATROSKA_DVD_LEVEL_TT = 0x28;
338 const binary MATROSKA_DVD_LEVEL_PGC = 0x20;
339 const binary MATROSKA_DVD_LEVEL_PG = 0x18;
340 const binary MATROSKA_DVD_LEVEL_PTT = 0x10;
341 const binary MATROSKA_DVD_LEVEL_CN = 0x08;
343 class chapter_codec_cmds_c
346 chapter_codec_cmds_c( demux_sys_t & demuxer, int codec_id = -1)
347 :i_codec_id( codec_id )
351 virtual ~chapter_codec_cmds_c() {}
353 void SetPrivate( const KaxChapterProcessPrivate & private_data )
355 m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
358 void AddCommand( const KaxChapterProcessCommand & command );
360 /// \return wether the codec has seeked in the files or not
361 virtual bool Enter() { return false; }
362 virtual bool Leave() { return false; }
363 virtual std::string GetCodecName( bool f_for_title = false ) const { return ""; }
365 KaxChapterProcessPrivate m_private_data;
368 std::vector<KaxChapterProcessData> enter_cmds;
369 std::vector<KaxChapterProcessData> during_cmds;
370 std::vector<KaxChapterProcessData> leave_cmds;
376 class dvd_command_interpretor_c
379 dvd_command_interpretor_c( demux_sys_t & demuxer )
382 memset( p_PRMs, 0, sizeof(p_PRMs) );
383 p_PRMs[ 0x80 + 1 ] = 15;
384 p_PRMs[ 0x80 + 2 ] = 62;
385 p_PRMs[ 0x80 + 3 ] = 1;
386 p_PRMs[ 0x80 + 4 ] = 1;
387 p_PRMs[ 0x80 + 7 ] = 1;
388 p_PRMs[ 0x80 + 8 ] = 1;
389 p_PRMs[ 0x80 + 16 ] = 0xFFFFu;
390 p_PRMs[ 0x80 + 18 ] = 0xFFFFu;
393 bool Interpret( const binary * p_command, size_t i_size = 8 );
396 uint16 GetPRM( size_t index ) const
399 return p_PRMs[ index ];
403 uint16 GetGPRM( size_t index ) const
405 if ( index >= 0 && index < 16 )
406 return p_PRMs[ index ];
410 uint16 GetSPRM( size_t index ) const
412 // 21,22,23 reserved for future use
413 if ( index >= 0x80 && index < 0x95 )
414 return p_PRMs[ index ];
418 bool SetPRM( size_t index, uint16 value )
420 if ( index >= 0 && index < 16 )
422 p_PRMs[ index ] = value;
428 bool SetGPRM( size_t index, uint16 value )
430 if ( index >= 0 && index < 16 )
432 p_PRMs[ index ] = value;
438 bool SetSPRM( size_t index, uint16 value )
440 if ( index > 0x80 && index <= 0x8D && index != 0x8C )
442 p_PRMs[ index ] = value;
448 std::string GetRegTypeName( bool b_value, uint16 value ) const
451 char s_value[6], s_reg_value[6];
452 itoa( value, s_value, 10 );
460 else if ( value < 0x80 )
462 itoa( GetPRM( value ) , s_reg_value, 10 );
466 result += s_reg_value;
471 itoa( GetPRM( value ) , s_reg_value, 10 );
475 result += s_reg_value;
487 // wether the test has to be positive or not
488 static const uint16 CMD_DVD_IF_NOT = 0x10;
489 // wether it's a comparison on the value or register
490 static const uint16 CMD_DVD_TEST_VALUE = 0x80;
491 static const uint16 CMD_DVD_IF_GPREG_AND = (0 << 5);
492 static const uint16 CMD_DVD_IF_GPREG_EQUAL = (1 << 5);
493 static const uint16 CMD_DVD_IF_GPREG_SUP_EQUAL = (2 << 5);
494 static const uint16 CMD_DVD_IF_GPREG_INF = (3 << 5);
496 static const uint16 CMD_DVD_NOP = 0x0000;
497 static const uint16 CMD_DVD_GOTO_LINE = 0x0001;
498 static const uint16 CMD_DVD_BREAK = 0x0002;
500 static const uint16 CMD_DVD_NOP2 = 0x2001;
501 static const uint16 CMD_DVD_LINKPGCN = 0x2004;
502 static const uint16 CMD_DVD_LINKPGN = 0x2006;
503 static const uint16 CMD_DVD_LINKCN = 0x2007;
504 static const uint16 CMD_DVD_JUMP_TT = 0x3002;
505 static const uint16 CMD_DVD_JUMPVTS_TT = 0x3003;
506 static const uint16 CMD_DVD_JUMP_SS = 0x3006;
507 static const uint16 CMD_DVD_CALLSS_VTSM1 = 0x3008;
509 static const uint16 CMD_DVD_SET_HL_BTNN2 = 0x4600;
510 static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN1 = 0x4604;
511 static const uint16 CMD_DVD_SET_AUDIO = 0x5100;
512 static const uint16 CMD_DVD_SET_GPRMMD = 0x5300;
513 static const uint16 CMD_DVD_SET_HL_BTNN1 = 0x5600;
514 static const uint16 CMD_DVD_SET_HL_BTNN_LINKPGCN2 = 0x5604;
515 static const uint16 CMD_DVD_SET_HL_BTNN_LINKCN = 0x5607;
517 static const uint16 CMD_DVD_MOV_SPREG_PREG = 0x6100;
518 static const uint16 CMD_DVD_GPREG_MOV_VALUE = 0x7100;
519 static const uint16 CMD_DVD_SUB_GPREG = 0x7400;
520 static const uint16 CMD_DVD_MULT_GPREG = 0x7500;
521 static const uint16 CMD_DVD_GPREG_DIV_VALUE = 0x7600;
522 static const uint16 CMD_DVD_GPREG_AND_VALUE = 0x7900;
524 // callbacks when browsing inside CodecPrivate
525 static bool MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
526 static bool MatchPgcType ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
529 class dvd_chapter_codec_c : public chapter_codec_cmds_c
532 dvd_chapter_codec_c( demux_sys_t & sys )
533 :chapter_codec_cmds_c( sys, 1 )
539 std::string GetCodecName( bool f_for_title = false ) const;
542 dvd_command_interpretor_c interpretor;
545 class matroska_script_interpretor_c
548 matroska_script_interpretor_c( demux_sys_t & demuxer )
552 bool Interpret( const binary * p_command, size_t i_size );
555 static const std::string CMD_MS_GOTO_AND_PLAY;
561 const std::string matroska_script_interpretor_c::CMD_MS_GOTO_AND_PLAY = "GotoAndPlay";
564 class matroska_script_codec_c : public chapter_codec_cmds_c
567 matroska_script_codec_c( demux_sys_t & sys )
568 :chapter_codec_cmds_c( sys, 0 )
576 matroska_script_interpretor_c interpretor;
579 class chapter_translation_c
582 KaxChapterTranslateID translated;
583 unsigned int codec_id;
584 std::vector<uint64_t> editions;
593 ,i_user_start_time(-1)
596 ,b_display_seekpoint(true)
597 ,b_user_display(false)
601 virtual ~chapter_item_c()
603 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
604 while ( index != codecs.end() )
609 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
610 while ( index_ != sub_chapters.end() )
617 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
618 int PublishChapters( input_title_t & title, int & i_user_chapters, int i_level = 0 );
619 chapter_item_c * FindTimecode( mtime_t i_timecode );
620 void Append( const chapter_item_c & edition );
621 chapter_item_c * FindChapter( int64_t i_find_uid );
622 virtual chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
623 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
624 const void *p_cookie,
625 size_t i_cookie_size );
626 std::string GetCodecName( bool f_for_title = false ) const;
627 bool ParentOf( const chapter_item_c & item ) const;
629 int64_t i_start_time, i_end_time;
630 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
631 std::vector<chapter_item_c*> sub_chapters;
634 bool b_display_seekpoint;
636 std::string psz_name;
637 chapter_item_c *psz_parent;
639 std::vector<chapter_codec_cmds_c*> codecs;
641 bool operator<( const chapter_item_c & item ) const
643 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) );
646 bool Enter( bool b_do_subchapters );
647 bool Leave( bool b_do_subchapters );
648 bool EnterAndLeave( chapter_item_c *p_item );
651 class chapter_edition_c : public chapter_item_c
658 void RefreshChapters( );
659 mtime_t Duration() const;
660 std::string GetMainName() const;
665 class matroska_segment_c
668 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
671 ,i_timescale(MKVD_TIMECODESCALE)
675 ,i_chapters_position(-1)
682 ,psz_muxing_application(NULL)
683 ,psz_writing_application(NULL)
684 ,psz_segment_filename(NULL)
687 ,i_default_edition(0)
692 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
695 virtual ~matroska_segment_c()
697 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
699 #define tk tracks[i_track]
700 if( tk->fmt.psz_description )
702 free( tk->fmt.psz_description );
706 free( tk->psz_codec );
708 if( tk->fmt.psz_language )
710 free( tk->fmt.psz_language );
716 if( psz_writing_application )
718 free( psz_writing_application );
720 if( psz_muxing_application )
722 free( psz_muxing_application );
724 if( psz_segment_filename )
726 free( psz_segment_filename );
734 free( psz_date_utc );
741 std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
742 while ( index != stored_editions.end() )
753 uint64_t i_timescale;
755 /* duration of the segment */
757 mtime_t i_start_time;
760 std::vector<mkv_track_t*> tracks;
763 int64_t i_cues_position;
764 int64_t i_chapters_position;
765 int64_t i_tags_position;
769 KaxSegmentUID segment_uid;
770 KaxPrevUID prev_segment_uid;
771 KaxNextUID next_segment_uid;
779 char *psz_muxing_application;
780 char *psz_writing_application;
781 char *psz_segment_filename;
785 /* !!!!! GCC 3.3 bug on Darwin !!!!! */
786 /* when you remove this variable the compiler issues an atomicity error */
787 /* this variable only works when using std::vector<chapter_edition_c> */
788 std::vector<chapter_edition_c*> stored_editions;
789 int i_default_edition;
791 std::vector<chapter_translation_c> translations;
792 std::vector<KaxSegmentFamily> families;
799 bool PreloadFamily( const matroska_segment_c & segment );
800 void ParseInfo( KaxInfo *info );
801 void ParseChapters( KaxChapters *chapters );
802 void ParseSeekHead( KaxSeekHead *seekhead );
803 void ParseTracks( KaxTracks *tracks );
804 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
805 void ParseTrackEntry( KaxTrackEntry *m );
806 void ParseCluster( );
807 void IndexAppendCluster( KaxCluster *cluster );
810 void InformationCreate( );
811 void Seek( mtime_t i_date, mtime_t i_time_offset );
812 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
813 bool Select( mtime_t i_start_time );
816 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
819 // class holding hard-linked segment together in the playback order
820 class virtual_segment_c
823 virtual_segment_c( matroska_segment_c *p_segment )
824 :i_current_segment(0)
826 ,i_current_edition(-1)
827 ,psz_current_chapter(NULL)
830 linked_segments.push_back( p_segment );
832 AppendUID( p_segment->segment_uid );
833 AppendUID( p_segment->prev_segment_uid );
834 AppendUID( p_segment->next_segment_uid );
838 size_t AddSegment( matroska_segment_c *p_segment );
839 void PreloadLinked( );
840 mtime_t Duration( ) const;
842 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
844 inline chapter_edition_c *Edition()
846 if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
847 return (*p_editions)[i_current_edition];
851 matroska_segment_c * Segment() const
853 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
855 return linked_segments[i_current_segment];
858 inline const chapter_item_c *CurrentChapter() const {
859 return psz_current_chapter;
864 if ( i_current_segment < linked_segments.size()-1 )
872 bool FindUID( KaxSegmentUID & uid ) const
874 for ( size_t i=0; i<linked_uids.size(); i++ )
876 if ( linked_uids[i] == uid )
882 bool UpdateCurrentToChapter( demux_t & demux );
883 void PrepareChapters( );
885 chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
886 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
887 const void *p_cookie,
888 size_t i_cookie_size );
889 chapter_item_c *FindChapter( int64_t i_find_uid );
891 std::vector<chapter_edition_c*> *p_editions;
895 std::vector<matroska_segment_c*> linked_segments;
896 std::vector<KaxSegmentUID> linked_uids;
897 size_t i_current_segment;
899 int i_current_edition;
900 chapter_item_c *psz_current_chapter;
902 void AppendUID( const EbmlBinary & UID );
905 class matroska_stream_c
908 matroska_stream_c( demux_sys_t & demuxer )
914 virtual ~matroska_stream_c()
923 std::vector<matroska_segment_c*> segments;
931 demux_sys_t( demux_t & demux )
938 ,p_current_segment(NULL)
942 virtual ~demux_sys_t()
945 for ( i=0; i<streams.size(); i++ )
947 for ( i=0; i<opened_segments.size(); i++ )
948 delete opened_segments[i];
949 for ( i=0; i<used_segments.size(); i++ )
950 delete used_segments[i];
958 mtime_t i_chapter_time;
962 std::vector<input_title_t> titles; // matroska editions
963 size_t i_current_title;
965 std::vector<matroska_stream_c*> streams;
966 std::vector<matroska_segment_c*> opened_segments;
967 std::vector<virtual_segment_c*> used_segments;
968 virtual_segment_c *p_current_segment;
970 /* duration of the stream */
973 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
974 chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
975 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
976 const void *p_cookie,
977 size_t i_cookie_size,
978 virtual_segment_c * & p_segment_found );
979 chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
981 void PreloadFamily( const matroska_segment_c & of_segment );
982 void PreloadLinked( matroska_segment_c *p_segment );
983 bool PreparePlayback( virtual_segment_c *p_new_segment );
984 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
987 virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
988 bool IsUsedSegment( matroska_segment_c &p_segment ) const;
991 static int Demux ( demux_t * );
992 static int Control( demux_t *, int, va_list );
993 static void Seek ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
995 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
997 static char *UTF8ToStr ( const UTFstring &u );
999 /*****************************************************************************
1000 * Open: initializes matroska demux structures
1001 *****************************************************************************/
1002 static int Open( vlc_object_t * p_this )
1004 demux_t *p_demux = (demux_t*)p_this;
1006 matroska_stream_c *p_stream;
1007 matroska_segment_c *p_segment;
1009 std::string s_path, s_filename;
1010 vlc_stream_io_callback *p_io_callback;
1011 EbmlStream *p_io_stream;
1013 /* peek the begining */
1014 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
1016 /* is a valid file */
1017 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
1018 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
1020 /* Set the demux function */
1021 p_demux->pf_demux = Demux;
1022 p_demux->pf_control = Control;
1023 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
1025 p_io_callback = new vlc_stream_io_callback( p_demux->s );
1026 p_io_stream = new EbmlStream( *p_io_callback );
1028 if( p_io_stream == NULL )
1030 msg_Err( p_demux, "failed to create EbmlStream" );
1031 delete p_io_callback;
1033 return VLC_EGENERIC;
1036 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
1037 if( p_stream == NULL )
1039 msg_Err( p_demux, "cannot find KaxSegment" );
1042 p_sys->streams.push_back( p_stream );
1044 p_stream->p_in = p_io_callback;
1045 p_stream->p_es = p_io_stream;
1047 for (size_t i=0; i<p_stream->segments.size(); i++)
1049 p_stream->segments[i]->Preload();
1052 p_segment = p_stream->segments[0];
1053 if( p_segment->cluster != NULL )
1055 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
1057 // reset the stream reading to the first cluster of the segment used
1058 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
1061 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
1062 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
1064 // assume it's a regular file
1065 // get the directory path
1066 s_path = p_demux->psz_path;
1067 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
1069 s_path = s_path.substr(0,s_path.length()-1);
1073 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
1075 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
1079 struct dirent *p_file_item;
1080 DIR *p_src_dir = opendir(s_path.c_str());
1082 if (p_src_dir != NULL)
1084 while ((p_file_item = (dirent *) readdir(p_src_dir)))
1086 if (strlen(p_file_item->d_name) > 4)
1088 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
1090 if (!s_filename.compare(p_demux->psz_path))
1091 continue; // don't reuse the original opened file
1093 #if defined(__GNUC__) && (__GNUC__ < 3)
1094 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
1095 !s_filename.compare("mka", s_filename.length() - 3, 3))
1097 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
1098 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1101 // test wether this file belongs to the our family
1102 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
1103 EbmlStream *p_estream = new EbmlStream(*p_file_io);
1105 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
1106 if ( p_stream == NULL )
1108 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1114 p_stream->p_in = p_file_io;
1115 p_stream->p_es = p_estream;
1116 p_sys->streams.push_back( p_stream );
1121 closedir( p_src_dir );
1125 p_sys->PreloadFamily( *p_segment );
1126 p_sys->PreloadLinked( p_segment );
1127 if ( !p_sys->PreparePlayback( NULL ) )
1129 msg_Err( p_demux, "cannot use the segment" );
1137 return VLC_EGENERIC;
1140 /*****************************************************************************
1141 * Close: frees unused data
1142 *****************************************************************************/
1143 static void Close( vlc_object_t *p_this )
1145 demux_t *p_demux = (demux_t*)p_this;
1146 demux_sys_t *p_sys = p_demux->p_sys;
1151 /*****************************************************************************
1153 *****************************************************************************/
1154 static int Control( demux_t *p_demux, int i_query, va_list args )
1156 demux_sys_t *p_sys = p_demux->p_sys;
1162 vlc_meta_t **pp_meta;
1166 case DEMUX_GET_META:
1167 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1168 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1171 case DEMUX_GET_LENGTH:
1172 pi64 = (int64_t*)va_arg( args, int64_t * );
1173 if( p_sys->f_duration > 0.0 )
1175 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1178 return VLC_EGENERIC;
1180 case DEMUX_GET_POSITION:
1181 pf = (double*)va_arg( args, double * );
1182 if ( p_sys->f_duration > 0.0 )
1183 *pf = (double)(p_sys->i_pts >= p_sys->i_start_pts ? p_sys->i_pts : p_sys->i_start_pts ) / (1000.0 * p_sys->f_duration);
1186 case DEMUX_SET_POSITION:
1187 f = (double)va_arg( args, double );
1188 Seek( p_demux, -1, f, NULL );
1191 case DEMUX_GET_TIME:
1192 pi64 = (int64_t*)va_arg( args, int64_t * );
1193 *pi64 = p_sys->i_pts;
1196 case DEMUX_GET_TITLE_INFO:
1197 if( p_sys->titles.size() )
1199 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1200 int *pi_int = (int*)va_arg( args, int* );
1202 *pi_int = p_sys->titles.size();
1203 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1205 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1207 (*ppp_title)[i] = vlc_input_title_Duplicate( &p_sys->titles[i] );
1212 return VLC_EGENERIC;
1214 case DEMUX_SET_TITLE:
1215 /* TODO handle editions as titles */
1216 i_idx = (int)va_arg( args, int );
1217 if( i_idx < p_sys->used_segments.size() )
1219 p_sys->PreparePlayback( p_sys->used_segments[i_idx] );
1222 return VLC_EGENERIC;
1224 case DEMUX_SET_SEEKPOINT:
1225 i_skp = (int)va_arg( args, int );
1227 if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title].i_seekpoint)
1229 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title].seekpoint[i_skp]->i_time_offset, -1, NULL);
1230 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1231 p_demux->info.i_seekpoint = i_skp;
1234 return VLC_EGENERIC;
1236 case DEMUX_SET_TIME:
1239 return VLC_EGENERIC;
1243 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1255 return VLC_EGENERIC;
1258 i_level = ep->GetLevel();
1260 if( el == NULL && *pp_block != NULL )
1262 /* update the index */
1263 #define idx index[i_index - 1]
1264 if( i_index > 0 && idx.i_time == -1 )
1266 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1267 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1275 if( ep->GetLevel() > 1 )
1280 msg_Warn( &sys.demuxer, "EOF" );
1281 return VLC_EGENERIC;
1287 if( MKV_IS_ID( el, KaxCluster ) )
1289 cluster = (KaxCluster*)el;
1291 /* add it to the index */
1293 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1295 IndexAppendCluster( cluster );
1298 // reset silent tracks
1299 for (size_t i=0; i<tracks.size(); i++)
1301 tracks[i]->b_silent = VLC_FALSE;
1306 else if( MKV_IS_ID( el, KaxCues ) )
1308 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1309 return VLC_EGENERIC;
1313 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1316 else if( i_level == 2 )
1318 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1320 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1322 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1323 cluster->InitTimecode( uint64( ctc ), i_timescale );
1325 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1329 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1334 else if( i_level == 3 )
1336 if( MKV_IS_ID( el, KaxBlock ) )
1338 *pp_block = (KaxBlock*)el;
1340 (*pp_block)->ReadData( es.I_O() );
1341 (*pp_block)->SetParent( *cluster );
1345 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1347 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1349 dur.ReadData( es.I_O() );
1350 *pi_duration = uint64( dur );
1352 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1354 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1356 ref.ReadData( es.I_O() );
1357 if( *pi_ref1 == -1 )
1359 *pi_ref1 = int64( ref );
1363 *pi_ref2 = int64( ref );
1366 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1368 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1369 track_num.ReadData( es.I_O() );
1371 for (size_t i=0; i<tracks.size(); i++)
1373 if ( tracks[i]->i_number == uint32(track_num))
1375 tracks[i]->b_silent = VLC_TRUE;
1383 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1384 return VLC_EGENERIC;
1389 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1392 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1393 memcpy( p_block->p_buffer, p_mem, i_mem );
1394 //p_block->i_rate = p_input->stream.control.i_rate;
1398 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1399 mtime_t i_duration )
1401 demux_sys_t *p_sys = p_demux->p_sys;
1402 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1408 #define tk p_segment->tracks[i_track]
1409 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1411 if( tk->i_number == block->TrackNum() )
1417 if( i_track >= p_segment->tracks.size() )
1419 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1422 if( tk->p_es == NULL )
1424 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1427 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1429 return; /* discard audio packets that shouldn't be rendered */
1432 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1435 tk->b_inited = VLC_FALSE;
1439 /* First send init data */
1440 if( !tk->b_inited && tk->i_data_init > 0 )
1444 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1445 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1446 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1448 tk->b_inited = VLC_TRUE;
1451 for( i = 0; i < block->NumberFrames(); i++ )
1454 DataBuffer &data = block->GetBuffer(i);
1456 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1458 if( p_block == NULL )
1463 #if defined(HAVE_ZLIB_H)
1464 if( tk->i_compression_type )
1466 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1470 // TODO implement correct timestamping when B frames are used
1471 if( tk->fmt.i_cat != VIDEO_ES )
1473 p_block->i_dts = p_block->i_pts = i_pts;
1477 p_block->i_dts = i_pts;
1481 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1483 p_block->i_length = i_duration * 1000;
1486 es_out_Send( p_demux->out, tk->p_es, p_block );
1488 /* use time stamp only for first block */
1495 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1497 int i_upper_lvl = 0;
1499 EbmlElement *p_l0, *p_l1, *p_l2;
1500 bool b_keep_stream = false, b_keep_segment;
1502 // verify the EBML Header
1503 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1508 p_l0->SkipData(*p_estream, EbmlHead_Context);
1511 // find all segments in this file
1512 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1518 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1522 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1525 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1526 b_keep_segment = false;
1528 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1529 p_segment1->ep = ep;
1530 p_segment1->segment = (KaxSegment*)p_l0;
1532 while ((p_l1 = ep->Get()))
1534 if (MKV_IS_ID(p_l1, KaxInfo))
1536 // find the families of this segment
1537 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1539 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1540 for( i = 0; i < p_info->ListSize(); i++ )
1542 EbmlElement *l = (*p_info)[i];
1544 if( MKV_IS_ID( l, KaxSegmentUID ) )
1546 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1547 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1548 if ( !b_keep_segment )
1549 break; // this segment is already known
1550 opened_segments.push_back( p_segment1 );
1551 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1553 else if( MKV_IS_ID( l, KaxPrevUID ) )
1555 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1557 else if( MKV_IS_ID( l, KaxNextUID ) )
1559 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1561 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1563 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1564 p_segment1->families.push_back( *p_fam );
1570 if ( b_keep_segment )
1572 b_keep_stream = true;
1573 p_stream1->segments.push_back( p_segment1 );
1579 p_l0->SkipData(*p_estream, EbmlHead_Context);
1580 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1583 if ( !b_keep_stream )
1592 bool matroska_segment_c::Select( mtime_t i_start_time )
1597 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1598 for( i_track = 0; i_track < tracks.size(); i_track++ )
1600 #define tk tracks[i_track]
1601 if( tk->fmt.i_cat == UNKNOWN_ES )
1603 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1608 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1610 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1612 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1613 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1617 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1619 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1620 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1621 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1623 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1624 if( tk->fmt.i_extra > 0 )
1626 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1627 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1631 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1632 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1634 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1636 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1638 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1640 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1642 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1644 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1645 tk->fmt.b_packetized = VLC_FALSE;
1646 tk->fmt.i_extra = tk->i_extra_data;
1647 tk->fmt.p_extra = malloc( tk->i_extra_data );
1648 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1652 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1655 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1657 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1659 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1663 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1668 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1669 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1670 tk->fmt.i_codec = p_box->i_type;
1671 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1672 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1673 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1674 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1675 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1676 MP4_FreeBox_sample_vide( p_box );
1678 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1680 stream_Delete( p_mp4_stream );
1683 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1685 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1687 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1688 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1692 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1694 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1696 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1697 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1698 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1699 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1700 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1702 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1703 if( tk->fmt.i_extra > 0 )
1705 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1706 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1710 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1711 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1712 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1714 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1716 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1718 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1720 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1722 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1724 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1726 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1727 tk->fmt.i_extra = tk->i_extra_data;
1728 tk->fmt.p_extra = malloc( tk->i_extra_data );
1729 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1731 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1733 int i, i_offset = 1, i_size[3], i_extra;
1736 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1738 /* Split the 3 headers */
1739 if( tk->p_extra_data[0] != 0x02 )
1740 msg_Err( &sys.demuxer, "invalid vorbis header" );
1742 for( i = 0; i < 2; i++ )
1745 while( i_offset < tk->i_extra_data )
1747 i_size[i] += tk->p_extra_data[i_offset];
1748 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1752 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1753 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1754 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1756 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1757 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1758 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1759 for( i = 0; i < 3; i++ )
1761 *(p_extra++) = i_size[i] >> 8;
1762 *(p_extra++) = i_size[i] & 0xFF;
1763 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1765 p_extra += i_size[i];
1766 i_extra += i_size[i];
1769 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1770 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1772 int i_profile, i_srate;
1773 static unsigned int i_sample_rates[] =
1775 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1776 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1779 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1780 /* create data for faad (MP4DecSpecificDescrTag)*/
1782 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1786 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1790 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1799 for( i_srate = 0; i_srate < 13; i_srate++ )
1801 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1806 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1808 tk->fmt.i_extra = 2;
1809 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1810 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1811 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1813 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1814 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1815 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1817 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1819 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1823 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1825 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1827 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1829 /* FIXME: support this codec */
1830 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1831 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1833 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1835 /* FIXME: support this codec */
1836 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1837 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1839 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1841 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1842 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1844 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1845 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1846 !strcmp( tk->psz_codec, "S_SSA" ) ||
1847 !strcmp( tk->psz_codec, "S_ASS" ))
1849 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1850 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1852 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1854 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1855 if( tk->i_extra_data )
1858 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1859 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1860 p_buf[tk->i_extra_data] = '\0';
1862 p_start = strstr( p_buf, "size:" );
1863 if( sscanf( p_start, "size: %dx%d",
1864 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1866 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 );
1870 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1875 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1877 /* FIXME: support this codec */
1878 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1879 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1883 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1884 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1888 tk->fmt.i_priority = 1000;
1891 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1893 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1897 sys.i_start_pts = i_start_time;
1898 // reset the stream reading to the first cluster of the segment used
1899 es.I_O().setFilePointer( i_start_pos );
1902 ep = new EbmlParser( &es, segment, &sys.demuxer );
1907 void matroska_segment_c::UnSelect( )
1911 for( i_track = 0; i_track < tracks.size(); i_track++ )
1913 #define tk tracks[i_track]
1914 if ( tk->p_es != NULL )
1916 es_out_Del( sys.demuxer.out, tk->p_es );
1925 void virtual_segment_c::PrepareChapters( )
1927 if ( linked_segments.size() == 0 )
1930 // !!! should be called only once !!!
1931 matroska_segment_c *p_segment;
1934 // copy editions from the first segment
1935 p_segment = linked_segments[0];
1936 p_editions = &p_segment->stored_editions;
1938 for ( i=1 ; i<linked_segments.size(); i++ )
1940 p_segment = linked_segments[i];
1941 // FIXME assume we have the same editions in all segments
1942 for (j=0; j<p_segment->stored_editions.size(); j++)
1943 (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
1947 std::string chapter_edition_c::GetMainName() const
1949 if ( sub_chapters.size() )
1951 return sub_chapters[0]->GetCodecName( true );
1956 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
1958 // add support for meta-elements from codec like DVD Titles
1959 if ( !b_display_seekpoint || psz_name == "" )
1961 psz_name = GetCodecName();
1962 if ( psz_name != "" )
1963 b_display_seekpoint = true;
1966 if (b_display_seekpoint)
1968 seekpoint_t *sk = vlc_seekpoint_New();
1970 sk->i_level = i_level;
1971 sk->i_time_offset = i_start_time;
1972 sk->psz_name = strdup( psz_name.c_str() );
1974 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1975 title.i_seekpoint++;
1976 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1977 title.seekpoint[title.i_seekpoint-1] = sk;
1979 if ( b_user_display )
1983 for ( size_t i=0; i<sub_chapters.size() ; i++)
1985 sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
1988 i_seekpoint_num = i_user_chapters;
1990 return i_user_chapters;
1993 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1995 demux_sys_t & sys = *demux.p_sys;
1996 chapter_item_c *psz_curr_chapter;
1998 /* update current chapter/seekpoint */
1999 if ( p_editions->size() )
2001 /* 1st, we need to know in which chapter we are */
2002 psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
2004 /* we have moved to a new chapter */
2005 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
2007 if ( (*p_editions)[i_current_edition]->b_ordered )
2009 // Leave/Enter up to the link point
2010 if ( !psz_curr_chapter->EnterAndLeave( psz_current_chapter ) )
2012 // only seek if necessary
2013 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
2014 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
2015 psz_current_chapter = psz_curr_chapter;
2018 else if ( psz_curr_chapter->i_seekpoint_num > 0 )
2020 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
2021 demux.info.i_title = sys.i_current_title = i_sys_title;
2022 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
2023 psz_current_chapter = psz_curr_chapter;
2027 psz_current_chapter = psz_curr_chapter;
2036 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id,
2037 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
2038 const void *p_cookie,
2039 size_t i_cookie_size )
2041 // FIXME don't assume it is the first edition
2042 std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2043 if ( index != p_editions->end() )
2045 chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2046 if ( p_result != NULL )
2052 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
2054 // FIXME don't assume it is the first edition
2055 std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2056 if ( index != p_editions->end() )
2058 chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
2059 if ( p_result != NULL )
2065 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id,
2066 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
2067 const void *p_cookie,
2068 size_t i_cookie_size )
2071 std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2072 while ( index != codecs.end() )
2074 if ( match( **index ,p_cookie, i_cookie_size ) )
2080 chapter_item_c *p_result = NULL;
2081 std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
2082 while ( index2 != sub_chapters.end() )
2084 p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2085 if ( p_result != NULL )
2093 void chapter_item_c::Append( const chapter_item_c & chapter )
2095 // we are appending content for the same chapter UID
2097 chapter_item_c *p_chapter;
2099 for ( i=0; i<chapter.sub_chapters.size(); i++ )
2101 p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
2102 if ( p_chapter != NULL )
2104 p_chapter->Append( *chapter.sub_chapters[i] );
2108 sub_chapters.push_back( chapter.sub_chapters[i] );
2112 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
2113 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
2116 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
2119 chapter_item_c *p_result = NULL;
2121 if ( i_uid == i_find_uid )
2124 for ( i=0; i<sub_chapters.size(); i++)
2126 p_result = sub_chapters[i]->FindChapter( i_find_uid );
2127 if ( p_result != NULL )
2133 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
2137 std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2138 while ( index != codecs.end() )
2140 result = (*index)->GetCodecName( f_for_title );
2149 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
2152 if ( m_private_data.GetSize() >= 3)
2154 const binary* p_data = m_private_data.GetBuffer();
2155 /* if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
2157 uint16_t i_title = (p_data[1] << 8) + p_data[2];
2159 sprintf( psz_str, " %d ---", i_title );
2160 result = N_("--- DVD Title");
2163 else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
2166 sprintf( psz_str, " (%c%c) ---", p_data[1], p_data[2] );
2167 result = N_("--- DVD Menu");
2170 else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
2172 if ( p_data[1] == 0x00 )
2173 result = N_("First Played");
2174 else if ( p_data[1] == 0xC0 )
2175 result = N_("Video Manager");
2176 else if ( p_data[1] == 0x80 )
2178 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2180 sprintf( psz_str, " %d -----", i_title );
2181 result = N_("----- Title");
2190 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2192 demux_sys_t *p_sys = p_demux->p_sys;
2193 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
2194 matroska_segment_c *p_segment = p_vsegment->Segment();
2195 mtime_t i_time_offset = 0;
2199 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2200 if( i_date < 0 && f_percent < 0 )
2202 msg_Warn( p_demux, "cannot seek nowhere !" );
2205 if( f_percent > 1.0 )
2207 msg_Warn( p_demux, "cannot seek so far !" );
2211 /* seek without index or without date */
2212 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2214 if (p_sys->f_duration >= 0)
2216 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2220 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2222 msg_Dbg( p_demux, "inacurate way of seeking" );
2223 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2225 if( p_segment->index[i_index].i_position >= i_pos)
2230 if( i_index == p_segment->i_index )
2235 i_date = p_segment->index[i_index].i_time;
2238 if( p_segment->index[i_index].i_position < i_pos )
2242 msg_Warn( p_demux, "searching for cluster, could take some time" );
2244 /* search a cluster */
2245 while( ( el = p_sys->ep->Get() ) != NULL )
2247 if( MKV_IS_ID( el, KaxCluster ) )
2249 KaxCluster *cluster = (KaxCluster*)el;
2251 /* add it to the index */
2252 p_segment->IndexAppendCluster( cluster );
2254 if( (int64_t)cluster->GetElementPosition() >= i_pos )
2256 p_sys->cluster = cluster;
2267 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
2270 /*****************************************************************************
2271 * Demux: reads and demuxes data packets
2272 *****************************************************************************
2273 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2274 *****************************************************************************/
2275 static int Demux( demux_t *p_demux)
2277 demux_sys_t *p_sys = p_demux->p_sys;
2278 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
2279 matroska_segment_c *p_segmet = p_vsegment->Segment();
2280 if ( p_segmet == NULL ) return 0;
2281 int i_block_count = 0;
2284 int64_t i_block_duration;
2285 int64_t i_block_ref1;
2286 int64_t i_block_ref2;
2290 if ( p_sys->demuxer.b_die )
2293 if( p_sys->i_pts >= p_sys->i_start_pts )
2294 if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
2297 if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
2299 /* nothing left to read in this ordered edition */
2300 if ( !p_vsegment->SelectNext() )
2302 p_segmet->UnSelect( );
2304 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2306 /* switch to the next segment */
2307 p_segmet = p_vsegment->Segment();
2308 if ( !p_segmet->Select( 0 ) )
2310 msg_Err( p_demux, "Failed to select new segment" );
2317 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
2319 if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
2321 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
2322 // check if there are more chapters to read
2323 if ( p_chap != NULL )
2325 /* TODO handle successive chapters with the same user_start_time/user_end_time
2326 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
2327 p_vsegment->SelectNext();
2329 p_sys->i_pts = p_chap->i_user_end_time;
2330 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2337 msg_Warn( p_demux, "cannot get block EOF?" );
2338 p_segmet->UnSelect( );
2340 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2342 /* switch to the next segment */
2343 if ( !p_vsegment->SelectNext() )
2344 // no more segments in this stream
2346 p_segmet = p_vsegment->Segment();
2347 if ( !p_segmet->Select( 0 ) )
2349 msg_Err( p_demux, "Failed to select new segment" );
2356 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2358 if( p_sys->i_pts >= p_sys->i_start_pts )
2360 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2363 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2368 // TODO optimize when there is need to leave or when seeking has been called
2369 if( i_block_count > 5 )
2378 /*****************************************************************************
2380 *****************************************************************************/
2381 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2387 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2389 if( i_size <= 0 || mb_eof )
2394 return stream_Read( s, p_buffer, i_size );
2396 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2402 case seek_beginning:
2406 i_pos = stream_Size( s ) - i_offset;
2409 i_pos= stream_Tell( s ) + i_offset;
2413 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2420 if( stream_Seek( s, i_pos ) )
2426 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2430 uint64 vlc_stream_io_callback::getFilePointer( void )
2432 return stream_Tell( s );
2434 void vlc_stream_io_callback::close( void )
2440 /*****************************************************************************
2441 * Ebml Stream parser
2442 *****************************************************************************/
2443 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2450 mi_remain_size[0] = el_start->GetSize();
2452 for( i = 1; i < 6; i++ )
2458 mb_keep = VLC_FALSE;
2459 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2462 EbmlParser::~EbmlParser( void )
2466 for( i = 1; i < mi_level; i++ )
2472 mb_keep = VLC_FALSE;
2476 void EbmlParser::Up( void )
2478 if( mi_user_level == mi_level )
2480 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2486 void EbmlParser::Down( void )
2492 void EbmlParser::Keep( void )
2497 int EbmlParser::GetLevel( void )
2499 return mi_user_level;
2502 void EbmlParser::Reset( demux_t *p_demux )
2504 while ( mi_level > 0)
2506 delete m_el[mi_level];
2507 m_el[mi_level] = NULL;
2510 mi_user_level = mi_level = 1;
2511 #if LIBEBML_VERSION >= 0x000704
2512 // a little faster and cleaner
2513 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2515 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2517 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2520 EbmlElement *EbmlParser::Get( void )
2524 if( mi_user_level != mi_level )
2530 EbmlElement *ret = m_got;
2536 if( m_el[mi_level] )
2538 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2541 delete m_el[mi_level];
2543 mb_keep = VLC_FALSE;
2546 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2547 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2558 delete m_el[mi_level - 1];
2559 m_got = m_el[mi_level -1] = m_el[mi_level];
2560 m_el[mi_level] = NULL;
2567 else if( m_el[mi_level] == NULL )
2569 fprintf( stderr," m_el[mi_level] == NULL\n" );
2572 return m_el[mi_level];
2576 /*****************************************************************************
2578 * * LoadCues : load the cues element and update index
2580 * * LoadTags : load ... the tags element
2582 * * InformationCreate : create all information, load tags if present
2584 *****************************************************************************/
2585 void matroska_segment_c::LoadCues( )
2587 int64_t i_sav_position = es.I_O().getFilePointer();
2589 EbmlElement *el, *cues;
2591 /* *** Load the cue if found *** */
2592 if( i_cues_position < 0 )
2594 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2596 // IndexAppendCluster( cluster );
2599 vlc_bool_t b_seekable;
2601 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2605 msg_Dbg( &sys.demuxer, "loading cues" );
2606 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2607 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2611 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2612 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2616 ep = new EbmlParser( &es, cues, &sys.demuxer );
2617 while( ( el = ep->Get() ) != NULL )
2619 if( MKV_IS_ID( el, KaxCuePoint ) )
2621 #define idx index[i_index]
2624 idx.i_block_number= -1;
2625 idx.i_position = -1;
2627 idx.b_key = VLC_TRUE;
2630 while( ( el = ep->Get() ) != NULL )
2632 if( MKV_IS_ID( el, KaxCueTime ) )
2634 KaxCueTime &ctime = *(KaxCueTime*)el;
2636 ctime.ReadData( es.I_O() );
2638 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2640 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2643 while( ( el = ep->Get() ) != NULL )
2645 if( MKV_IS_ID( el, KaxCueTrack ) )
2647 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2649 ctrack.ReadData( es.I_O() );
2650 idx.i_track = uint16( ctrack );
2652 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2654 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2656 ccpos.ReadData( es.I_O() );
2657 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2659 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2661 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2663 cbnum.ReadData( es.I_O() );
2664 idx.i_block_number = uint32( cbnum );
2668 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2675 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2681 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2682 " track=%d bnum=%d", idx.i_time, idx.i_position,
2683 idx.i_track, idx.i_block_number );
2687 if( i_index >= i_index_max )
2689 i_index_max += 1024;
2690 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2696 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2704 msg_Dbg( &sys.demuxer, "loading cues done." );
2705 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2708 void matroska_segment_c::LoadTags( )
2710 int64_t i_sav_position = es.I_O().getFilePointer();
2712 EbmlElement *el, *tags;
2714 msg_Dbg( &sys.demuxer, "loading tags" );
2715 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2716 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2720 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2721 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2725 msg_Dbg( &sys.demuxer, "Tags" );
2726 ep = new EbmlParser( &es, tags, &sys.demuxer );
2727 while( ( el = ep->Get() ) != NULL )
2729 if( MKV_IS_ID( el, KaxTag ) )
2731 msg_Dbg( &sys.demuxer, "+ Tag" );
2733 while( ( el = ep->Get() ) != NULL )
2735 if( MKV_IS_ID( el, KaxTagTargets ) )
2737 msg_Dbg( &sys.demuxer, "| + Targets" );
2739 while( ( el = ep->Get() ) != NULL )
2741 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2745 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2747 msg_Dbg( &sys.demuxer, "| + General" );
2749 while( ( el = ep->Get() ) != NULL )
2751 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2755 else if( MKV_IS_ID( el, KaxTagGenres ) )
2757 msg_Dbg( &sys.demuxer, "| + Genres" );
2759 while( ( el = ep->Get() ) != NULL )
2761 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2765 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2767 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2769 while( ( el = ep->Get() ) != NULL )
2771 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2775 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2777 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2779 while( ( el = ep->Get() ) != NULL )
2781 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2785 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2787 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2789 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2791 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2793 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2795 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2797 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2799 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2801 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2803 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2805 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2807 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2809 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2811 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2815 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2822 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2828 msg_Dbg( &sys.demuxer, "loading tags done." );
2829 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2832 /*****************************************************************************
2834 *****************************************************************************/
2835 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2839 int i_upper_level = 0;
2841 msg_Dbg( &sys.demuxer, "| + Seek head" );
2843 /* Master elements */
2844 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2846 for( i = 0; i < seekhead->ListSize(); i++ )
2848 EbmlElement *l = (*seekhead)[i];
2850 if( MKV_IS_ID( l, KaxSeek ) )
2852 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2853 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2856 for( j = 0; j < sk->ListSize(); j++ )
2858 EbmlElement *l = (*sk)[j];
2860 if( MKV_IS_ID( l, KaxSeekID ) )
2862 KaxSeekID &sid = *(KaxSeekID*)l;
2863 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2865 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2867 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2868 i_pos = uint64( spos );
2872 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2878 if( id == KaxCues::ClassInfos.GlobalId )
2880 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2881 i_cues_position = segment->GetGlobalPosition( i_pos );
2883 else if( id == KaxChapters::ClassInfos.GlobalId )
2885 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2886 i_chapters_position = segment->GetGlobalPosition( i_pos );
2888 else if( id == KaxTags::ClassInfos.GlobalId )
2890 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2891 i_tags_position = segment->GetGlobalPosition( i_pos );
2897 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2902 /*****************************************************************************
2904 *****************************************************************************/
2905 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2911 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2913 tk = new mkv_track_t();
2914 tracks.push_back( tk );
2916 /* Init the track */
2917 memset( tk, 0, sizeof( mkv_track_t ) );
2919 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2920 tk->fmt.psz_language = strdup("English");
2921 tk->fmt.psz_description = NULL;
2923 tk->b_default = VLC_TRUE;
2924 tk->b_enabled = VLC_TRUE;
2925 tk->b_silent = VLC_FALSE;
2926 tk->i_number = tracks.size() - 1;
2927 tk->i_extra_data = 0;
2928 tk->p_extra_data = NULL;
2929 tk->psz_codec = NULL;
2930 tk->i_default_duration = 0;
2931 tk->f_timecodescale = 1.0;
2933 tk->b_inited = VLC_FALSE;
2934 tk->i_data_init = 0;
2935 tk->p_data_init = NULL;
2937 tk->psz_codec_name = NULL;
2938 tk->psz_codec_settings = NULL;
2939 tk->psz_codec_info_url = NULL;
2940 tk->psz_codec_download_url = NULL;
2942 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2944 for( i = 0; i < m->ListSize(); i++ )
2946 EbmlElement *l = (*m)[i];
2948 if( MKV_IS_ID( l, KaxTrackNumber ) )
2950 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2952 tk->i_number = uint32( tnum );
2953 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2955 else if( MKV_IS_ID( l, KaxTrackUID ) )
2957 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2959 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2961 else if( MKV_IS_ID( l, KaxTrackType ) )
2964 KaxTrackType &ttype = *(KaxTrackType*)l;
2966 switch( uint8(ttype) )
2970 tk->fmt.i_cat = AUDIO_ES;
2974 tk->fmt.i_cat = VIDEO_ES;
2976 case track_subtitle:
2977 psz_type = "subtitle";
2978 tk->fmt.i_cat = SPU_ES;
2981 psz_type = "unknown";
2982 tk->fmt.i_cat = UNKNOWN_ES;
2986 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2988 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2990 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2992 // tk->b_enabled = uint32( fenb );
2993 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2994 // uint32( fenb ) );
2996 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2998 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
3000 tk->b_default = uint32( fdef );
3001 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
3003 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
3005 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
3007 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
3009 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
3011 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
3013 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
3015 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
3017 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
3019 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
3021 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
3023 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
3025 tk->i_default_duration = uint64(defd);
3026 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
3028 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
3030 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
3032 tk->f_timecodescale = float( ttcs );
3033 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
3035 else if( MKV_IS_ID( l, KaxTrackName ) )
3037 KaxTrackName &tname = *(KaxTrackName*)l;
3039 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
3040 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
3042 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
3044 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
3046 tk->fmt.psz_language = strdup( string( lang ).c_str() );
3047 msg_Dbg( &sys.demuxer,
3048 "| | | + Track Language=`%s'", tk->fmt.psz_language );
3050 else if( MKV_IS_ID( l, KaxCodecID ) )
3052 KaxCodecID &codecid = *(KaxCodecID*)l;
3054 tk->psz_codec = strdup( string( codecid ).c_str() );
3055 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
3057 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
3059 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
3061 tk->i_extra_data = cpriv.GetSize();
3062 if( tk->i_extra_data > 0 )
3064 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
3065 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
3067 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
3069 else if( MKV_IS_ID( l, KaxCodecName ) )
3071 KaxCodecName &cname = *(KaxCodecName*)l;
3073 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
3074 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
3076 else if( MKV_IS_ID( l, KaxContentEncodings ) )
3078 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
3079 MkvTree( sys.demuxer, 3, "Content Encodings" );
3080 for( j = 0; j < cencs->ListSize(); j++ )
3082 EbmlElement *l2 = (*cencs)[j];
3083 if( MKV_IS_ID( l2, KaxContentEncoding ) )
3085 MkvTree( sys.demuxer, 4, "Content Encoding" );
3086 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
3087 for( k = 0; k < cenc->ListSize(); k++ )
3089 EbmlElement *l3 = (*cenc)[k];
3090 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
3092 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
3093 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
3095 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
3097 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
3098 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
3100 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
3102 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
3103 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
3105 else if( MKV_IS_ID( l3, KaxContentCompression ) )
3107 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
3108 MkvTree( sys.demuxer, 5, "Content Compression" );
3109 for( n = 0; n < compr->ListSize(); n++ )
3111 EbmlElement *l4 = (*compr)[n];
3112 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
3114 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
3115 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
3116 if( uint32( compalg ) == 0 )
3118 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
3123 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
3130 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
3137 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
3142 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
3144 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
3146 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
3147 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
3149 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
3151 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
3153 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3154 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
3156 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3158 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3160 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3161 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
3163 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3165 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3167 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3169 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3171 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3173 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3175 else if( MKV_IS_ID( l, KaxTrackVideo ) )
3177 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3180 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
3183 for( j = 0; j < tkv->ListSize(); j++ )
3185 EbmlElement *l = (*tkv)[j];
3186 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3188 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3190 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
3192 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3194 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3196 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
3199 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3201 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3203 tk->fmt.video.i_width = uint16( vwidth );
3204 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
3206 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3208 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3210 tk->fmt.video.i_height = uint16( vheight );
3211 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
3213 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3215 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3217 tk->fmt.video.i_visible_width = uint16( vwidth );
3218 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
3220 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
3222 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
3224 tk->fmt.video.i_visible_height = uint16( vheight );
3225 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
3227 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
3229 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
3231 tk->f_fps = float( vfps );
3232 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
3234 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
3236 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
3238 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
3239 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
3241 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
3243 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
3245 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
3247 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
3249 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
3251 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
3255 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
3258 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
3259 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
3261 else if( MKV_IS_ID( l, KaxTrackAudio ) )
3263 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
3266 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
3268 for( j = 0; j < tka->ListSize(); j++ )
3270 EbmlElement *l = (*tka)[j];
3272 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
3274 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
3276 tk->fmt.audio.i_rate = (int)float( afreq );
3277 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
3279 else if( MKV_IS_ID( l, KaxAudioChannels ) )
3281 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
3283 tk->fmt.audio.i_channels = uint8( achan );
3284 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
3286 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
3288 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
3290 tk->fmt.audio.i_bitspersample = uint8( abits );
3291 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
3295 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
3301 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
3302 typeid(*l).name() );
3307 /*****************************************************************************
3309 *****************************************************************************/
3310 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
3314 int i_upper_level = 0;
3316 msg_Dbg( &sys.demuxer, "| + Tracks" );
3318 /* Master elements */
3319 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
3321 for( i = 0; i < tracks->ListSize(); i++ )
3323 EbmlElement *l = (*tracks)[i];
3325 if( MKV_IS_ID( l, KaxTrackEntry ) )
3327 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
3331 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3336 /*****************************************************************************
3338 *****************************************************************************/
3339 void matroska_segment_c::ParseInfo( KaxInfo *info )
3344 int i_upper_level = 0;
3346 msg_Dbg( &sys.demuxer, "| + Information" );
3348 /* Master elements */
3349 m = static_cast<EbmlMaster *>(info);
3350 m->Read( es, info->Generic().Context, i_upper_level, el, true );
3352 for( i = 0; i < m->ListSize(); i++ )
3354 EbmlElement *l = (*m)[i];
3356 if( MKV_IS_ID( l, KaxSegmentUID ) )
3358 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3360 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3362 else if( MKV_IS_ID( l, KaxPrevUID ) )
3364 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3366 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3368 else if( MKV_IS_ID( l, KaxNextUID ) )
3370 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3372 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3374 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3376 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3378 i_timescale = uint64(tcs);
3380 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3383 else if( MKV_IS_ID( l, KaxDuration ) )
3385 KaxDuration &dur = *(KaxDuration*)l;
3387 i_duration = mtime_t( double( dur ) );
3389 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3392 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3394 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3396 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3398 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3399 psz_muxing_application );
3401 else if( MKV_IS_ID( l, KaxWritingApp ) )
3403 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3405 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3407 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3408 psz_writing_application );
3410 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3412 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3414 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3416 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3417 psz_segment_filename );
3419 else if( MKV_IS_ID( l, KaxTitle ) )
3421 KaxTitle &title = *(KaxTitle*)l;
3423 psz_title = UTF8ToStr( UTFstring( title ) );
3425 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3427 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3429 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3431 families.push_back(*uid);
3433 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3435 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3436 else if( MKV_IS_ID( l, KaxDateUTC ) )
3438 KaxDateUTC &date = *(KaxDateUTC*)l;
3443 i_date = date.GetEpochDate();
3444 memset( buffer, 0, 256 );
3445 if( gmtime_r( &i_date, &tmres ) &&
3446 asctime_r( &tmres, buffer ) )
3448 buffer[strlen( buffer)-1]= '\0';
3449 psz_date_utc = strdup( buffer );
3450 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3454 #if LIBMATROSKA_VERSION >= 0x000704
3455 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3457 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3458 chapter_translation_c translated;
3460 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3461 for( j = 0; j < p_trans->ListSize(); j++ )
3463 EbmlElement *l = (*p_trans)[j];
3465 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3467 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3469 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3471 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3473 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3475 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3479 translations.push_back( translated );
3484 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3488 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3489 i_duration = mtime_t(f_dur);
3493 /*****************************************************************************
3495 *****************************************************************************/
3496 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3500 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3501 for( i = 0; i < ca->ListSize(); i++ )
3503 EbmlElement *l = (*ca)[i];
3505 if( MKV_IS_ID( l, KaxChapterUID ) )
3507 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3508 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3510 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3512 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3513 chapters.b_display_seekpoint = uint8( flag ) == 0;
3515 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3517 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3519 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3520 chapters.i_start_time = uint64( start ) / I64C(1000);
3522 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3524 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3526 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3527 chapters.i_end_time = uint64( end ) / I64C(1000);
3529 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3531 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3533 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3535 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3536 for( j = 0; j < cd->ListSize(); j++ )
3538 EbmlElement *l= (*cd)[j];
3540 if( MKV_IS_ID( l, KaxChapterString ) )
3544 KaxChapterString &name =*(KaxChapterString*)l;
3545 for (k = 0; k < i_level; k++)
3546 chapters.psz_name += '+';
3547 chapters.psz_name += ' ';
3548 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3549 chapters.b_user_display = true;
3551 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3553 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3555 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3556 const char *psz = string( lang ).c_str();
3558 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3560 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3562 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3563 const char *psz = string( ct ).c_str();
3565 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3569 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3571 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3573 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3574 chapter_codec_cmds_c *p_ccodec = NULL;
3576 for( j = 0; j < cp->ListSize(); j++ )
3578 EbmlElement *k= (*cp)[j];
3580 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3582 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3583 if ( uint32(*p_codec_id) == 0 )
3584 p_ccodec = new matroska_script_codec_c( sys );
3585 else if ( uint32(*p_codec_id) == 1 )
3586 p_ccodec = new dvd_chapter_codec_c( sys );
3591 if ( p_ccodec != NULL )
3593 for( j = 0; j < cp->ListSize(); j++ )
3595 EbmlElement *k= (*cp)[j];
3597 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3599 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3600 p_ccodec->SetPrivate( *p_private );
3602 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3604 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3607 chapters.codecs.push_back( p_ccodec );
3610 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3612 chapter_item_c *new_sub_chapter = new chapter_item_c();
3613 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3614 new_sub_chapter->psz_parent = &chapters;
3615 chapters.sub_chapters.push_back( new_sub_chapter );
3620 /*****************************************************************************
3622 *****************************************************************************/
3623 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3627 int i_upper_level = 0;
3630 /* Master elements */
3631 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3633 for( i = 0; i < chapters->ListSize(); i++ )
3635 EbmlElement *l = (*chapters)[i];
3637 if( MKV_IS_ID( l, KaxEditionEntry ) )
3639 chapter_edition_c *p_edition = new chapter_edition_c();
3641 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3643 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3644 for( j = 0; j < E->ListSize(); j++ )
3646 EbmlElement *l = (*E)[j];
3648 if( MKV_IS_ID( l, KaxChapterAtom ) )
3650 chapter_item_c *new_sub_chapter = new chapter_item_c();
3651 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3652 p_edition->sub_chapters.push_back( new_sub_chapter );
3654 else if( MKV_IS_ID( l, KaxEditionUID ) )
3656 p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3658 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3660 p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3662 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3664 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3665 i_default_edition = stored_editions.size();
3669 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3672 stored_editions.push_back( p_edition );
3676 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3680 for( i = 0; i < stored_editions.size(); i++ )
3682 stored_editions[i]->RefreshChapters( );
3685 if ( stored_editions[i_default_edition]->b_ordered )
3687 /* update the duration of the segment according to the sum of all sub chapters */
3688 i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3694 void matroska_segment_c::ParseCluster( )
3699 int i_upper_level = 0;
3701 /* Master elements */
3702 m = static_cast<EbmlMaster *>( cluster );
3703 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3705 for( i = 0; i < m->ListSize(); i++ )
3707 EbmlElement *l = (*m)[i];
3709 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3711 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3713 cluster->InitTimecode( uint64( ctc ), i_timescale );
3718 i_start_time = cluster->GlobalTimecode() / 1000;
3721 /*****************************************************************************
3722 * InformationCreate:
3723 *****************************************************************************/
3724 void matroska_segment_c::InformationCreate( )
3728 sys.meta = vlc_meta_New();
3732 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3736 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3738 if( psz_segment_filename )
3740 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3742 if( psz_muxing_application )
3744 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3746 if( psz_writing_application )
3748 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3751 for( i_track = 0; i_track < tracks.size(); i_track++ )
3753 mkv_track_t *tk = tracks[i_track];
3754 vlc_meta_t *mtk = vlc_meta_New();
3756 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3757 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3758 sys.meta->track[sys.meta->i_track++] = mtk;
3760 if( tk->fmt.psz_description )
3762 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3764 if( tk->psz_codec_name )
3766 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3768 if( tk->psz_codec_settings )
3770 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3772 if( tk->psz_codec_info_url )
3774 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3776 if( tk->psz_codec_download_url )
3778 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3782 if( i_tags_position >= 0 )
3784 vlc_bool_t b_seekable;
3786 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3795 /*****************************************************************************
3797 *****************************************************************************/
3799 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3801 #define idx index[i_index]
3803 idx.i_block_number= -1;
3804 idx.i_position = cluster->GetElementPosition();
3806 idx.b_key = VLC_TRUE;
3809 if( i_index >= i_index_max )
3811 i_index_max += 1024;
3812 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3817 static char * UTF8ToStr( const UTFstring &u )
3826 p = dst = (char*)malloc( i_src + 1);
3845 void chapter_edition_c::RefreshChapters( )
3847 chapter_item_c::RefreshChapters( b_ordered, -1 );
3848 b_display_seekpoint = false;
3851 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3853 int64_t i_user_time = i_prev_user_time;
3855 // first the sub-chapters, and then ourself
3856 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3857 while ( index != sub_chapters.end() )
3859 i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3865 // the ordered chapters always start at zero
3866 if ( i_prev_user_time == -1 )
3868 if ( i_user_time == -1 )
3870 i_prev_user_time = 0;
3873 i_user_start_time = i_prev_user_time;
3874 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3876 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3880 i_user_end_time = i_user_time;
3885 std::sort( sub_chapters.begin(), sub_chapters.end() );
3886 i_user_start_time = i_start_time;
3887 if ( i_end_time != -1 )
3888 i_user_end_time = i_end_time;
3889 else if ( i_user_time != -1 )
3890 i_user_end_time = i_user_time;
3892 i_user_end_time = i_user_start_time;
3895 return i_user_end_time;
3898 mtime_t chapter_edition_c::Duration() const
3900 mtime_t i_result = 0;
3902 if ( sub_chapters.size() )
3904 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3906 i_result = (*index)->i_user_end_time;
3912 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3914 chapter_item_c *psz_result = NULL;
3916 if ( i_user_timecode >= i_user_start_time &&
3917 ( i_user_timecode < i_user_end_time ||
3918 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3920 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3921 while ( index != sub_chapters.end() && psz_result == NULL )
3923 psz_result = (*index)->FindTimecode( i_user_timecode );
3927 if ( psz_result == NULL )
3934 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
3936 if ( &item == this )
3939 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
3940 while ( index != sub_chapters.end() )
3942 if ( (*index)->ParentOf( item ) )
3950 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3952 for (size_t i=0; i<opened_segments.size(); i++)
3954 opened_segments[i]->PreloadFamily( of_segment );
3957 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3962 for (size_t i=0; i<families.size(); i++)
3964 for (size_t j=0; j<of_segment.families.size(); j++)
3966 if ( families[i] == of_segment.families[j] )
3974 // preload all the linked segments for all preloaded segments
3975 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3977 size_t i_preloaded, i, j;
3978 virtual_segment_c *p_seg;
3980 p_current_segment = VirtualFromSegments( p_segment );
3982 used_segments.push_back( p_current_segment );
3984 // create all the other virtual segments of the family
3987 for ( i=0; i< opened_segments.size(); i++ )
3989 if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
3991 p_seg = VirtualFromSegments( opened_segments[i] );
3992 used_segments.push_back( p_seg );
3996 } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
3998 // publish all editions of all usable segment
3999 for ( i=0; i< used_segments.size(); i++ )
4001 p_seg = used_segments[i];
4002 if ( p_seg->p_editions != NULL )
4004 std::string sz_name;
4005 input_title_t *p_title = vlc_input_title_New();
4006 p_seg->i_sys_title = i;
4009 // TODO use a name for each edition, let the TITLE deal with a codec name
4010 for ( j=0; j<p_seg->p_editions->size(); j++ )
4012 if ( p_title->psz_name == NULL )
4014 sz_name = (*p_seg->p_editions)[j]->GetMainName();
4015 if ( sz_name != "" )
4016 p_title->psz_name = strdup( sz_name.c_str() );
4019 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
4022 p_edition->PublishChapters( *p_title, i_chapters, 0 );
4025 // create a name if there is none
4026 if ( p_title->psz_name == NULL )
4028 sz_name = N_("Segment ");
4030 sprintf( psz_str, "%d", i );
4032 p_title->psz_name = strdup( sz_name.c_str() );
4035 titles.push_back( *p_title );
4040 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
4042 for ( size_t i=0; i< used_segments.size(); i++ )
4044 if ( used_segments[i]->FindUID( segment.segment_uid ) )
4050 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
4052 size_t i_preloaded, i;
4054 virtual_segment_c *p_result = new virtual_segment_c( p_segment );
4056 // fill our current virtual segment with all hard linked segments
4059 for ( i=0; i< opened_segments.size(); i++ )
4061 i_preloaded += p_result->AddSegment( opened_segments[i] );
4063 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
4067 p_result->PreloadLinked( );
4069 p_result->PrepareChapters( );
4074 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
4076 if ( p_new_segment != NULL && p_new_segment != p_current_segment )
4078 if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
4079 p_current_segment->Segment()->UnSelect();
4081 p_current_segment = p_new_segment;
4082 i_current_title = p_new_segment->i_sys_title;
4085 p_current_segment->LoadCues();
4086 f_duration = p_current_segment->Duration();
4088 /* add information */
4089 p_current_segment->Segment()->InformationCreate( );
4091 p_current_segment->Segment()->Select( 0 );
4096 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
4098 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
4099 if ( *p_itema == p_item_b->prev_segment_uid )
4102 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
4103 if ( *p_itema == p_item_b->segment_uid )
4106 if ( *p_itema == p_item_b->prev_segment_uid )
4112 bool matroska_segment_c::Preload( )
4117 EbmlElement *el = NULL;
4119 ep->Reset( &sys.demuxer );
4121 while( ( el = ep->Get() ) != NULL )
4123 if( MKV_IS_ID( el, KaxInfo ) )
4125 ParseInfo( static_cast<KaxInfo*>( el ) );
4127 else if( MKV_IS_ID( el, KaxTracks ) )
4129 ParseTracks( static_cast<KaxTracks*>( el ) );
4131 else if( MKV_IS_ID( el, KaxSeekHead ) )
4133 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
4135 else if( MKV_IS_ID( el, KaxCues ) )
4137 msg_Dbg( &sys.demuxer, "| + Cues" );
4139 else if( MKV_IS_ID( el, KaxCluster ) )
4141 msg_Dbg( &sys.demuxer, "| + Cluster" );
4143 cluster = (KaxCluster*)el;
4145 i_start_pos = cluster->GetElementPosition();
4149 /* stop parsing the stream */
4152 else if( MKV_IS_ID( el, KaxAttachments ) )
4154 msg_Dbg( &sys.demuxer, "| + Attachments FIXME (but probably never supported)" );
4156 else if( MKV_IS_ID( el, KaxChapters ) )
4158 msg_Dbg( &sys.demuxer, "| + Chapters" );
4159 ParseChapters( static_cast<KaxChapters*>( el ) );
4161 else if( MKV_IS_ID( el, KaxTag ) )
4163 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
4167 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
4176 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4178 for (size_t i=0; i<opened_segments.size(); i++)
4180 if ( opened_segments[i]->segment_uid == uid )
4181 return opened_segments[i];
4186 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id,
4187 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
4188 const void *p_cookie,
4189 size_t i_cookie_size,
4190 virtual_segment_c * &p_segment_found )
4192 chapter_item_c *p_result = NULL;
4193 for (size_t i=0; i<used_segments.size(); i++)
4195 p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4196 if ( p_result != NULL )
4198 p_segment_found = used_segments[i];
4205 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
4207 chapter_item_c *p_result = NULL;
4208 for (size_t i=0; i<used_segments.size(); i++)
4210 p_result = used_segments[i]->FindChapter( i_find_uid );
4211 if ( p_result != NULL )
4213 p_segment_found = used_segments[i];
4220 void virtual_segment_c::Sort()
4222 // keep the current segment index
4223 matroska_segment_c *p_segment = linked_segments[i_current_segment];
4225 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
4227 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
4228 if ( linked_segments[i_current_segment] == p_segment )
4232 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
4235 // check if it's not already in here
4236 for ( i=0; i<linked_segments.size(); i++ )
4238 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
4242 // find possible mates
4243 for ( i=0; i<linked_uids.size(); i++ )
4245 if ( p_segment->segment_uid == linked_uids[i]
4246 || p_segment->prev_segment_uid == linked_uids[i]
4247 || p_segment->next_segment_uid == linked_uids[i] )
4249 linked_segments.push_back( p_segment );
4251 AppendUID( p_segment->prev_segment_uid );
4252 AppendUID( p_segment->next_segment_uid );
4260 void virtual_segment_c::PreloadLinked( )
4262 for ( size_t i=0; i<linked_segments.size(); i++ )
4264 linked_segments[i]->Preload( );
4266 i_current_edition = linked_segments[0]->i_default_edition;
4269 mtime_t virtual_segment_c::Duration() const
4272 if ( linked_segments.size() == 0 )
4275 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
4276 // p_last_segment->ParseCluster( );
4278 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
4283 void virtual_segment_c::LoadCues( )
4285 for ( size_t i=0; i<linked_segments.size(); i++ )
4287 linked_segments[i]->LoadCues();
4291 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
4293 if ( UID.GetBuffer() == NULL )
4296 for (size_t i=0; i<linked_uids.size(); i++)
4298 if ( UID == linked_uids[i] )
4301 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
4304 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
4307 int i_track_skipping;
4308 int64_t i_block_duration;
4309 int64_t i_block_ref1;
4310 int64_t i_block_ref2;
4312 int64_t i_seek_position = i_start_pos;
4313 int64_t i_seek_time = i_start_time;
4319 for( ; i_idx < i_index; i_idx++ )
4321 if( index[i_idx].i_time + i_time_offset > i_date )
4332 i_seek_position = index[i_idx].i_position;
4333 i_seek_time = index[i_idx].i_time;
4336 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
4337 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
4339 es.I_O().setFilePointer( i_seek_position, seek_beginning );
4342 ep = new EbmlParser( &es, segment, &sys.demuxer );
4345 sys.i_start_pts = i_date;
4347 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
4349 /* now parse until key frame */
4350 #define tk tracks[i_track]
4351 i_track_skipping = 0;
4352 for( i_track = 0; i_track < tracks.size(); i_track++ )
4354 if( tk->fmt.i_cat == VIDEO_ES )
4356 tk->b_search_keyframe = VLC_TRUE;
4359 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
4363 while( i_track_skipping > 0 )
4365 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
4367 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
4372 for( i_track = 0; i_track < tracks.size(); i_track++ )
4374 if( tk->i_number == block->TrackNum() )
4380 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
4382 if( i_track < tracks.size() )
4384 if( sys.i_pts >= sys.i_start_pts )
4386 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4387 i_track_skipping = 0;
4389 else if( tk->fmt.i_cat == VIDEO_ES )
4391 if( i_block_ref1 == -1 && tk->b_search_keyframe )
4393 tk->b_search_keyframe = VLC_FALSE;
4396 if( !tk->b_search_keyframe )
4398 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4408 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
4410 demux_sys_t *p_sys = demuxer.p_sys;
4413 // find the actual time for an ordered edition
4414 if ( psz_chapter == NULL )
4416 if ( Edition() && Edition()->b_ordered )
4418 /* 1st, we need to know in which chapter we are */
4419 psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
4423 if ( psz_chapter != NULL )
4425 psz_current_chapter = psz_chapter;
4426 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
4427 if ( psz_chapter->i_seekpoint_num > 0 )
4429 demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
4430 demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
4431 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
4435 // find the best matching segment
4436 for ( i=0; i<linked_segments.size(); i++ )
4438 if ( i_date < linked_segments[i]->i_start_time )
4445 if ( i_current_segment != i )
4447 linked_segments[i_current_segment]->UnSelect();
4448 linked_segments[i]->Select( i_date );
4449 i_current_segment = i;
4452 linked_segments[i]->Seek( i_date, i_time_offset );
4455 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
4459 uint32 codec_time = uint32(-1);
4460 for( i = 0; i < command.ListSize(); i++ )
4462 const EbmlElement *k = command[i];
4464 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
4466 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
4471 for( i = 0; i < command.ListSize(); i++ )
4473 const EbmlElement *k = command[i];
4475 if( MKV_IS_ID( k, KaxChapterProcessData ) )
4477 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4478 switch ( codec_time )
4481 during_cmds.push_back( *p_data );
4484 enter_cmds.push_back( *p_data );
4487 leave_cmds.push_back( *p_data );
4496 bool chapter_item_c::Enter( bool b_do_subs )
4498 bool f_result = false;
4499 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4500 while ( index != codecs.end() )
4502 f_result |= (*index)->Enter();
4509 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4510 while ( index_ != sub_chapters.end() )
4512 f_result |= (*index_)->Enter( true );
4519 bool chapter_item_c::Leave( bool b_do_subs )
4521 bool f_result = false;
4522 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4523 while ( index != codecs.end() )
4525 f_result |= (*index)->Leave();
4532 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4533 while ( index_ != sub_chapters.end() )
4535 f_result |= (*index_)->Leave( true );
4542 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item )
4544 chapter_item_c *p_common_parent = p_item;
4546 // leave, up to a common parent
4547 while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
4549 if ( p_common_parent->Leave( false ) )
4551 p_common_parent = p_common_parent->psz_parent;
4554 // enter from the parent to <this>
4555 if ( p_common_parent != NULL )
4559 for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
4561 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
4563 p_common_parent = p_common_parent->sub_chapters[i];
4568 if ( p_common_parent == this )
4571 if ( p_common_parent->Enter( false ) )
4576 return Enter( true );
4579 bool dvd_chapter_codec_c::Enter()
4581 bool f_result = false;
4582 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4583 while ( index != enter_cmds.end() )
4585 if ( (*index).GetSize() )
4587 binary *p_data = (*index).GetBuffer();
4588 size_t i_size = *p_data++;
4589 // avoid reading too much from the buffer
4590 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4591 for ( ; i_size > 0; i_size--, p_data += 8 )
4593 msg_Dbg( &sys.demuxer, "Matroska DVD enter command" );
4594 f_result |= interpretor.Interpret( p_data );
4602 bool dvd_chapter_codec_c::Leave()
4604 bool f_result = false;
4605 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4606 while ( index != leave_cmds.end() )
4608 if ( (*index).GetSize() )
4610 binary *p_data = (*index).GetBuffer();
4611 size_t i_size = *p_data++;
4612 // avoid reading too much from the buffer
4613 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4614 for ( ; i_size > 0; i_size--, p_data += 8 )
4616 msg_Dbg( &sys.demuxer, "Matroska DVD leave command" );
4617 f_result |= interpretor.Interpret( p_data );
4625 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
4626 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4631 virtual_segment_c *p_segment;
4632 chapter_item_c *p_chapter;
4633 bool f_result = false;
4634 uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4636 // handle register tests if there are some
4637 if ( (i_command & 0xF0) != 0 )
4639 bool b_test_positive = (i_command & CMD_DVD_IF_NOT) == 0;
4640 bool b_test_value = (i_command & CMD_DVD_TEST_VALUE) != 0;
4641 uint8 i_test = i_command & 0x70;
4645 i_value = ( p_command[4] << 8 ) + p_command[5];
4647 i_value = GetPRM( p_command[7] );
4651 case CMD_DVD_IF_GPREG_EQUAL:
4653 msg_Dbg( &sys.demuxer, "IF %s EQUALS %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4654 if (!( GetPRM( p_command[3] ) == i_value ))
4656 b_test_positive = !b_test_positive;
4659 case CMD_DVD_IF_GPREG_INF:
4661 msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4662 if (!( GetPRM( p_command[3] ) < i_value ))
4664 b_test_positive = !b_test_positive;
4667 case CMD_DVD_IF_GPREG_AND:
4669 msg_Dbg( &sys.demuxer, "IF %s & %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4670 if (!( GetPRM( p_command[3] ) & i_value ))
4672 b_test_positive = !b_test_positive;
4675 case CMD_DVD_IF_GPREG_SUP_EQUAL:
4676 // if superior or equal
4677 msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4678 if (!( GetPRM( p_command[3] ) >= i_value ))
4680 b_test_positive = !b_test_positive;
4685 if ( !b_test_positive )
4689 // strip the test command
4690 i_command &= 0xFF0F;
4692 switch ( i_command )
4697 msg_Dbg( &sys.demuxer, "NOP" );
4702 msg_Dbg( &sys.demuxer, "Break" );
4706 case CMD_DVD_JUMP_TT:
4708 uint8 i_title = p_command[5];
4709 msg_Dbg( &sys.demuxer, "JumpTT %d", i_title );
4711 // find in the ChapProcessPrivate matching this Title level
4712 p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
4713 if ( p_chapter != NULL )
4715 // if the segment is not part of the current segment, select the new one
4716 if ( p_segment != sys.p_current_segment )
4718 sys.PreparePlayback( p_segment );
4721 // jump to the location in the found segment
4722 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, NULL );
4723 p_chapter->Enter( true );
4730 case CMD_DVD_CALLSS_VTSM1:
4732 msg_Dbg( &sys.demuxer, "CallSS VTSM" );
4733 switch( (p_command[6] & 0xC0) >> 6 ) {
4735 switch ( p_command[5] )
4738 msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[5]);
4741 msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[5]);
4744 msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[5]);
4747 msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[5]);
4750 msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[5]);
4753 msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[5]);
4756 msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[5]);
4759 msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[5]);
4762 p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_command[5], 1, p_segment );
4763 if ( p_chapter != NULL )
4765 // if the segment is not part of the current segment, select the new one
4766 if ( p_segment != sys.p_current_segment )
4768 sys.PreparePlayback( p_segment );
4771 p_chapter->Enter( true );
4773 // jump to the location in the found segment
4774 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
4779 msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4782 msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4785 msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[3] << 8) + p_command[4], p_command[5]);
4790 case CMD_DVD_SET_GPRMMD:
4792 msg_Dbg( &sys.demuxer, "Set GPRMMD [%d]=%d", (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3]);
4794 if ( !SetGPRM( (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3] ) )
4795 msg_Dbg( &sys.demuxer, "Set GPRMMD failed" );
4798 case CMD_DVD_LINKPGCN:
4800 uint16 i_pgcn = (p_command[6] << 8) + p_command[7];
4802 msg_Dbg( &sys.demuxer, "Link PGCN(%d)", i_pgcn );
4806 case CMD_DVD_LINKCN:
4808 msg_Dbg( &sys.demuxer, "LinkCN (cell %d)", (p_command[6] << 8) + p_command[7] );
4813 case CMD_DVD_GOTO_LINE:
4815 msg_Dbg( &sys.demuxer, "GotoLine (%d)", (p_command[6] << 8) + p_command[7] );
4821 msg_Dbg( &sys.demuxer, "unsupported command : %02X %02X %02X %02X %02X %02X %02X %02X"
4837 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4839 if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
4842 if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
4845 uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
4846 uint8 i_title = *(uint8*)p_cookie;
4848 return (i_gtitle == i_title);
4851 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4853 if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 7 )
4856 if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
4859 uint8 i_pgc_type = data.m_private_data.GetBuffer()[3];
4860 uint8 i_pgc = *(uint8*)p_cookie;
4862 return (i_pgc_type == i_pgc);
4865 bool matroska_script_codec_c::Enter()
4867 bool f_result = false;
4868 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4869 while ( index != enter_cmds.end() )
4871 if ( (*index).GetSize() )
4873 msg_Dbg( &sys.demuxer, "Matroska Script enter command" );
4874 f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4881 bool matroska_script_codec_c::Leave()
4883 bool f_result = false;
4884 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4885 while ( index != leave_cmds.end() )
4887 if ( (*index).GetSize() )
4889 msg_Dbg( &sys.demuxer, "Matroska Script leave command" );
4890 f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4897 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript
4898 // for a description of existing commands
4899 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4901 bool b_result = false;
4903 char *psz_str = (char*) malloc( i_size + 1 );
4904 memcpy( psz_str, p_command, i_size );
4905 psz_str[ i_size ] = '\0';
4907 std::string sz_command = psz_str;
4910 msg_Dbg( &sys.demuxer, "command : %s", sz_command.c_str() );
4912 if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
4917 for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
4919 if ( sz_command[i] == '(' )
4926 for ( j=i; j<sz_command.size(); j++)
4928 if ( sz_command[j] == ')' )
4935 std::string st = sz_command.substr( i+1, j-i-1 );
4936 int64_t i_chapter_uid = atoi( st.c_str() );
4938 virtual_segment_c *p_segment;
4939 chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
4941 if ( p_chapter == NULL )
4942 msg_Dbg( &sys.demuxer, "Chapter %d not found", i_chapter_uid);
4945 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );