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 sprintf( s_value, "%.5d", value );
460 else if ( value < 0x80 )
462 sprintf( s_reg_value, "%.5d", GetPRM( value ) );
466 result += s_reg_value;
471 sprintf( s_reg_value, "%.5d", GetPRM( value ) );
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)
602 virtual ~chapter_item_c()
604 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
605 while ( index != codecs.end() )
610 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
611 while ( index_ != sub_chapters.end() )
618 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
619 int PublishChapters( input_title_t & title, int & i_user_chapters, int i_level = 0 );
620 chapter_item_c * FindTimecode( mtime_t i_timecode );
621 void Append( const chapter_item_c & edition );
622 chapter_item_c * FindChapter( int64_t i_find_uid );
623 virtual chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
624 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
625 const void *p_cookie,
626 size_t i_cookie_size );
627 std::string GetCodecName( bool f_for_title = false ) const;
628 bool ParentOf( const chapter_item_c & item ) const;
630 int64_t i_start_time, i_end_time;
631 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
632 std::vector<chapter_item_c*> sub_chapters;
635 bool b_display_seekpoint;
637 std::string psz_name;
638 chapter_item_c *psz_parent;
641 std::vector<chapter_codec_cmds_c*> codecs;
643 bool operator<( const chapter_item_c & item ) const
645 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) );
648 bool Enter( bool b_do_subchapters );
649 bool Leave( bool b_do_subchapters );
650 bool EnterAndLeave( chapter_item_c *p_item );
653 class chapter_edition_c : public chapter_item_c
660 void RefreshChapters( );
661 mtime_t Duration() const;
662 std::string GetMainName() const;
667 class matroska_segment_c
670 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
673 ,i_timescale(MKVD_TIMECODESCALE)
677 ,i_chapters_position(-1)
684 ,psz_muxing_application(NULL)
685 ,psz_writing_application(NULL)
686 ,psz_segment_filename(NULL)
689 ,i_default_edition(0)
694 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
697 virtual ~matroska_segment_c()
699 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
701 #define tk tracks[i_track]
702 if( tk->fmt.psz_description )
704 free( tk->fmt.psz_description );
708 free( tk->psz_codec );
710 if( tk->fmt.psz_language )
712 free( tk->fmt.psz_language );
718 if( psz_writing_application )
720 free( psz_writing_application );
722 if( psz_muxing_application )
724 free( psz_muxing_application );
726 if( psz_segment_filename )
728 free( psz_segment_filename );
736 free( psz_date_utc );
743 std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
744 while ( index != stored_editions.end() )
755 uint64_t i_timescale;
757 /* duration of the segment */
759 mtime_t i_start_time;
762 std::vector<mkv_track_t*> tracks;
765 int64_t i_cues_position;
766 int64_t i_chapters_position;
767 int64_t i_tags_position;
771 KaxSegmentUID segment_uid;
772 KaxPrevUID prev_segment_uid;
773 KaxNextUID next_segment_uid;
781 char *psz_muxing_application;
782 char *psz_writing_application;
783 char *psz_segment_filename;
787 /* !!!!! GCC 3.3 bug on Darwin !!!!! */
788 /* when you remove this variable the compiler issues an atomicity error */
789 /* this variable only works when using std::vector<chapter_edition_c> */
790 std::vector<chapter_edition_c*> stored_editions;
791 int i_default_edition;
793 std::vector<chapter_translation_c> translations;
794 std::vector<KaxSegmentFamily> families;
801 bool PreloadFamily( const matroska_segment_c & segment );
802 void ParseInfo( KaxInfo *info );
803 void ParseChapters( KaxChapters *chapters );
804 void ParseSeekHead( KaxSeekHead *seekhead );
805 void ParseTracks( KaxTracks *tracks );
806 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
807 void ParseTrackEntry( KaxTrackEntry *m );
808 void ParseCluster( );
809 void IndexAppendCluster( KaxCluster *cluster );
812 void InformationCreate( );
813 void Seek( mtime_t i_date, mtime_t i_time_offset );
814 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
815 bool Select( mtime_t i_start_time );
818 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
821 // class holding hard-linked segment together in the playback order
822 class virtual_segment_c
825 virtual_segment_c( matroska_segment_c *p_segment )
828 ,i_current_segment(0)
829 ,i_current_edition(-1)
830 ,psz_current_chapter(NULL)
832 linked_segments.push_back( p_segment );
834 AppendUID( p_segment->segment_uid );
835 AppendUID( p_segment->prev_segment_uid );
836 AppendUID( p_segment->next_segment_uid );
840 size_t AddSegment( matroska_segment_c *p_segment );
841 void PreloadLinked( );
842 mtime_t Duration( ) const;
844 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
846 inline chapter_edition_c *Edition()
848 if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
849 return (*p_editions)[i_current_edition];
853 matroska_segment_c * Segment() const
855 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
857 return linked_segments[i_current_segment];
860 inline const chapter_item_c *CurrentChapter() const {
861 return psz_current_chapter;
866 if ( i_current_segment < linked_segments.size()-1 )
874 bool FindUID( KaxSegmentUID & uid ) const
876 for ( size_t i=0; i<linked_uids.size(); i++ )
878 if ( linked_uids[i] == uid )
884 bool UpdateCurrentToChapter( demux_t & demux );
885 void PrepareChapters( );
887 chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
888 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
889 const void *p_cookie,
890 size_t i_cookie_size );
891 chapter_item_c *FindChapter( int64_t i_find_uid );
893 std::vector<chapter_edition_c*> *p_editions;
897 std::vector<matroska_segment_c*> linked_segments;
898 std::vector<KaxSegmentUID> linked_uids;
899 size_t i_current_segment;
901 int i_current_edition;
902 chapter_item_c *psz_current_chapter;
904 void AppendUID( const EbmlBinary & UID );
907 class matroska_stream_c
910 matroska_stream_c( demux_sys_t & demuxer )
916 virtual ~matroska_stream_c()
925 std::vector<matroska_segment_c*> segments;
933 demux_sys_t( demux_t & demux )
940 ,p_current_segment(NULL)
944 virtual ~demux_sys_t()
947 for ( i=0; i<streams.size(); i++ )
949 for ( i=0; i<opened_segments.size(); i++ )
950 delete opened_segments[i];
951 for ( i=0; i<used_segments.size(); i++ )
952 delete used_segments[i];
960 mtime_t i_chapter_time;
964 std::vector<input_title_t> titles; // matroska editions
965 size_t i_current_title;
967 std::vector<matroska_stream_c*> streams;
968 std::vector<matroska_segment_c*> opened_segments;
969 std::vector<virtual_segment_c*> used_segments;
970 virtual_segment_c *p_current_segment;
972 /* duration of the stream */
975 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
976 chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
977 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
978 const void *p_cookie,
979 size_t i_cookie_size,
980 virtual_segment_c * & p_segment_found );
981 chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
983 void PreloadFamily( const matroska_segment_c & of_segment );
984 void PreloadLinked( matroska_segment_c *p_segment );
985 bool PreparePlayback( virtual_segment_c *p_new_segment );
986 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
989 virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
990 bool IsUsedSegment( matroska_segment_c &p_segment ) const;
993 static int Demux ( demux_t * );
994 static int Control( demux_t *, int, va_list );
995 static void Seek ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
997 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
999 static char *UTF8ToStr ( const UTFstring &u );
1001 /*****************************************************************************
1002 * Open: initializes matroska demux structures
1003 *****************************************************************************/
1004 static int Open( vlc_object_t * p_this )
1006 demux_t *p_demux = (demux_t*)p_this;
1008 matroska_stream_c *p_stream;
1009 matroska_segment_c *p_segment;
1011 std::string s_path, s_filename;
1012 vlc_stream_io_callback *p_io_callback;
1013 EbmlStream *p_io_stream;
1015 /* peek the begining */
1016 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
1018 /* is a valid file */
1019 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
1020 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
1022 /* Set the demux function */
1023 p_demux->pf_demux = Demux;
1024 p_demux->pf_control = Control;
1025 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
1027 p_io_callback = new vlc_stream_io_callback( p_demux->s );
1028 p_io_stream = new EbmlStream( *p_io_callback );
1030 if( p_io_stream == NULL )
1032 msg_Err( p_demux, "failed to create EbmlStream" );
1033 delete p_io_callback;
1035 return VLC_EGENERIC;
1038 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
1039 if( p_stream == NULL )
1041 msg_Err( p_demux, "cannot find KaxSegment" );
1044 p_sys->streams.push_back( p_stream );
1046 p_stream->p_in = p_io_callback;
1047 p_stream->p_es = p_io_stream;
1049 for (size_t i=0; i<p_stream->segments.size(); i++)
1051 p_stream->segments[i]->Preload();
1054 p_segment = p_stream->segments[0];
1055 if( p_segment->cluster != NULL )
1057 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
1059 // reset the stream reading to the first cluster of the segment used
1060 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
1063 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
1064 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
1066 // assume it's a regular file
1067 // get the directory path
1068 s_path = p_demux->psz_path;
1069 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
1071 s_path = s_path.substr(0,s_path.length()-1);
1075 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
1077 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
1081 struct dirent *p_file_item;
1082 DIR *p_src_dir = opendir(s_path.c_str());
1084 if (p_src_dir != NULL)
1086 while ((p_file_item = (dirent *) readdir(p_src_dir)))
1088 if (strlen(p_file_item->d_name) > 4)
1090 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
1092 if (!s_filename.compare(p_demux->psz_path))
1093 continue; // don't reuse the original opened file
1095 #if defined(__GNUC__) && (__GNUC__ < 3)
1096 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
1097 !s_filename.compare("mka", s_filename.length() - 3, 3))
1099 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
1100 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1103 // test wether this file belongs to the our family
1104 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
1105 EbmlStream *p_estream = new EbmlStream(*p_file_io);
1107 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
1108 if ( p_stream == NULL )
1110 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1116 p_stream->p_in = p_file_io;
1117 p_stream->p_es = p_estream;
1118 p_sys->streams.push_back( p_stream );
1123 closedir( p_src_dir );
1127 p_sys->PreloadFamily( *p_segment );
1128 p_sys->PreloadLinked( p_segment );
1129 if ( !p_sys->PreparePlayback( NULL ) )
1131 msg_Err( p_demux, "cannot use the segment" );
1139 return VLC_EGENERIC;
1142 /*****************************************************************************
1143 * Close: frees unused data
1144 *****************************************************************************/
1145 static void Close( vlc_object_t *p_this )
1147 demux_t *p_demux = (demux_t*)p_this;
1148 demux_sys_t *p_sys = p_demux->p_sys;
1153 /*****************************************************************************
1155 *****************************************************************************/
1156 static int Control( demux_t *p_demux, int i_query, va_list args )
1158 demux_sys_t *p_sys = p_demux->p_sys;
1164 vlc_meta_t **pp_meta;
1168 case DEMUX_GET_META:
1169 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1170 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1173 case DEMUX_GET_LENGTH:
1174 pi64 = (int64_t*)va_arg( args, int64_t * );
1175 if( p_sys->f_duration > 0.0 )
1177 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1180 return VLC_EGENERIC;
1182 case DEMUX_GET_POSITION:
1183 pf = (double*)va_arg( args, double * );
1184 if ( p_sys->f_duration > 0.0 )
1185 *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);
1188 case DEMUX_SET_POSITION:
1189 f = (double)va_arg( args, double );
1190 Seek( p_demux, -1, f, NULL );
1193 case DEMUX_GET_TIME:
1194 pi64 = (int64_t*)va_arg( args, int64_t * );
1195 *pi64 = p_sys->i_pts;
1198 case DEMUX_GET_TITLE_INFO:
1199 if( p_sys->titles.size() )
1201 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1202 int *pi_int = (int*)va_arg( args, int* );
1204 *pi_int = p_sys->titles.size();
1205 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1207 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1209 (*ppp_title)[i] = vlc_input_title_Duplicate( &p_sys->titles[i] );
1214 return VLC_EGENERIC;
1216 case DEMUX_SET_TITLE:
1217 /* TODO handle editions as titles */
1218 i_idx = (int)va_arg( args, int );
1219 if( i_idx < p_sys->used_segments.size() )
1221 p_sys->PreparePlayback( p_sys->used_segments[i_idx] );
1224 return VLC_EGENERIC;
1226 case DEMUX_SET_SEEKPOINT:
1227 i_skp = (int)va_arg( args, int );
1229 if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title].i_seekpoint)
1231 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title].seekpoint[i_skp]->i_time_offset, -1, NULL);
1232 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1233 p_demux->info.i_seekpoint = i_skp;
1236 return VLC_EGENERIC;
1238 case DEMUX_SET_TIME:
1241 return VLC_EGENERIC;
1245 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1257 return VLC_EGENERIC;
1260 i_level = ep->GetLevel();
1262 if( el == NULL && *pp_block != NULL )
1264 /* update the index */
1265 #define idx index[i_index - 1]
1266 if( i_index > 0 && idx.i_time == -1 )
1268 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1269 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1277 if( ep->GetLevel() > 1 )
1282 msg_Warn( &sys.demuxer, "EOF" );
1283 return VLC_EGENERIC;
1289 if( MKV_IS_ID( el, KaxCluster ) )
1291 cluster = (KaxCluster*)el;
1293 /* add it to the index */
1295 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1297 IndexAppendCluster( cluster );
1300 // reset silent tracks
1301 for (size_t i=0; i<tracks.size(); i++)
1303 tracks[i]->b_silent = VLC_FALSE;
1308 else if( MKV_IS_ID( el, KaxCues ) )
1310 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1311 return VLC_EGENERIC;
1315 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1318 else if( i_level == 2 )
1320 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1322 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1324 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1325 cluster->InitTimecode( uint64( ctc ), i_timescale );
1327 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1331 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1336 else if( i_level == 3 )
1338 if( MKV_IS_ID( el, KaxBlock ) )
1340 *pp_block = (KaxBlock*)el;
1342 (*pp_block)->ReadData( es.I_O() );
1343 (*pp_block)->SetParent( *cluster );
1347 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1349 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1351 dur.ReadData( es.I_O() );
1352 *pi_duration = uint64( dur );
1354 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1356 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1358 ref.ReadData( es.I_O() );
1359 if( *pi_ref1 == -1 )
1361 *pi_ref1 = int64( ref );
1365 *pi_ref2 = int64( ref );
1368 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1370 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1371 track_num.ReadData( es.I_O() );
1373 for (size_t i=0; i<tracks.size(); i++)
1375 if ( tracks[i]->i_number == uint32(track_num))
1377 tracks[i]->b_silent = VLC_TRUE;
1385 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1386 return VLC_EGENERIC;
1391 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1394 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1395 memcpy( p_block->p_buffer, p_mem, i_mem );
1396 //p_block->i_rate = p_input->stream.control.i_rate;
1400 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1401 mtime_t i_duration )
1403 demux_sys_t *p_sys = p_demux->p_sys;
1404 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1410 #define tk p_segment->tracks[i_track]
1411 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1413 if( tk->i_number == block->TrackNum() )
1419 if( i_track >= p_segment->tracks.size() )
1421 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1424 if( tk->p_es == NULL )
1426 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1429 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1431 return; /* discard audio packets that shouldn't be rendered */
1434 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1437 tk->b_inited = VLC_FALSE;
1441 /* First send init data */
1442 if( !tk->b_inited && tk->i_data_init > 0 )
1446 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1447 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1448 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1450 tk->b_inited = VLC_TRUE;
1453 for( i = 0; i < block->NumberFrames(); i++ )
1456 DataBuffer &data = block->GetBuffer(i);
1458 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1460 if( p_block == NULL )
1465 #if defined(HAVE_ZLIB_H)
1466 if( tk->i_compression_type )
1468 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1472 // TODO implement correct timestamping when B frames are used
1473 if( tk->fmt.i_cat != VIDEO_ES )
1475 p_block->i_dts = p_block->i_pts = i_pts;
1479 p_block->i_dts = i_pts;
1483 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1485 p_block->i_length = i_duration * 1000;
1488 es_out_Send( p_demux->out, tk->p_es, p_block );
1490 /* use time stamp only for first block */
1497 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1499 int i_upper_lvl = 0;
1501 EbmlElement *p_l0, *p_l1, *p_l2;
1502 bool b_keep_stream = false, b_keep_segment;
1504 // verify the EBML Header
1505 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1510 p_l0->SkipData(*p_estream, EbmlHead_Context);
1513 // find all segments in this file
1514 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1520 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1524 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1527 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1528 b_keep_segment = false;
1530 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1531 p_segment1->ep = ep;
1532 p_segment1->segment = (KaxSegment*)p_l0;
1534 while ((p_l1 = ep->Get()))
1536 if (MKV_IS_ID(p_l1, KaxInfo))
1538 // find the families of this segment
1539 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1541 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1542 for( i = 0; i < p_info->ListSize(); i++ )
1544 EbmlElement *l = (*p_info)[i];
1546 if( MKV_IS_ID( l, KaxSegmentUID ) )
1548 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1549 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1550 if ( !b_keep_segment )
1551 break; // this segment is already known
1552 opened_segments.push_back( p_segment1 );
1553 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1555 else if( MKV_IS_ID( l, KaxPrevUID ) )
1557 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1559 else if( MKV_IS_ID( l, KaxNextUID ) )
1561 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1563 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1565 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1566 p_segment1->families.push_back( *p_fam );
1572 if ( b_keep_segment )
1574 b_keep_stream = true;
1575 p_stream1->segments.push_back( p_segment1 );
1581 p_l0->SkipData(*p_estream, EbmlHead_Context);
1582 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1585 if ( !b_keep_stream )
1594 bool matroska_segment_c::Select( mtime_t i_start_time )
1599 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1600 for( i_track = 0; i_track < tracks.size(); i_track++ )
1602 #define tk tracks[i_track]
1603 if( tk->fmt.i_cat == UNKNOWN_ES )
1605 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1610 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1612 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1614 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1615 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1619 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1621 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1622 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1623 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1625 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1626 if( tk->fmt.i_extra > 0 )
1628 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1629 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1633 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1634 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1636 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1638 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1640 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1642 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1644 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1646 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1647 tk->fmt.b_packetized = VLC_FALSE;
1648 tk->fmt.i_extra = tk->i_extra_data;
1649 tk->fmt.p_extra = malloc( tk->i_extra_data );
1650 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1654 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1657 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1659 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1661 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1665 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1670 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1671 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1672 tk->fmt.i_codec = p_box->i_type;
1673 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1674 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1675 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1676 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1677 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1678 MP4_FreeBox_sample_vide( p_box );
1680 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1682 stream_Delete( p_mp4_stream );
1685 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1687 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1689 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1690 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1694 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1696 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1698 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1699 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1700 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1701 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1702 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1704 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1705 if( tk->fmt.i_extra > 0 )
1707 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1708 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1712 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1713 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1714 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1716 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1718 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1720 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1722 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1724 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1726 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1728 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1729 tk->fmt.i_extra = tk->i_extra_data;
1730 tk->fmt.p_extra = malloc( tk->i_extra_data );
1731 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1733 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1735 int i, i_offset = 1, i_size[3], i_extra;
1738 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1740 /* Split the 3 headers */
1741 if( tk->p_extra_data[0] != 0x02 )
1742 msg_Err( &sys.demuxer, "invalid vorbis header" );
1744 for( i = 0; i < 2; i++ )
1747 while( i_offset < tk->i_extra_data )
1749 i_size[i] += tk->p_extra_data[i_offset];
1750 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1754 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1755 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1756 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1758 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1759 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1760 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1761 for( i = 0; i < 3; i++ )
1763 *(p_extra++) = i_size[i] >> 8;
1764 *(p_extra++) = i_size[i] & 0xFF;
1765 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1767 p_extra += i_size[i];
1768 i_extra += i_size[i];
1771 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1772 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1774 int i_profile, i_srate;
1775 static unsigned int i_sample_rates[] =
1777 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1778 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1781 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1782 /* create data for faad (MP4DecSpecificDescrTag)*/
1784 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1788 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1792 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1801 for( i_srate = 0; i_srate < 13; i_srate++ )
1803 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1808 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1810 tk->fmt.i_extra = 2;
1811 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1812 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1813 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1815 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1816 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1817 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1819 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1821 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1825 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1827 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1829 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1831 /* FIXME: support this codec */
1832 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1833 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1835 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1837 /* FIXME: support this codec */
1838 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1839 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1841 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1843 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1844 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1846 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1847 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1848 !strcmp( tk->psz_codec, "S_SSA" ) ||
1849 !strcmp( tk->psz_codec, "S_ASS" ))
1851 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1852 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1854 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1856 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1857 if( tk->i_extra_data )
1860 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1861 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1862 p_buf[tk->i_extra_data] = '\0';
1864 p_start = strstr( p_buf, "size:" );
1865 if( sscanf( p_start, "size: %dx%d",
1866 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1868 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 );
1872 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1877 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1879 /* FIXME: support this codec */
1880 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1881 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1885 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1886 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1890 tk->fmt.i_priority = 1000;
1893 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1895 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1899 sys.i_start_pts = i_start_time;
1900 // reset the stream reading to the first cluster of the segment used
1901 es.I_O().setFilePointer( i_start_pos );
1904 ep = new EbmlParser( &es, segment, &sys.demuxer );
1909 void matroska_segment_c::UnSelect( )
1913 for( i_track = 0; i_track < tracks.size(); i_track++ )
1915 #define tk tracks[i_track]
1916 if ( tk->p_es != NULL )
1918 es_out_Del( sys.demuxer.out, tk->p_es );
1927 void virtual_segment_c::PrepareChapters( )
1929 if ( linked_segments.size() == 0 )
1932 // !!! should be called only once !!!
1933 matroska_segment_c *p_segment;
1936 // copy editions from the first segment
1937 p_segment = linked_segments[0];
1938 p_editions = &p_segment->stored_editions;
1940 for ( i=1 ; i<linked_segments.size(); i++ )
1942 p_segment = linked_segments[i];
1943 // FIXME assume we have the same editions in all segments
1944 for (j=0; j<p_segment->stored_editions.size(); j++)
1945 (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
1949 std::string chapter_edition_c::GetMainName() const
1951 if ( sub_chapters.size() )
1953 return sub_chapters[0]->GetCodecName( true );
1958 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
1960 // add support for meta-elements from codec like DVD Titles
1961 if ( !b_display_seekpoint || psz_name == "" )
1963 psz_name = GetCodecName();
1964 if ( psz_name != "" )
1965 b_display_seekpoint = true;
1968 if (b_display_seekpoint)
1970 seekpoint_t *sk = vlc_seekpoint_New();
1972 sk->i_level = i_level;
1973 sk->i_time_offset = i_start_time;
1974 sk->psz_name = strdup( psz_name.c_str() );
1976 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1977 title.i_seekpoint++;
1978 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1979 title.seekpoint[title.i_seekpoint-1] = sk;
1981 if ( b_user_display )
1985 for ( size_t i=0; i<sub_chapters.size() ; i++)
1987 sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
1990 i_seekpoint_num = i_user_chapters;
1992 return i_user_chapters;
1995 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1997 demux_sys_t & sys = *demux.p_sys;
1998 chapter_item_c *psz_curr_chapter;
2000 /* update current chapter/seekpoint */
2001 if ( p_editions->size() )
2003 /* 1st, we need to know in which chapter we are */
2004 psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
2006 /* we have moved to a new chapter */
2007 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
2009 if ( (*p_editions)[i_current_edition]->b_ordered )
2011 // Leave/Enter up to the link point
2012 if ( !psz_curr_chapter->EnterAndLeave( psz_current_chapter ) )
2014 // only seek if necessary
2015 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
2016 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
2017 psz_current_chapter = psz_curr_chapter;
2020 else if ( psz_curr_chapter->i_seekpoint_num > 0 )
2022 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
2023 demux.info.i_title = sys.i_current_title = i_sys_title;
2024 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
2025 psz_current_chapter = psz_curr_chapter;
2029 psz_current_chapter = psz_curr_chapter;
2038 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id,
2039 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
2040 const void *p_cookie,
2041 size_t i_cookie_size )
2043 // FIXME don't assume it is the first edition
2044 std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2045 if ( index != p_editions->end() )
2047 chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2048 if ( p_result != NULL )
2054 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
2056 // FIXME don't assume it is the first edition
2057 std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
2058 if ( index != p_editions->end() )
2060 chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
2061 if ( p_result != NULL )
2067 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id,
2068 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
2069 const void *p_cookie,
2070 size_t i_cookie_size )
2073 std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2074 while ( index != codecs.end() )
2076 if ( match( **index ,p_cookie, i_cookie_size ) )
2082 chapter_item_c *p_result = NULL;
2083 std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
2084 while ( index2 != sub_chapters.end() )
2086 p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
2087 if ( p_result != NULL )
2095 void chapter_item_c::Append( const chapter_item_c & chapter )
2097 // we are appending content for the same chapter UID
2099 chapter_item_c *p_chapter;
2101 for ( i=0; i<chapter.sub_chapters.size(); i++ )
2103 p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
2104 if ( p_chapter != NULL )
2106 p_chapter->Append( *chapter.sub_chapters[i] );
2110 sub_chapters.push_back( chapter.sub_chapters[i] );
2114 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
2115 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
2118 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
2121 chapter_item_c *p_result = NULL;
2123 if ( i_uid == i_find_uid )
2126 for ( i=0; i<sub_chapters.size(); i++)
2128 p_result = sub_chapters[i]->FindChapter( i_find_uid );
2129 if ( p_result != NULL )
2135 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
2139 std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2140 while ( index != codecs.end() )
2142 result = (*index)->GetCodecName( f_for_title );
2151 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
2154 if ( m_private_data.GetSize() >= 3)
2156 const binary* p_data = m_private_data.GetBuffer();
2157 /* if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
2159 uint16_t i_title = (p_data[1] << 8) + p_data[2];
2161 sprintf( psz_str, " %d ---", i_title );
2162 result = N_("--- DVD Title");
2165 else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
2168 sprintf( psz_str, " (%c%c) ---", p_data[1], p_data[2] );
2169 result = N_("--- DVD Menu");
2172 else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
2174 if ( p_data[1] == 0x00 )
2175 result = N_("First Played");
2176 else if ( p_data[1] == 0xC0 )
2177 result = N_("Video Manager");
2178 else if ( p_data[1] == 0x80 )
2180 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2182 sprintf( psz_str, " %d -----", i_title );
2183 result = N_("----- Title");
2192 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2194 demux_sys_t *p_sys = p_demux->p_sys;
2195 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
2196 matroska_segment_c *p_segment = p_vsegment->Segment();
2197 mtime_t i_time_offset = 0;
2201 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2202 if( i_date < 0 && f_percent < 0 )
2204 msg_Warn( p_demux, "cannot seek nowhere !" );
2207 if( f_percent > 1.0 )
2209 msg_Warn( p_demux, "cannot seek so far !" );
2213 /* seek without index or without date */
2214 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2216 if (p_sys->f_duration >= 0)
2218 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2222 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2224 msg_Dbg( p_demux, "inacurate way of seeking" );
2225 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2227 if( p_segment->index[i_index].i_position >= i_pos)
2232 if( i_index == p_segment->i_index )
2237 i_date = p_segment->index[i_index].i_time;
2240 if( p_segment->index[i_index].i_position < i_pos )
2244 msg_Warn( p_demux, "searching for cluster, could take some time" );
2246 /* search a cluster */
2247 while( ( el = p_sys->ep->Get() ) != NULL )
2249 if( MKV_IS_ID( el, KaxCluster ) )
2251 KaxCluster *cluster = (KaxCluster*)el;
2253 /* add it to the index */
2254 p_segment->IndexAppendCluster( cluster );
2256 if( (int64_t)cluster->GetElementPosition() >= i_pos )
2258 p_sys->cluster = cluster;
2269 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
2272 /*****************************************************************************
2273 * Demux: reads and demuxes data packets
2274 *****************************************************************************
2275 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2276 *****************************************************************************/
2277 static int Demux( demux_t *p_demux)
2279 demux_sys_t *p_sys = p_demux->p_sys;
2280 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
2281 matroska_segment_c *p_segmet = p_vsegment->Segment();
2282 if ( p_segmet == NULL ) return 0;
2283 int i_block_count = 0;
2286 int64_t i_block_duration;
2287 int64_t i_block_ref1;
2288 int64_t i_block_ref2;
2292 if ( p_sys->demuxer.b_die )
2295 if( p_sys->i_pts >= p_sys->i_start_pts )
2296 if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
2299 if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
2301 /* nothing left to read in this ordered edition */
2302 if ( !p_vsegment->SelectNext() )
2304 p_segmet->UnSelect( );
2306 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2308 /* switch to the next segment */
2309 p_segmet = p_vsegment->Segment();
2310 if ( !p_segmet->Select( 0 ) )
2312 msg_Err( p_demux, "Failed to select new segment" );
2319 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
2321 if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
2323 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
2324 // check if there are more chapters to read
2325 if ( p_chap != NULL )
2327 /* TODO handle successive chapters with the same user_start_time/user_end_time
2328 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
2329 p_vsegment->SelectNext();
2331 p_sys->i_pts = p_chap->i_user_end_time;
2332 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2339 msg_Warn( p_demux, "cannot get block EOF?" );
2340 p_segmet->UnSelect( );
2342 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2344 /* switch to the next segment */
2345 if ( !p_vsegment->SelectNext() )
2346 // no more segments in this stream
2348 p_segmet = p_vsegment->Segment();
2349 if ( !p_segmet->Select( 0 ) )
2351 msg_Err( p_demux, "Failed to select new segment" );
2358 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2360 if( p_sys->i_pts >= p_sys->i_start_pts )
2362 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2365 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2370 // TODO optimize when there is need to leave or when seeking has been called
2371 if( i_block_count > 5 )
2380 /*****************************************************************************
2382 *****************************************************************************/
2383 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2389 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2391 if( i_size <= 0 || mb_eof )
2396 return stream_Read( s, p_buffer, i_size );
2398 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2404 case seek_beginning:
2408 i_pos = stream_Size( s ) - i_offset;
2411 i_pos= stream_Tell( s ) + i_offset;
2415 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2422 if( stream_Seek( s, i_pos ) )
2428 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2432 uint64 vlc_stream_io_callback::getFilePointer( void )
2434 return stream_Tell( s );
2436 void vlc_stream_io_callback::close( void )
2442 /*****************************************************************************
2443 * Ebml Stream parser
2444 *****************************************************************************/
2445 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2452 mi_remain_size[0] = el_start->GetSize();
2454 for( i = 1; i < 6; i++ )
2460 mb_keep = VLC_FALSE;
2461 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2464 EbmlParser::~EbmlParser( void )
2468 for( i = 1; i < mi_level; i++ )
2474 mb_keep = VLC_FALSE;
2478 void EbmlParser::Up( void )
2480 if( mi_user_level == mi_level )
2482 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2488 void EbmlParser::Down( void )
2494 void EbmlParser::Keep( void )
2499 int EbmlParser::GetLevel( void )
2501 return mi_user_level;
2504 void EbmlParser::Reset( demux_t *p_demux )
2506 while ( mi_level > 0)
2508 delete m_el[mi_level];
2509 m_el[mi_level] = NULL;
2512 mi_user_level = mi_level = 1;
2513 #if LIBEBML_VERSION >= 0x000704
2514 // a little faster and cleaner
2515 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2517 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2519 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2522 EbmlElement *EbmlParser::Get( void )
2526 if( mi_user_level != mi_level )
2532 EbmlElement *ret = m_got;
2538 if( m_el[mi_level] )
2540 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2543 delete m_el[mi_level];
2545 mb_keep = VLC_FALSE;
2548 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2549 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2560 delete m_el[mi_level - 1];
2561 m_got = m_el[mi_level -1] = m_el[mi_level];
2562 m_el[mi_level] = NULL;
2569 else if( m_el[mi_level] == NULL )
2571 fprintf( stderr," m_el[mi_level] == NULL\n" );
2574 return m_el[mi_level];
2578 /*****************************************************************************
2580 * * LoadCues : load the cues element and update index
2582 * * LoadTags : load ... the tags element
2584 * * InformationCreate : create all information, load tags if present
2586 *****************************************************************************/
2587 void matroska_segment_c::LoadCues( )
2589 int64_t i_sav_position = es.I_O().getFilePointer();
2591 EbmlElement *el, *cues;
2593 /* *** Load the cue if found *** */
2594 if( i_cues_position < 0 )
2596 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2598 // IndexAppendCluster( cluster );
2601 vlc_bool_t b_seekable;
2603 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2607 msg_Dbg( &sys.demuxer, "loading cues" );
2608 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2609 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2613 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2614 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2618 ep = new EbmlParser( &es, cues, &sys.demuxer );
2619 while( ( el = ep->Get() ) != NULL )
2621 if( MKV_IS_ID( el, KaxCuePoint ) )
2623 #define idx index[i_index]
2626 idx.i_block_number= -1;
2627 idx.i_position = -1;
2629 idx.b_key = VLC_TRUE;
2632 while( ( el = ep->Get() ) != NULL )
2634 if( MKV_IS_ID( el, KaxCueTime ) )
2636 KaxCueTime &ctime = *(KaxCueTime*)el;
2638 ctime.ReadData( es.I_O() );
2640 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2642 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2645 while( ( el = ep->Get() ) != NULL )
2647 if( MKV_IS_ID( el, KaxCueTrack ) )
2649 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2651 ctrack.ReadData( es.I_O() );
2652 idx.i_track = uint16( ctrack );
2654 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2656 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2658 ccpos.ReadData( es.I_O() );
2659 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2661 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2663 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2665 cbnum.ReadData( es.I_O() );
2666 idx.i_block_number = uint32( cbnum );
2670 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2677 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2683 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2684 " track=%d bnum=%d", idx.i_time, idx.i_position,
2685 idx.i_track, idx.i_block_number );
2689 if( i_index >= i_index_max )
2691 i_index_max += 1024;
2692 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2698 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2706 msg_Dbg( &sys.demuxer, "loading cues done." );
2707 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2710 void matroska_segment_c::LoadTags( )
2712 int64_t i_sav_position = es.I_O().getFilePointer();
2714 EbmlElement *el, *tags;
2716 msg_Dbg( &sys.demuxer, "loading tags" );
2717 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2718 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2722 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2723 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2727 msg_Dbg( &sys.demuxer, "Tags" );
2728 ep = new EbmlParser( &es, tags, &sys.demuxer );
2729 while( ( el = ep->Get() ) != NULL )
2731 if( MKV_IS_ID( el, KaxTag ) )
2733 msg_Dbg( &sys.demuxer, "+ Tag" );
2735 while( ( el = ep->Get() ) != NULL )
2737 if( MKV_IS_ID( el, KaxTagTargets ) )
2739 msg_Dbg( &sys.demuxer, "| + Targets" );
2741 while( ( el = ep->Get() ) != NULL )
2743 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2747 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2749 msg_Dbg( &sys.demuxer, "| + General" );
2751 while( ( el = ep->Get() ) != NULL )
2753 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2757 else if( MKV_IS_ID( el, KaxTagGenres ) )
2759 msg_Dbg( &sys.demuxer, "| + Genres" );
2761 while( ( el = ep->Get() ) != NULL )
2763 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2767 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2769 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2771 while( ( el = ep->Get() ) != NULL )
2773 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2777 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2779 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2781 while( ( el = ep->Get() ) != NULL )
2783 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2787 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2789 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2791 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2793 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2795 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2797 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2799 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2801 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2803 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2805 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2807 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2809 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2811 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2813 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2817 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2824 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2830 msg_Dbg( &sys.demuxer, "loading tags done." );
2831 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2834 /*****************************************************************************
2836 *****************************************************************************/
2837 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2841 int i_upper_level = 0;
2843 msg_Dbg( &sys.demuxer, "| + Seek head" );
2845 /* Master elements */
2846 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2848 for( i = 0; i < seekhead->ListSize(); i++ )
2850 EbmlElement *l = (*seekhead)[i];
2852 if( MKV_IS_ID( l, KaxSeek ) )
2854 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2855 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2858 for( j = 0; j < sk->ListSize(); j++ )
2860 EbmlElement *l = (*sk)[j];
2862 if( MKV_IS_ID( l, KaxSeekID ) )
2864 KaxSeekID &sid = *(KaxSeekID*)l;
2865 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2867 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2869 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2870 i_pos = uint64( spos );
2874 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2880 if( id == KaxCues::ClassInfos.GlobalId )
2882 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2883 i_cues_position = segment->GetGlobalPosition( i_pos );
2885 else if( id == KaxChapters::ClassInfos.GlobalId )
2887 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2888 i_chapters_position = segment->GetGlobalPosition( i_pos );
2890 else if( id == KaxTags::ClassInfos.GlobalId )
2892 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2893 i_tags_position = segment->GetGlobalPosition( i_pos );
2899 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2904 /*****************************************************************************
2906 *****************************************************************************/
2907 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2913 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2915 tk = new mkv_track_t();
2916 tracks.push_back( tk );
2918 /* Init the track */
2919 memset( tk, 0, sizeof( mkv_track_t ) );
2921 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2922 tk->fmt.psz_language = strdup("English");
2923 tk->fmt.psz_description = NULL;
2925 tk->b_default = VLC_TRUE;
2926 tk->b_enabled = VLC_TRUE;
2927 tk->b_silent = VLC_FALSE;
2928 tk->i_number = tracks.size() - 1;
2929 tk->i_extra_data = 0;
2930 tk->p_extra_data = NULL;
2931 tk->psz_codec = NULL;
2932 tk->i_default_duration = 0;
2933 tk->f_timecodescale = 1.0;
2935 tk->b_inited = VLC_FALSE;
2936 tk->i_data_init = 0;
2937 tk->p_data_init = NULL;
2939 tk->psz_codec_name = NULL;
2940 tk->psz_codec_settings = NULL;
2941 tk->psz_codec_info_url = NULL;
2942 tk->psz_codec_download_url = NULL;
2944 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2946 for( i = 0; i < m->ListSize(); i++ )
2948 EbmlElement *l = (*m)[i];
2950 if( MKV_IS_ID( l, KaxTrackNumber ) )
2952 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2954 tk->i_number = uint32( tnum );
2955 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2957 else if( MKV_IS_ID( l, KaxTrackUID ) )
2959 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2961 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2963 else if( MKV_IS_ID( l, KaxTrackType ) )
2966 KaxTrackType &ttype = *(KaxTrackType*)l;
2968 switch( uint8(ttype) )
2972 tk->fmt.i_cat = AUDIO_ES;
2976 tk->fmt.i_cat = VIDEO_ES;
2978 case track_subtitle:
2979 psz_type = "subtitle";
2980 tk->fmt.i_cat = SPU_ES;
2983 psz_type = "unknown";
2984 tk->fmt.i_cat = UNKNOWN_ES;
2988 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2990 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2992 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2994 // tk->b_enabled = uint32( fenb );
2995 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2996 // uint32( fenb ) );
2998 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
3000 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
3002 tk->b_default = uint32( fdef );
3003 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
3005 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
3007 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
3009 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
3011 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
3013 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
3015 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
3017 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
3019 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
3021 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
3023 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
3025 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
3027 tk->i_default_duration = uint64(defd);
3028 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
3030 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
3032 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
3034 tk->f_timecodescale = float( ttcs );
3035 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
3037 else if( MKV_IS_ID( l, KaxTrackName ) )
3039 KaxTrackName &tname = *(KaxTrackName*)l;
3041 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
3042 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
3044 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
3046 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
3048 tk->fmt.psz_language = strdup( string( lang ).c_str() );
3049 msg_Dbg( &sys.demuxer,
3050 "| | | + Track Language=`%s'", tk->fmt.psz_language );
3052 else if( MKV_IS_ID( l, KaxCodecID ) )
3054 KaxCodecID &codecid = *(KaxCodecID*)l;
3056 tk->psz_codec = strdup( string( codecid ).c_str() );
3057 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
3059 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
3061 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
3063 tk->i_extra_data = cpriv.GetSize();
3064 if( tk->i_extra_data > 0 )
3066 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
3067 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
3069 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
3071 else if( MKV_IS_ID( l, KaxCodecName ) )
3073 KaxCodecName &cname = *(KaxCodecName*)l;
3075 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
3076 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
3078 else if( MKV_IS_ID( l, KaxContentEncodings ) )
3080 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
3081 MkvTree( sys.demuxer, 3, "Content Encodings" );
3082 for( j = 0; j < cencs->ListSize(); j++ )
3084 EbmlElement *l2 = (*cencs)[j];
3085 if( MKV_IS_ID( l2, KaxContentEncoding ) )
3087 MkvTree( sys.demuxer, 4, "Content Encoding" );
3088 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
3089 for( k = 0; k < cenc->ListSize(); k++ )
3091 EbmlElement *l3 = (*cenc)[k];
3092 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
3094 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
3095 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
3097 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
3099 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
3100 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
3102 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
3104 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
3105 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
3107 else if( MKV_IS_ID( l3, KaxContentCompression ) )
3109 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
3110 MkvTree( sys.demuxer, 5, "Content Compression" );
3111 for( n = 0; n < compr->ListSize(); n++ )
3113 EbmlElement *l4 = (*compr)[n];
3114 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
3116 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
3117 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
3118 if( uint32( compalg ) == 0 )
3120 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
3125 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
3132 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
3139 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
3144 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
3146 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
3148 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
3149 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
3151 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
3153 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
3155 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3156 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
3158 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3160 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3162 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3163 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
3165 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3167 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3169 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3171 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3173 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3175 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3177 else if( MKV_IS_ID( l, KaxTrackVideo ) )
3179 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3182 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
3185 for( j = 0; j < tkv->ListSize(); j++ )
3187 EbmlElement *l = (*tkv)[j];
3188 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3190 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3192 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
3194 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3196 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3198 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
3201 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3203 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3205 tk->fmt.video.i_width = uint16( vwidth );
3206 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
3208 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3210 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3212 tk->fmt.video.i_height = uint16( vheight );
3213 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
3215 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3217 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3219 tk->fmt.video.i_visible_width = uint16( vwidth );
3220 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
3222 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
3224 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
3226 tk->fmt.video.i_visible_height = uint16( vheight );
3227 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
3229 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
3231 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
3233 tk->f_fps = float( vfps );
3234 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
3236 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
3238 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
3240 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
3241 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
3243 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
3245 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
3247 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
3249 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
3251 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
3253 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
3257 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
3260 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
3261 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
3263 else if( MKV_IS_ID( l, KaxTrackAudio ) )
3265 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
3268 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
3270 for( j = 0; j < tka->ListSize(); j++ )
3272 EbmlElement *l = (*tka)[j];
3274 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
3276 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
3278 tk->fmt.audio.i_rate = (int)float( afreq );
3279 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
3281 else if( MKV_IS_ID( l, KaxAudioChannels ) )
3283 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
3285 tk->fmt.audio.i_channels = uint8( achan );
3286 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
3288 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
3290 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
3292 tk->fmt.audio.i_bitspersample = uint8( abits );
3293 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
3297 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
3303 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
3304 typeid(*l).name() );
3309 /*****************************************************************************
3311 *****************************************************************************/
3312 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
3316 int i_upper_level = 0;
3318 msg_Dbg( &sys.demuxer, "| + Tracks" );
3320 /* Master elements */
3321 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
3323 for( i = 0; i < tracks->ListSize(); i++ )
3325 EbmlElement *l = (*tracks)[i];
3327 if( MKV_IS_ID( l, KaxTrackEntry ) )
3329 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
3333 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3338 /*****************************************************************************
3340 *****************************************************************************/
3341 void matroska_segment_c::ParseInfo( KaxInfo *info )
3346 int i_upper_level = 0;
3348 msg_Dbg( &sys.demuxer, "| + Information" );
3350 /* Master elements */
3351 m = static_cast<EbmlMaster *>(info);
3352 m->Read( es, info->Generic().Context, i_upper_level, el, true );
3354 for( i = 0; i < m->ListSize(); i++ )
3356 EbmlElement *l = (*m)[i];
3358 if( MKV_IS_ID( l, KaxSegmentUID ) )
3360 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3362 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3364 else if( MKV_IS_ID( l, KaxPrevUID ) )
3366 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3368 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3370 else if( MKV_IS_ID( l, KaxNextUID ) )
3372 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3374 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3376 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3378 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3380 i_timescale = uint64(tcs);
3382 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3385 else if( MKV_IS_ID( l, KaxDuration ) )
3387 KaxDuration &dur = *(KaxDuration*)l;
3389 i_duration = mtime_t( double( dur ) );
3391 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3394 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3396 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3398 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3400 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3401 psz_muxing_application );
3403 else if( MKV_IS_ID( l, KaxWritingApp ) )
3405 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3407 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3409 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3410 psz_writing_application );
3412 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3414 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3416 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3418 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3419 psz_segment_filename );
3421 else if( MKV_IS_ID( l, KaxTitle ) )
3423 KaxTitle &title = *(KaxTitle*)l;
3425 psz_title = UTF8ToStr( UTFstring( title ) );
3427 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3429 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3431 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3433 families.push_back(*uid);
3435 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3437 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3438 else if( MKV_IS_ID( l, KaxDateUTC ) )
3440 KaxDateUTC &date = *(KaxDateUTC*)l;
3445 i_date = date.GetEpochDate();
3446 memset( buffer, 0, 256 );
3447 if( gmtime_r( &i_date, &tmres ) &&
3448 asctime_r( &tmres, buffer ) )
3450 buffer[strlen( buffer)-1]= '\0';
3451 psz_date_utc = strdup( buffer );
3452 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3456 #if LIBMATROSKA_VERSION >= 0x000704
3457 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3459 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3460 chapter_translation_c translated;
3462 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3463 for( j = 0; j < p_trans->ListSize(); j++ )
3465 EbmlElement *l = (*p_trans)[j];
3467 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3469 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3471 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3473 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3475 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3477 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3481 translations.push_back( translated );
3486 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3490 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3491 i_duration = mtime_t(f_dur);
3495 /*****************************************************************************
3497 *****************************************************************************/
3498 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3502 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3503 for( i = 0; i < ca->ListSize(); i++ )
3505 EbmlElement *l = (*ca)[i];
3507 if( MKV_IS_ID( l, KaxChapterUID ) )
3509 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3510 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3512 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3514 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3515 chapters.b_display_seekpoint = uint8( flag ) == 0;
3517 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3519 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3521 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3522 chapters.i_start_time = uint64( start ) / I64C(1000);
3524 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3526 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3528 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3529 chapters.i_end_time = uint64( end ) / I64C(1000);
3531 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3533 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3535 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3537 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3538 for( j = 0; j < cd->ListSize(); j++ )
3540 EbmlElement *l= (*cd)[j];
3542 if( MKV_IS_ID( l, KaxChapterString ) )
3546 KaxChapterString &name =*(KaxChapterString*)l;
3547 for (k = 0; k < i_level; k++)
3548 chapters.psz_name += '+';
3549 chapters.psz_name += ' ';
3550 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3551 chapters.b_user_display = true;
3553 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3555 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3557 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3558 const char *psz = string( lang ).c_str();
3560 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3562 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3564 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3565 const char *psz = string( ct ).c_str();
3567 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3571 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3573 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3575 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3576 chapter_codec_cmds_c *p_ccodec = NULL;
3578 for( j = 0; j < cp->ListSize(); j++ )
3580 EbmlElement *k= (*cp)[j];
3582 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3584 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3585 if ( uint32(*p_codec_id) == 0 )
3586 p_ccodec = new matroska_script_codec_c( sys );
3587 else if ( uint32(*p_codec_id) == 1 )
3588 p_ccodec = new dvd_chapter_codec_c( sys );
3593 if ( p_ccodec != NULL )
3595 for( j = 0; j < cp->ListSize(); j++ )
3597 EbmlElement *k= (*cp)[j];
3599 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3601 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3602 p_ccodec->SetPrivate( *p_private );
3604 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3606 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3609 chapters.codecs.push_back( p_ccodec );
3612 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3614 chapter_item_c *new_sub_chapter = new chapter_item_c();
3615 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3616 new_sub_chapter->psz_parent = &chapters;
3617 chapters.sub_chapters.push_back( new_sub_chapter );
3622 /*****************************************************************************
3624 *****************************************************************************/
3625 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3629 int i_upper_level = 0;
3632 /* Master elements */
3633 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3635 for( i = 0; i < chapters->ListSize(); i++ )
3637 EbmlElement *l = (*chapters)[i];
3639 if( MKV_IS_ID( l, KaxEditionEntry ) )
3641 chapter_edition_c *p_edition = new chapter_edition_c();
3643 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3645 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3646 for( j = 0; j < E->ListSize(); j++ )
3648 EbmlElement *l = (*E)[j];
3650 if( MKV_IS_ID( l, KaxChapterAtom ) )
3652 chapter_item_c *new_sub_chapter = new chapter_item_c();
3653 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3654 p_edition->sub_chapters.push_back( new_sub_chapter );
3656 else if( MKV_IS_ID( l, KaxEditionUID ) )
3658 p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3660 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3662 p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3664 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3666 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3667 i_default_edition = stored_editions.size();
3671 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3674 stored_editions.push_back( p_edition );
3678 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3682 for( i = 0; i < stored_editions.size(); i++ )
3684 stored_editions[i]->RefreshChapters( );
3687 if ( stored_editions[i_default_edition]->b_ordered )
3689 /* update the duration of the segment according to the sum of all sub chapters */
3690 i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3696 void matroska_segment_c::ParseCluster( )
3701 int i_upper_level = 0;
3703 /* Master elements */
3704 m = static_cast<EbmlMaster *>( cluster );
3705 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3707 for( i = 0; i < m->ListSize(); i++ )
3709 EbmlElement *l = (*m)[i];
3711 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3713 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3715 cluster->InitTimecode( uint64( ctc ), i_timescale );
3720 i_start_time = cluster->GlobalTimecode() / 1000;
3723 /*****************************************************************************
3724 * InformationCreate:
3725 *****************************************************************************/
3726 void matroska_segment_c::InformationCreate( )
3730 sys.meta = vlc_meta_New();
3734 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3738 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3740 if( psz_segment_filename )
3742 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3744 if( psz_muxing_application )
3746 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3748 if( psz_writing_application )
3750 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3753 for( i_track = 0; i_track < tracks.size(); i_track++ )
3755 mkv_track_t *tk = tracks[i_track];
3756 vlc_meta_t *mtk = vlc_meta_New();
3758 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3759 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3760 sys.meta->track[sys.meta->i_track++] = mtk;
3762 if( tk->fmt.psz_description )
3764 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3766 if( tk->psz_codec_name )
3768 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3770 if( tk->psz_codec_settings )
3772 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3774 if( tk->psz_codec_info_url )
3776 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3778 if( tk->psz_codec_download_url )
3780 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3784 if( i_tags_position >= 0 )
3786 vlc_bool_t b_seekable;
3788 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3797 /*****************************************************************************
3799 *****************************************************************************/
3801 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3803 #define idx index[i_index]
3805 idx.i_block_number= -1;
3806 idx.i_position = cluster->GetElementPosition();
3808 idx.b_key = VLC_TRUE;
3811 if( i_index >= i_index_max )
3813 i_index_max += 1024;
3814 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3819 static char * UTF8ToStr( const UTFstring &u )
3828 p = dst = (char*)malloc( i_src + 1);
3847 void chapter_edition_c::RefreshChapters( )
3849 chapter_item_c::RefreshChapters( b_ordered, -1 );
3850 b_display_seekpoint = false;
3853 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3855 int64_t i_user_time = i_prev_user_time;
3857 // first the sub-chapters, and then ourself
3858 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3859 while ( index != sub_chapters.end() )
3861 i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3867 // the ordered chapters always start at zero
3868 if ( i_prev_user_time == -1 )
3870 if ( i_user_time == -1 )
3872 i_prev_user_time = 0;
3875 i_user_start_time = i_prev_user_time;
3876 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3878 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3882 i_user_end_time = i_user_time;
3887 std::sort( sub_chapters.begin(), sub_chapters.end() );
3888 i_user_start_time = i_start_time;
3889 if ( i_end_time != -1 )
3890 i_user_end_time = i_end_time;
3891 else if ( i_user_time != -1 )
3892 i_user_end_time = i_user_time;
3894 i_user_end_time = i_user_start_time;
3897 return i_user_end_time;
3900 mtime_t chapter_edition_c::Duration() const
3902 mtime_t i_result = 0;
3904 if ( sub_chapters.size() )
3906 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3908 i_result = (*index)->i_user_end_time;
3914 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3916 chapter_item_c *psz_result = NULL;
3918 if ( i_user_timecode >= i_user_start_time &&
3919 ( i_user_timecode < i_user_end_time ||
3920 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3922 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3923 while ( index != sub_chapters.end() && psz_result == NULL )
3925 psz_result = (*index)->FindTimecode( i_user_timecode );
3929 if ( psz_result == NULL )
3936 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
3938 if ( &item == this )
3941 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
3942 while ( index != sub_chapters.end() )
3944 if ( (*index)->ParentOf( item ) )
3952 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3954 for (size_t i=0; i<opened_segments.size(); i++)
3956 opened_segments[i]->PreloadFamily( of_segment );
3959 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3964 for (size_t i=0; i<families.size(); i++)
3966 for (size_t j=0; j<of_segment.families.size(); j++)
3968 if ( families[i] == of_segment.families[j] )
3976 // preload all the linked segments for all preloaded segments
3977 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3979 size_t i_preloaded, i, j;
3980 virtual_segment_c *p_seg;
3982 p_current_segment = VirtualFromSegments( p_segment );
3984 used_segments.push_back( p_current_segment );
3986 // create all the other virtual segments of the family
3989 for ( i=0; i< opened_segments.size(); i++ )
3991 if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
3993 p_seg = VirtualFromSegments( opened_segments[i] );
3994 used_segments.push_back( p_seg );
3998 } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
4000 // publish all editions of all usable segment
4001 for ( i=0; i< used_segments.size(); i++ )
4003 p_seg = used_segments[i];
4004 if ( p_seg->p_editions != NULL )
4006 std::string sz_name;
4007 input_title_t *p_title = vlc_input_title_New();
4008 p_seg->i_sys_title = i;
4011 // TODO use a name for each edition, let the TITLE deal with a codec name
4012 for ( j=0; j<p_seg->p_editions->size(); j++ )
4014 if ( p_title->psz_name == NULL )
4016 sz_name = (*p_seg->p_editions)[j]->GetMainName();
4017 if ( sz_name != "" )
4018 p_title->psz_name = strdup( sz_name.c_str() );
4021 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
4024 p_edition->PublishChapters( *p_title, i_chapters, 0 );
4027 // create a name if there is none
4028 if ( p_title->psz_name == NULL )
4030 sz_name = N_("Segment ");
4032 sprintf( psz_str, "%d", i );
4034 p_title->psz_name = strdup( sz_name.c_str() );
4037 titles.push_back( *p_title );
4042 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
4044 for ( size_t i=0; i< used_segments.size(); i++ )
4046 if ( used_segments[i]->FindUID( segment.segment_uid ) )
4052 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
4054 size_t i_preloaded, i;
4056 virtual_segment_c *p_result = new virtual_segment_c( p_segment );
4058 // fill our current virtual segment with all hard linked segments
4061 for ( i=0; i< opened_segments.size(); i++ )
4063 i_preloaded += p_result->AddSegment( opened_segments[i] );
4065 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
4069 p_result->PreloadLinked( );
4071 p_result->PrepareChapters( );
4076 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
4078 if ( p_new_segment != NULL && p_new_segment != p_current_segment )
4080 if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
4081 p_current_segment->Segment()->UnSelect();
4083 p_current_segment = p_new_segment;
4084 i_current_title = p_new_segment->i_sys_title;
4087 p_current_segment->LoadCues();
4088 f_duration = p_current_segment->Duration();
4090 /* add information */
4091 p_current_segment->Segment()->InformationCreate( );
4093 p_current_segment->Segment()->Select( 0 );
4098 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
4100 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
4101 if ( *p_itema == p_item_b->prev_segment_uid )
4104 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
4105 if ( *p_itema == p_item_b->segment_uid )
4108 if ( *p_itema == p_item_b->prev_segment_uid )
4114 bool matroska_segment_c::Preload( )
4119 EbmlElement *el = NULL;
4121 ep->Reset( &sys.demuxer );
4123 while( ( el = ep->Get() ) != NULL )
4125 if( MKV_IS_ID( el, KaxInfo ) )
4127 ParseInfo( static_cast<KaxInfo*>( el ) );
4129 else if( MKV_IS_ID( el, KaxTracks ) )
4131 ParseTracks( static_cast<KaxTracks*>( el ) );
4133 else if( MKV_IS_ID( el, KaxSeekHead ) )
4135 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
4137 else if( MKV_IS_ID( el, KaxCues ) )
4139 msg_Dbg( &sys.demuxer, "| + Cues" );
4141 else if( MKV_IS_ID( el, KaxCluster ) )
4143 msg_Dbg( &sys.demuxer, "| + Cluster" );
4145 cluster = (KaxCluster*)el;
4147 i_start_pos = cluster->GetElementPosition();
4151 /* stop parsing the stream */
4154 else if( MKV_IS_ID( el, KaxAttachments ) )
4156 msg_Dbg( &sys.demuxer, "| + Attachments FIXME (but probably never supported)" );
4158 else if( MKV_IS_ID( el, KaxChapters ) )
4160 msg_Dbg( &sys.demuxer, "| + Chapters" );
4161 ParseChapters( static_cast<KaxChapters*>( el ) );
4163 else if( MKV_IS_ID( el, KaxTag ) )
4165 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
4169 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
4178 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4180 for (size_t i=0; i<opened_segments.size(); i++)
4182 if ( opened_segments[i]->segment_uid == uid )
4183 return opened_segments[i];
4188 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id,
4189 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
4190 const void *p_cookie,
4191 size_t i_cookie_size,
4192 virtual_segment_c * &p_segment_found )
4194 chapter_item_c *p_result = NULL;
4195 for (size_t i=0; i<used_segments.size(); i++)
4197 p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4198 if ( p_result != NULL )
4200 p_segment_found = used_segments[i];
4207 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
4209 chapter_item_c *p_result = NULL;
4210 for (size_t i=0; i<used_segments.size(); i++)
4212 p_result = used_segments[i]->FindChapter( i_find_uid );
4213 if ( p_result != NULL )
4215 p_segment_found = used_segments[i];
4222 void virtual_segment_c::Sort()
4224 // keep the current segment index
4225 matroska_segment_c *p_segment = linked_segments[i_current_segment];
4227 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
4229 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
4230 if ( linked_segments[i_current_segment] == p_segment )
4234 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
4237 // check if it's not already in here
4238 for ( i=0; i<linked_segments.size(); i++ )
4240 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
4244 // find possible mates
4245 for ( i=0; i<linked_uids.size(); i++ )
4247 if ( p_segment->segment_uid == linked_uids[i]
4248 || p_segment->prev_segment_uid == linked_uids[i]
4249 || p_segment->next_segment_uid == linked_uids[i] )
4251 linked_segments.push_back( p_segment );
4253 AppendUID( p_segment->prev_segment_uid );
4254 AppendUID( p_segment->next_segment_uid );
4262 void virtual_segment_c::PreloadLinked( )
4264 for ( size_t i=0; i<linked_segments.size(); i++ )
4266 linked_segments[i]->Preload( );
4268 i_current_edition = linked_segments[0]->i_default_edition;
4271 mtime_t virtual_segment_c::Duration() const
4274 if ( linked_segments.size() == 0 )
4277 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
4278 // p_last_segment->ParseCluster( );
4280 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
4285 void virtual_segment_c::LoadCues( )
4287 for ( size_t i=0; i<linked_segments.size(); i++ )
4289 linked_segments[i]->LoadCues();
4293 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
4295 if ( UID.GetBuffer() == NULL )
4298 for (size_t i=0; i<linked_uids.size(); i++)
4300 if ( UID == linked_uids[i] )
4303 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
4306 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
4309 int i_track_skipping;
4310 int64_t i_block_duration;
4311 int64_t i_block_ref1;
4312 int64_t i_block_ref2;
4314 int64_t i_seek_position = i_start_pos;
4315 int64_t i_seek_time = i_start_time;
4321 for( ; i_idx < i_index; i_idx++ )
4323 if( index[i_idx].i_time + i_time_offset > i_date )
4334 i_seek_position = index[i_idx].i_position;
4335 i_seek_time = index[i_idx].i_time;
4338 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
4339 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
4341 es.I_O().setFilePointer( i_seek_position, seek_beginning );
4344 ep = new EbmlParser( &es, segment, &sys.demuxer );
4347 sys.i_start_pts = i_date;
4349 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
4351 /* now parse until key frame */
4352 #define tk tracks[i_track]
4353 i_track_skipping = 0;
4354 for( i_track = 0; i_track < tracks.size(); i_track++ )
4356 if( tk->fmt.i_cat == VIDEO_ES )
4358 tk->b_search_keyframe = VLC_TRUE;
4361 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
4365 while( i_track_skipping > 0 )
4367 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
4369 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
4374 for( i_track = 0; i_track < tracks.size(); i_track++ )
4376 if( tk->i_number == block->TrackNum() )
4382 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
4384 if( i_track < tracks.size() )
4386 if( sys.i_pts >= sys.i_start_pts )
4388 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4389 i_track_skipping = 0;
4391 else if( tk->fmt.i_cat == VIDEO_ES )
4393 if( i_block_ref1 == -1 && tk->b_search_keyframe )
4395 tk->b_search_keyframe = VLC_FALSE;
4398 if( !tk->b_search_keyframe )
4400 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4410 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
4412 demux_sys_t *p_sys = demuxer.p_sys;
4415 // find the actual time for an ordered edition
4416 if ( psz_chapter == NULL )
4418 if ( Edition() && Edition()->b_ordered )
4420 /* 1st, we need to know in which chapter we are */
4421 psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
4425 if ( psz_chapter != NULL )
4427 psz_current_chapter = psz_chapter;
4428 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
4429 if ( psz_chapter->i_seekpoint_num > 0 )
4431 demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
4432 demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
4433 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
4437 // find the best matching segment
4438 for ( i=0; i<linked_segments.size(); i++ )
4440 if ( i_date < linked_segments[i]->i_start_time )
4447 if ( i_current_segment != i )
4449 linked_segments[i_current_segment]->UnSelect();
4450 linked_segments[i]->Select( i_date );
4451 i_current_segment = i;
4454 linked_segments[i]->Seek( i_date, i_time_offset );
4457 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
4461 uint32 codec_time = uint32(-1);
4462 for( i = 0; i < command.ListSize(); i++ )
4464 const EbmlElement *k = command[i];
4466 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
4468 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
4473 for( i = 0; i < command.ListSize(); i++ )
4475 const EbmlElement *k = command[i];
4477 if( MKV_IS_ID( k, KaxChapterProcessData ) )
4479 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4480 switch ( codec_time )
4483 during_cmds.push_back( *p_data );
4486 enter_cmds.push_back( *p_data );
4489 leave_cmds.push_back( *p_data );
4498 bool chapter_item_c::Enter( bool b_do_subs )
4500 bool f_result = false;
4501 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4502 while ( index != codecs.end() )
4504 f_result |= (*index)->Enter();
4511 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4512 while ( index_ != sub_chapters.end() )
4514 f_result |= (*index_)->Enter( true );
4521 bool chapter_item_c::Leave( bool b_do_subs )
4523 bool f_result = false;
4524 b_is_leaving = true;
4525 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4526 while ( index != codecs.end() )
4528 f_result |= (*index)->Leave();
4535 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4536 while ( index_ != sub_chapters.end() )
4538 f_result |= (*index_)->Leave( true );
4542 b_is_leaving = false;
4546 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item )
4548 chapter_item_c *p_common_parent = p_item;
4550 // leave, up to a common parent
4551 while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
4553 if ( !p_common_parent->b_is_leaving && p_common_parent->Leave( false ) )
4555 p_common_parent = p_common_parent->psz_parent;
4558 // enter from the parent to <this>
4559 if ( p_common_parent != NULL )
4563 for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
4565 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
4567 p_common_parent = p_common_parent->sub_chapters[i];
4572 if ( p_common_parent == this )
4575 if ( p_common_parent->Enter( false ) )
4580 return Enter( true );
4583 bool dvd_chapter_codec_c::Enter()
4585 bool f_result = false;
4586 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4587 while ( index != enter_cmds.end() )
4589 if ( (*index).GetSize() )
4591 binary *p_data = (*index).GetBuffer();
4592 size_t i_size = *p_data++;
4593 // avoid reading too much from the buffer
4594 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4595 for ( ; i_size > 0; i_size--, p_data += 8 )
4597 msg_Dbg( &sys.demuxer, "Matroska DVD enter command" );
4598 f_result |= interpretor.Interpret( p_data );
4606 bool dvd_chapter_codec_c::Leave()
4608 bool f_result = false;
4609 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4610 while ( index != leave_cmds.end() )
4612 if ( (*index).GetSize() )
4614 binary *p_data = (*index).GetBuffer();
4615 size_t i_size = *p_data++;
4616 // avoid reading too much from the buffer
4617 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4618 for ( ; i_size > 0; i_size--, p_data += 8 )
4620 msg_Dbg( &sys.demuxer, "Matroska DVD leave command" );
4621 f_result |= interpretor.Interpret( p_data );
4629 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
4630 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4635 virtual_segment_c *p_segment;
4636 chapter_item_c *p_chapter;
4637 bool f_result = false;
4638 uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4640 // handle register tests if there are some
4641 if ( (i_command & 0xF0) != 0 )
4643 bool b_test_positive = (i_command & CMD_DVD_IF_NOT) == 0;
4644 bool b_test_value = (i_command & CMD_DVD_TEST_VALUE) != 0;
4645 uint8 i_test = i_command & 0x70;
4649 i_value = ( p_command[4] << 8 ) + p_command[5];
4651 i_value = GetPRM( p_command[7] );
4655 case CMD_DVD_IF_GPREG_EQUAL:
4657 msg_Dbg( &sys.demuxer, "IF %s EQUALS %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4658 if (!( GetPRM( p_command[3] ) == i_value ))
4660 b_test_positive = !b_test_positive;
4663 case CMD_DVD_IF_GPREG_INF:
4665 msg_Dbg( &sys.demuxer, "IF %s < %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4666 if (!( GetPRM( p_command[3] ) < i_value ))
4668 b_test_positive = !b_test_positive;
4671 case CMD_DVD_IF_GPREG_AND:
4673 msg_Dbg( &sys.demuxer, "IF %s & %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4674 if (!( GetPRM( p_command[3] ) & i_value ))
4676 b_test_positive = !b_test_positive;
4679 case CMD_DVD_IF_GPREG_SUP_EQUAL:
4680 // if superior or equal
4681 msg_Dbg( &sys.demuxer, "IF %s >= %s", GetRegTypeName( false, p_command[3] ).c_str(), GetRegTypeName( b_test_value, i_value ).c_str() );
4682 if (!( GetPRM( p_command[3] ) >= i_value ))
4684 b_test_positive = !b_test_positive;
4689 if ( !b_test_positive )
4693 // strip the test command
4694 i_command &= 0xFF0F;
4696 switch ( i_command )
4701 msg_Dbg( &sys.demuxer, "NOP" );
4706 msg_Dbg( &sys.demuxer, "Break" );
4710 case CMD_DVD_JUMP_TT:
4712 uint8 i_title = p_command[5];
4713 msg_Dbg( &sys.demuxer, "JumpTT %d", i_title );
4715 // find in the ChapProcessPrivate matching this Title level
4716 p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
4717 if ( p_chapter != NULL )
4719 // if the segment is not part of the current segment, select the new one
4720 if ( p_segment != sys.p_current_segment )
4722 sys.PreparePlayback( p_segment );
4725 // jump to the location in the found segment
4726 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, NULL );
4727 p_chapter->Enter( true );
4734 case CMD_DVD_CALLSS_VTSM1:
4736 msg_Dbg( &sys.demuxer, "CallSS VTSM" );
4737 switch( (p_command[6] & 0xC0) >> 6 ) {
4739 switch ( p_command[5] )
4742 msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[5]);
4745 msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[5]);
4748 msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[5]);
4751 msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[5]);
4754 msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[5]);
4757 msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[5]);
4760 msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[5]);
4763 msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[5]);
4766 p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_command[5], 1, p_segment );
4767 if ( p_chapter != NULL )
4769 // if the segment is not part of the current segment, select the new one
4770 if ( p_segment != sys.p_current_segment )
4772 sys.PreparePlayback( p_segment );
4775 p_chapter->Enter( true );
4777 // jump to the location in the found segment
4778 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
4783 msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4786 msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4789 msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[3] << 8) + p_command[4], p_command[5]);
4794 case CMD_DVD_SET_GPRMMD:
4796 msg_Dbg( &sys.demuxer, "Set GPRMMD [%d]=%d", (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3]);
4798 if ( !SetGPRM( (p_command[4] << 8) + p_command[5], (p_command[2] << 8) + p_command[3] ) )
4799 msg_Dbg( &sys.demuxer, "Set GPRMMD failed" );
4802 case CMD_DVD_LINKPGCN:
4804 uint16 i_pgcn = (p_command[6] << 8) + p_command[7];
4806 msg_Dbg( &sys.demuxer, "Link PGCN(%d)", i_pgcn );
4810 case CMD_DVD_LINKCN:
4812 msg_Dbg( &sys.demuxer, "LinkCN (cell %d)", (p_command[6] << 8) + p_command[7] );
4817 case CMD_DVD_GOTO_LINE:
4819 msg_Dbg( &sys.demuxer, "GotoLine (%d)", (p_command[6] << 8) + p_command[7] );
4825 msg_Dbg( &sys.demuxer, "unsupported command : %02X %02X %02X %02X %02X %02X %02X %02X"
4841 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4843 if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
4846 if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
4849 uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
4850 uint8 i_title = *(uint8*)p_cookie;
4852 return (i_gtitle == i_title);
4855 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4857 if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 7 )
4860 if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
4863 uint8 i_pgc_type = data.m_private_data.GetBuffer()[3];
4864 uint8 i_pgc = *(uint8*)p_cookie;
4866 return (i_pgc_type == i_pgc);
4869 bool matroska_script_codec_c::Enter()
4871 bool f_result = false;
4872 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4873 while ( index != enter_cmds.end() )
4875 if ( (*index).GetSize() )
4877 msg_Dbg( &sys.demuxer, "Matroska Script enter command" );
4878 f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4885 bool matroska_script_codec_c::Leave()
4887 bool f_result = false;
4888 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4889 while ( index != leave_cmds.end() )
4891 if ( (*index).GetSize() )
4893 msg_Dbg( &sys.demuxer, "Matroska Script leave command" );
4894 f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4901 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript
4902 // for a description of existing commands
4903 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4905 bool b_result = false;
4907 char *psz_str = (char*) malloc( i_size + 1 );
4908 memcpy( psz_str, p_command, i_size );
4909 psz_str[ i_size ] = '\0';
4911 std::string sz_command = psz_str;
4914 msg_Dbg( &sys.demuxer, "command : %s", sz_command.c_str() );
4916 if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
4921 for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
4923 if ( sz_command[i] == '(' )
4930 for ( j=i; j<sz_command.size(); j++)
4932 if ( sz_command[j] == ')' )
4939 std::string st = sz_command.substr( i+1, j-i-1 );
4940 int64_t i_chapter_uid = atoi( st.c_str() );
4942 virtual_segment_c *p_segment;
4943 chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
4945 if ( p_chapter == NULL )
4946 msg_Dbg( &sys.demuxer, "Chapter "I64Fd" not found", i_chapter_uid);
4949 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );