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( int codec_id = -1)
347 :i_codec_id( codec_id )
350 virtual ~chapter_codec_cmds_c() {}
352 void SetPrivate( const KaxChapterProcessPrivate & private_data )
354 m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
357 void AddCommand( const KaxChapterProcessCommand & command );
359 /// \return wether the codec has seeked in the files or not
360 virtual bool Enter() { return false; }
361 virtual bool Leave() { return false; }
362 virtual std::string GetCodecName( bool f_for_title = false ) const { return ""; }
364 KaxChapterProcessPrivate m_private_data;
367 std::vector<KaxChapterProcessData> enter_cmds;
368 std::vector<KaxChapterProcessData> during_cmds;
369 std::vector<KaxChapterProcessData> leave_cmds;
374 class dvd_command_interpretor_c
377 dvd_command_interpretor_c( demux_sys_t & demuxer )
380 memset( p_GPRM, 0, sizeof(p_GPRM) );
381 memset( p_SPRM, 0, sizeof(p_SPRM) );
388 p_SPRM[ 16 ] = 0xFFFFu;
389 p_SPRM[ 18 ] = 0xFFFFu;
392 bool Interpret( const binary * p_command, size_t i_size = 8 );
395 uint16 GetGPRM( size_t index ) const
397 if ( index >= 0 && index < 16 )
398 return p_GPRM[ index ];
402 uint16 GetSPRM( size_t index ) const
404 // 21,22,23 reserved for future use
405 if ( index >= 0 && index < 21 )
406 return p_SPRM[ index ];
410 bool SetGPRM( size_t index, uint16 value )
412 if ( index >= 0 && index < 16 )
414 p_GPRM[ index ] = value;
420 bool SetSPRM( size_t index, uint16 value )
422 if ( index > 0 && index <= 13 && index != 12 )
424 p_SPRM[ index ] = value;
435 static const uint16 CMD_JUMP_TT = 0x3002;
436 static const uint16 CMD_CALLSS_VTSM = 0x3008;
438 // callbacks when browsing inside CodecPrivate
439 static bool MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
440 static bool MatchPgcType ( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size );
443 class dvd_chapter_codec_c : public chapter_codec_cmds_c
446 dvd_chapter_codec_c( demux_sys_t & sys )
447 :chapter_codec_cmds_c( 1 )
453 std::string GetCodecName( bool f_for_title = false ) const;
456 dvd_command_interpretor_c interpretor;
459 class matroska_script_interpretor_c
462 matroska_script_interpretor_c( demux_sys_t & demuxer )
466 bool Interpret( const binary * p_command, size_t i_size );
469 static const std::string CMD_MS_GOTO_AND_PLAY;
475 const std::string matroska_script_interpretor_c::CMD_MS_GOTO_AND_PLAY = "GotoAndPlay";
478 class matroska_script_codec_c : public chapter_codec_cmds_c
481 matroska_script_codec_c( demux_sys_t & sys )
482 :chapter_codec_cmds_c( 0 )
490 matroska_script_interpretor_c interpretor;
493 class chapter_translation_c
496 KaxChapterTranslateID translated;
497 unsigned int codec_id;
498 std::vector<uint64_t> editions;
507 ,i_user_start_time(-1)
510 ,b_display_seekpoint(true)
511 ,b_user_display(false)
515 virtual ~chapter_item_c()
517 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
518 while ( index != codecs.end() )
523 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
524 while ( index_ != sub_chapters.end() )
531 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
532 int PublishChapters( input_title_t & title, int & i_user_chapters, int i_level = 0 );
533 chapter_item_c * FindTimecode( mtime_t i_timecode );
534 void Append( const chapter_item_c & edition );
535 chapter_item_c * FindChapter( int64_t i_find_uid );
536 virtual chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
537 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
538 const void *p_cookie,
539 size_t i_cookie_size );
540 std::string GetCodecName( bool f_for_title = false ) const;
541 bool ParentOf( const chapter_item_c & item ) const;
543 int64_t i_start_time, i_end_time;
544 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
545 std::vector<chapter_item_c*> sub_chapters;
548 bool b_display_seekpoint;
550 std::string psz_name;
551 chapter_item_c *psz_parent;
553 std::vector<chapter_codec_cmds_c*> codecs;
555 bool operator<( const chapter_item_c & item ) const
557 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) );
560 bool Enter( bool b_do_subchapters );
561 bool Leave( bool b_do_subchapters );
562 bool EnterAndLeave( chapter_item_c *p_item );
565 class chapter_edition_c : public chapter_item_c
572 void RefreshChapters( );
573 mtime_t Duration() const;
574 std::string GetMainName() const;
579 class matroska_segment_c
582 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
585 ,i_timescale(MKVD_TIMECODESCALE)
589 ,i_chapters_position(-1)
596 ,psz_muxing_application(NULL)
597 ,psz_writing_application(NULL)
598 ,psz_segment_filename(NULL)
601 ,i_default_edition(0)
606 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
609 virtual ~matroska_segment_c()
611 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
613 #define tk tracks[i_track]
614 if( tk->fmt.psz_description )
616 free( tk->fmt.psz_description );
620 free( tk->psz_codec );
622 if( tk->fmt.psz_language )
624 free( tk->fmt.psz_language );
630 if( psz_writing_application )
632 free( psz_writing_application );
634 if( psz_muxing_application )
636 free( psz_muxing_application );
638 if( psz_segment_filename )
640 free( psz_segment_filename );
648 free( psz_date_utc );
655 std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
656 while ( index != stored_editions.end() )
667 uint64_t i_timescale;
669 /* duration of the segment */
671 mtime_t i_start_time;
674 std::vector<mkv_track_t*> tracks;
677 int64_t i_cues_position;
678 int64_t i_chapters_position;
679 int64_t i_tags_position;
683 KaxSegmentUID segment_uid;
684 KaxPrevUID prev_segment_uid;
685 KaxNextUID next_segment_uid;
693 char *psz_muxing_application;
694 char *psz_writing_application;
695 char *psz_segment_filename;
699 /* !!!!! GCC 3.3 bug on Darwin !!!!! */
700 /* when you remove this variable the compiler issues an atomicity error */
701 /* this variable only works when using std::vector<chapter_edition_c> */
702 std::vector<chapter_edition_c*> stored_editions;
703 int i_default_edition;
705 std::vector<chapter_translation_c> translations;
706 std::vector<KaxSegmentFamily> families;
713 bool PreloadFamily( const matroska_segment_c & segment );
714 void ParseInfo( KaxInfo *info );
715 void ParseChapters( KaxChapters *chapters );
716 void ParseSeekHead( KaxSeekHead *seekhead );
717 void ParseTracks( KaxTracks *tracks );
718 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
719 void ParseTrackEntry( KaxTrackEntry *m );
720 void ParseCluster( );
721 void IndexAppendCluster( KaxCluster *cluster );
724 void InformationCreate( );
725 void Seek( mtime_t i_date, mtime_t i_time_offset );
726 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
727 bool Select( mtime_t i_start_time );
730 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
733 // class holding hard-linked segment together in the playback order
734 class virtual_segment_c
737 virtual_segment_c( matroska_segment_c *p_segment )
738 :i_current_segment(0)
740 ,i_current_edition(-1)
741 ,psz_current_chapter(NULL)
744 linked_segments.push_back( p_segment );
746 AppendUID( p_segment->segment_uid );
747 AppendUID( p_segment->prev_segment_uid );
748 AppendUID( p_segment->next_segment_uid );
752 size_t AddSegment( matroska_segment_c *p_segment );
753 void PreloadLinked( );
754 mtime_t Duration( ) const;
756 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
758 inline chapter_edition_c *Edition()
760 if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
761 return (*p_editions)[i_current_edition];
765 matroska_segment_c * Segment() const
767 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
769 return linked_segments[i_current_segment];
772 inline const chapter_item_c *CurrentChapter() const {
773 return psz_current_chapter;
778 if ( i_current_segment < linked_segments.size()-1 )
786 bool FindUID( KaxSegmentUID & uid ) const
788 for ( size_t i=0; i<linked_uids.size(); i++ )
790 if ( linked_uids[i] == uid )
796 bool UpdateCurrentToChapter( demux_t & demux );
797 void PrepareChapters( );
799 chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
800 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
801 const void *p_cookie,
802 size_t i_cookie_size );
803 chapter_item_c *FindChapter( int64_t i_find_uid );
805 std::vector<chapter_edition_c*> *p_editions;
809 std::vector<matroska_segment_c*> linked_segments;
810 std::vector<KaxSegmentUID> linked_uids;
811 size_t i_current_segment;
813 int i_current_edition;
814 chapter_item_c *psz_current_chapter;
816 void AppendUID( const EbmlBinary & UID );
819 class matroska_stream_c
822 matroska_stream_c( demux_sys_t & demuxer )
828 virtual ~matroska_stream_c()
837 std::vector<matroska_segment_c*> segments;
845 demux_sys_t( demux_t & demux )
852 ,p_current_segment(NULL)
856 virtual ~demux_sys_t()
859 for ( i=0; i<streams.size(); i++ )
861 for ( i=0; i<opened_segments.size(); i++ )
862 delete opened_segments[i];
863 for ( i=0; i<used_segments.size(); i++ )
864 delete used_segments[i];
872 mtime_t i_chapter_time;
876 std::vector<input_title_t> titles; // matroska editions
877 size_t i_current_title;
879 std::vector<matroska_stream_c*> streams;
880 std::vector<matroska_segment_c*> opened_segments;
881 std::vector<virtual_segment_c*> used_segments;
882 virtual_segment_c *p_current_segment;
884 /* duration of the stream */
887 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
888 chapter_item_c *BrowseCodecPrivate( unsigned int codec_id,
889 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
890 const void *p_cookie,
891 size_t i_cookie_size,
892 virtual_segment_c * & p_segment_found );
893 chapter_item_c *FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found );
895 void PreloadFamily( const matroska_segment_c & of_segment );
896 void PreloadLinked( matroska_segment_c *p_segment );
897 bool PreparePlayback( virtual_segment_c *p_new_segment );
898 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
901 virtual_segment_c *VirtualFromSegments( matroska_segment_c *p_segment ) const;
902 bool IsUsedSegment( matroska_segment_c &p_segment ) const;
905 static int Demux ( demux_t * );
906 static int Control( demux_t *, int, va_list );
907 static void Seek ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
909 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
911 static char *UTF8ToStr ( const UTFstring &u );
913 /*****************************************************************************
914 * Open: initializes matroska demux structures
915 *****************************************************************************/
916 static int Open( vlc_object_t * p_this )
918 demux_t *p_demux = (demux_t*)p_this;
920 matroska_stream_c *p_stream;
921 matroska_segment_c *p_segment;
923 std::string s_path, s_filename;
924 vlc_stream_io_callback *p_io_callback;
925 EbmlStream *p_io_stream;
927 /* peek the begining */
928 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
930 /* is a valid file */
931 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
932 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
934 /* Set the demux function */
935 p_demux->pf_demux = Demux;
936 p_demux->pf_control = Control;
937 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
939 p_io_callback = new vlc_stream_io_callback( p_demux->s );
940 p_io_stream = new EbmlStream( *p_io_callback );
942 if( p_io_stream == NULL )
944 msg_Err( p_demux, "failed to create EbmlStream" );
945 delete p_io_callback;
950 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
951 if( p_stream == NULL )
953 msg_Err( p_demux, "cannot find KaxSegment" );
956 p_sys->streams.push_back( p_stream );
958 p_stream->p_in = p_io_callback;
959 p_stream->p_es = p_io_stream;
961 for (size_t i=0; i<p_stream->segments.size(); i++)
963 p_stream->segments[i]->Preload();
966 p_segment = p_stream->segments[0];
967 if( p_segment->cluster != NULL )
969 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
971 // reset the stream reading to the first cluster of the segment used
972 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
975 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
976 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
978 // assume it's a regular file
979 // get the directory path
980 s_path = p_demux->psz_path;
981 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
983 s_path = s_path.substr(0,s_path.length()-1);
987 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
989 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
993 struct dirent *p_file_item;
994 DIR *p_src_dir = opendir(s_path.c_str());
996 if (p_src_dir != NULL)
998 while ((p_file_item = (dirent *) readdir(p_src_dir)))
1000 if (strlen(p_file_item->d_name) > 4)
1002 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
1004 if (!s_filename.compare(p_demux->psz_path))
1005 continue; // don't reuse the original opened file
1007 #if defined(__GNUC__) && (__GNUC__ < 3)
1008 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
1009 !s_filename.compare("mka", s_filename.length() - 3, 3))
1011 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
1012 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
1015 // test wether this file belongs to the our family
1016 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
1017 EbmlStream *p_estream = new EbmlStream(*p_file_io);
1019 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
1020 if ( p_stream == NULL )
1022 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
1028 p_stream->p_in = p_file_io;
1029 p_stream->p_es = p_estream;
1030 p_sys->streams.push_back( p_stream );
1035 closedir( p_src_dir );
1039 p_sys->PreloadFamily( *p_segment );
1040 p_sys->PreloadLinked( p_segment );
1041 if ( !p_sys->PreparePlayback( NULL ) )
1043 msg_Err( p_demux, "cannot use the segment" );
1051 return VLC_EGENERIC;
1054 /*****************************************************************************
1055 * Close: frees unused data
1056 *****************************************************************************/
1057 static void Close( vlc_object_t *p_this )
1059 demux_t *p_demux = (demux_t*)p_this;
1060 demux_sys_t *p_sys = p_demux->p_sys;
1065 /*****************************************************************************
1067 *****************************************************************************/
1068 static int Control( demux_t *p_demux, int i_query, va_list args )
1070 demux_sys_t *p_sys = p_demux->p_sys;
1076 vlc_meta_t **pp_meta;
1080 case DEMUX_GET_META:
1081 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1082 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1085 case DEMUX_GET_LENGTH:
1086 pi64 = (int64_t*)va_arg( args, int64_t * );
1087 if( p_sys->f_duration > 0.0 )
1089 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1092 return VLC_EGENERIC;
1094 case DEMUX_GET_POSITION:
1095 pf = (double*)va_arg( args, double * );
1096 if ( p_sys->f_duration > 0.0 )
1097 *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);
1100 case DEMUX_SET_POSITION:
1101 f = (double)va_arg( args, double );
1102 Seek( p_demux, -1, f, NULL );
1105 case DEMUX_GET_TIME:
1106 pi64 = (int64_t*)va_arg( args, int64_t * );
1107 *pi64 = p_sys->i_pts;
1110 case DEMUX_GET_TITLE_INFO:
1111 if( p_sys->titles.size() )
1113 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1114 int *pi_int = (int*)va_arg( args, int* );
1116 *pi_int = p_sys->titles.size();
1117 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) * p_sys->titles.size() );
1119 for( size_t i = 0; i < p_sys->titles.size(); i++ )
1121 (*ppp_title)[i] = vlc_input_title_Duplicate( &p_sys->titles[i] );
1126 return VLC_EGENERIC;
1128 case DEMUX_SET_TITLE:
1129 /* TODO handle editions as titles */
1130 i_idx = (int)va_arg( args, int );
1131 if( i_idx < p_sys->used_segments.size() )
1133 p_sys->PreparePlayback( p_sys->used_segments[i_idx] );
1136 return VLC_EGENERIC;
1138 case DEMUX_SET_SEEKPOINT:
1139 i_skp = (int)va_arg( args, int );
1141 if( p_sys->titles.size() && i_skp < p_sys->titles[p_sys->i_current_title].i_seekpoint)
1143 Seek( p_demux, (int64_t)p_sys->titles[p_sys->i_current_title].seekpoint[i_skp]->i_time_offset, -1, NULL);
1144 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1145 p_demux->info.i_seekpoint = i_skp;
1148 return VLC_EGENERIC;
1150 case DEMUX_SET_TIME:
1153 return VLC_EGENERIC;
1157 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1169 return VLC_EGENERIC;
1172 i_level = ep->GetLevel();
1174 if( el == NULL && *pp_block != NULL )
1176 /* update the index */
1177 #define idx index[i_index - 1]
1178 if( i_index > 0 && idx.i_time == -1 )
1180 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1181 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1189 if( ep->GetLevel() > 1 )
1194 msg_Warn( &sys.demuxer, "EOF" );
1195 return VLC_EGENERIC;
1201 if( MKV_IS_ID( el, KaxCluster ) )
1203 cluster = (KaxCluster*)el;
1205 /* add it to the index */
1207 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1209 IndexAppendCluster( cluster );
1212 // reset silent tracks
1213 for (size_t i=0; i<tracks.size(); i++)
1215 tracks[i]->b_silent = VLC_FALSE;
1220 else if( MKV_IS_ID( el, KaxCues ) )
1222 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1223 return VLC_EGENERIC;
1227 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1230 else if( i_level == 2 )
1232 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1234 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1236 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1237 cluster->InitTimecode( uint64( ctc ), i_timescale );
1239 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1243 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1248 else if( i_level == 3 )
1250 if( MKV_IS_ID( el, KaxBlock ) )
1252 *pp_block = (KaxBlock*)el;
1254 (*pp_block)->ReadData( es.I_O() );
1255 (*pp_block)->SetParent( *cluster );
1259 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1261 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1263 dur.ReadData( es.I_O() );
1264 *pi_duration = uint64( dur );
1266 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1268 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1270 ref.ReadData( es.I_O() );
1271 if( *pi_ref1 == -1 )
1273 *pi_ref1 = int64( ref );
1277 *pi_ref2 = int64( ref );
1280 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1282 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1283 track_num.ReadData( es.I_O() );
1285 for (size_t i=0; i<tracks.size(); i++)
1287 if ( tracks[i]->i_number == uint32(track_num))
1289 tracks[i]->b_silent = VLC_TRUE;
1297 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1298 return VLC_EGENERIC;
1303 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1306 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1307 memcpy( p_block->p_buffer, p_mem, i_mem );
1308 //p_block->i_rate = p_input->stream.control.i_rate;
1312 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1313 mtime_t i_duration )
1315 demux_sys_t *p_sys = p_demux->p_sys;
1316 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1322 #define tk p_segment->tracks[i_track]
1323 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1325 if( tk->i_number == block->TrackNum() )
1331 if( i_track >= p_segment->tracks.size() )
1333 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1336 if( tk->p_es == NULL )
1338 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1341 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1343 return; /* discard audio packets that shouldn't be rendered */
1346 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1349 tk->b_inited = VLC_FALSE;
1353 /* First send init data */
1354 if( !tk->b_inited && tk->i_data_init > 0 )
1358 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1359 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1360 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1362 tk->b_inited = VLC_TRUE;
1365 for( i = 0; i < block->NumberFrames(); i++ )
1368 DataBuffer &data = block->GetBuffer(i);
1370 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1372 if( p_block == NULL )
1377 #if defined(HAVE_ZLIB_H)
1378 if( tk->i_compression_type )
1380 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1384 // TODO implement correct timestamping when B frames are used
1385 if( tk->fmt.i_cat != VIDEO_ES )
1387 p_block->i_dts = p_block->i_pts = i_pts;
1391 p_block->i_dts = i_pts;
1395 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1397 p_block->i_length = i_duration * 1000;
1400 es_out_Send( p_demux->out, tk->p_es, p_block );
1402 /* use time stamp only for first block */
1409 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1411 int i_upper_lvl = 0;
1413 EbmlElement *p_l0, *p_l1, *p_l2;
1414 bool b_keep_stream = false, b_keep_segment;
1416 // verify the EBML Header
1417 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1422 p_l0->SkipData(*p_estream, EbmlHead_Context);
1425 // find all segments in this file
1426 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1432 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1436 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1439 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1440 b_keep_segment = false;
1442 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1443 p_segment1->ep = ep;
1444 p_segment1->segment = (KaxSegment*)p_l0;
1446 while ((p_l1 = ep->Get()))
1448 if (MKV_IS_ID(p_l1, KaxInfo))
1450 // find the families of this segment
1451 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1453 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1454 for( i = 0; i < p_info->ListSize(); i++ )
1456 EbmlElement *l = (*p_info)[i];
1458 if( MKV_IS_ID( l, KaxSegmentUID ) )
1460 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1461 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1462 if ( !b_keep_segment )
1463 break; // this segment is already known
1464 opened_segments.push_back( p_segment1 );
1465 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1467 else if( MKV_IS_ID( l, KaxPrevUID ) )
1469 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1471 else if( MKV_IS_ID( l, KaxNextUID ) )
1473 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1475 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1477 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1478 p_segment1->families.push_back( *p_fam );
1484 if ( b_keep_segment )
1486 b_keep_stream = true;
1487 p_stream1->segments.push_back( p_segment1 );
1493 p_l0->SkipData(*p_estream, EbmlHead_Context);
1494 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1497 if ( !b_keep_stream )
1506 bool matroska_segment_c::Select( mtime_t i_start_time )
1511 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1512 for( i_track = 0; i_track < tracks.size(); i_track++ )
1514 #define tk tracks[i_track]
1515 if( tk->fmt.i_cat == UNKNOWN_ES )
1517 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1522 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1524 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1526 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1527 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1531 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1533 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1534 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1535 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1537 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1538 if( tk->fmt.i_extra > 0 )
1540 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1541 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1545 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1546 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1548 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1550 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1552 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1554 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1556 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1558 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1559 tk->fmt.b_packetized = VLC_FALSE;
1560 tk->fmt.i_extra = tk->i_extra_data;
1561 tk->fmt.p_extra = malloc( tk->i_extra_data );
1562 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1566 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1569 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1571 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1573 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1577 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1582 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1583 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1584 tk->fmt.i_codec = p_box->i_type;
1585 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1586 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1587 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1588 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1589 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1590 MP4_FreeBox_sample_vide( p_box );
1592 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1594 stream_Delete( p_mp4_stream );
1597 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1599 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1601 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1602 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1606 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1608 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1610 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1611 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1612 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1613 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1614 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1616 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1617 if( tk->fmt.i_extra > 0 )
1619 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1620 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1624 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1625 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1626 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1628 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1630 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1632 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1634 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1636 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1638 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1640 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1641 tk->fmt.i_extra = tk->i_extra_data;
1642 tk->fmt.p_extra = malloc( tk->i_extra_data );
1643 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1645 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1647 int i, i_offset = 1, i_size[3], i_extra;
1650 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1652 /* Split the 3 headers */
1653 if( tk->p_extra_data[0] != 0x02 )
1654 msg_Err( &sys.demuxer, "invalid vorbis header" );
1656 for( i = 0; i < 2; i++ )
1659 while( i_offset < tk->i_extra_data )
1661 i_size[i] += tk->p_extra_data[i_offset];
1662 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1666 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1667 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1668 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1670 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1671 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1672 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1673 for( i = 0; i < 3; i++ )
1675 *(p_extra++) = i_size[i] >> 8;
1676 *(p_extra++) = i_size[i] & 0xFF;
1677 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1679 p_extra += i_size[i];
1680 i_extra += i_size[i];
1683 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1684 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1686 int i_profile, i_srate;
1687 static unsigned int i_sample_rates[] =
1689 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1690 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1693 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1694 /* create data for faad (MP4DecSpecificDescrTag)*/
1696 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1700 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1704 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1713 for( i_srate = 0; i_srate < 13; i_srate++ )
1715 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1720 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1722 tk->fmt.i_extra = 2;
1723 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1724 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1725 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1727 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1728 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1729 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1731 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1733 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1737 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1739 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1741 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1743 /* FIXME: support this codec */
1744 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1745 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1747 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1749 /* FIXME: support this codec */
1750 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1751 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1753 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1755 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1756 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1758 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1759 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1760 !strcmp( tk->psz_codec, "S_SSA" ) ||
1761 !strcmp( tk->psz_codec, "S_ASS" ))
1763 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1764 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1766 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1768 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1769 if( tk->i_extra_data )
1772 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1773 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1774 p_buf[tk->i_extra_data] = '\0';
1776 p_start = strstr( p_buf, "size:" );
1777 if( sscanf( p_start, "size: %dx%d",
1778 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1780 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 );
1784 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1789 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1791 /* FIXME: support this codec */
1792 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1793 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1797 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1798 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1802 tk->fmt.i_priority = 1000;
1805 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1807 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1811 sys.i_start_pts = i_start_time;
1812 // reset the stream reading to the first cluster of the segment used
1813 es.I_O().setFilePointer( i_start_pos );
1816 ep = new EbmlParser( &es, segment, &sys.demuxer );
1821 void matroska_segment_c::UnSelect( )
1825 for( i_track = 0; i_track < tracks.size(); i_track++ )
1827 #define tk tracks[i_track]
1828 if ( tk->p_es != NULL )
1830 es_out_Del( sys.demuxer.out, tk->p_es );
1839 void virtual_segment_c::PrepareChapters( )
1841 if ( linked_segments.size() == 0 )
1844 // !!! should be called only once !!!
1845 matroska_segment_c *p_segment;
1848 // copy editions from the first segment
1849 p_segment = linked_segments[0];
1850 p_editions = &p_segment->stored_editions;
1852 for ( i=1 ; i<linked_segments.size(); i++ )
1854 p_segment = linked_segments[i];
1855 // FIXME assume we have the same editions in all segments
1856 for (j=0; j<p_segment->stored_editions.size(); j++)
1857 (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
1861 std::string chapter_edition_c::GetMainName() const
1863 if ( sub_chapters.size() )
1865 return sub_chapters[0]->GetCodecName( true );
1870 int chapter_item_c::PublishChapters( input_title_t & title, int & i_user_chapters, int i_level )
1872 // add support for meta-elements from codec like DVD Titles
1873 if ( !b_display_seekpoint || psz_name == "" )
1875 psz_name = GetCodecName();
1876 if ( psz_name != "" )
1877 b_display_seekpoint = true;
1880 if (b_display_seekpoint)
1882 seekpoint_t *sk = vlc_seekpoint_New();
1884 sk->i_level = i_level;
1885 sk->i_time_offset = i_start_time;
1886 sk->psz_name = strdup( psz_name.c_str() );
1888 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1889 title.i_seekpoint++;
1890 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1891 title.seekpoint[title.i_seekpoint-1] = sk;
1893 if ( b_user_display )
1897 for ( size_t i=0; i<sub_chapters.size() ; i++)
1899 sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
1902 i_seekpoint_num = i_user_chapters;
1904 return i_user_chapters;
1907 bool virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1909 demux_sys_t & sys = *demux.p_sys;
1910 chapter_item_c *psz_curr_chapter;
1912 /* update current chapter/seekpoint */
1913 if ( p_editions->size() )
1915 /* 1st, we need to know in which chapter we are */
1916 psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
1918 /* we have moved to a new chapter */
1919 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1921 if ( (*p_editions)[i_current_edition]->b_ordered )
1923 // Leave/Enter up to the link point
1924 if ( !psz_curr_chapter->EnterAndLeave( psz_current_chapter ) )
1926 // only seek if necessary
1927 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1928 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1931 else if ( psz_curr_chapter->i_seekpoint_num > 0 )
1933 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
1934 demux.info.i_title = sys.i_current_title = i_sys_title;
1935 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1938 psz_current_chapter = psz_curr_chapter;
1945 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id,
1946 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1947 const void *p_cookie,
1948 size_t i_cookie_size )
1950 // FIXME don't assume it is the first edition
1951 std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
1952 if ( index != p_editions->end() )
1954 chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
1955 if ( p_result != NULL )
1961 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
1963 // FIXME don't assume it is the first edition
1964 std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
1965 if ( index != p_editions->end() )
1967 chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
1968 if ( p_result != NULL )
1974 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id,
1975 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
1976 const void *p_cookie,
1977 size_t i_cookie_size )
1980 std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
1981 while ( index != codecs.end() )
1983 if ( match( **index ,p_cookie, i_cookie_size ) )
1989 chapter_item_c *p_result = NULL;
1990 std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
1991 while ( index2 != sub_chapters.end() )
1993 p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
1994 if ( p_result != NULL )
2002 void chapter_item_c::Append( const chapter_item_c & chapter )
2004 // we are appending content for the same chapter UID
2006 chapter_item_c *p_chapter;
2008 for ( i=0; i<chapter.sub_chapters.size(); i++ )
2010 p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
2011 if ( p_chapter != NULL )
2013 p_chapter->Append( *chapter.sub_chapters[i] );
2017 sub_chapters.push_back( chapter.sub_chapters[i] );
2021 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
2022 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
2025 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
2028 chapter_item_c *p_result = NULL;
2030 if ( i_uid == i_find_uid )
2033 for ( i=0; i<sub_chapters.size(); i++)
2035 p_result = sub_chapters[i]->FindChapter( i_find_uid );
2036 if ( p_result != NULL )
2042 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
2046 std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2047 while ( index != codecs.end() )
2049 result = (*index)->GetCodecName( f_for_title );
2058 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
2061 if ( m_private_data.GetSize() >= 3)
2063 const binary* p_data = m_private_data.GetBuffer();
2064 /* if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
2066 uint16_t i_title = (p_data[1] << 8) + p_data[2];
2068 sprintf( psz_str, " %d ---", i_title );
2069 result = N_("--- DVD Title");
2072 else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
2075 sprintf( psz_str, " (%c%c) ---", p_data[1], p_data[2] );
2076 result = N_("--- DVD Menu");
2079 else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
2081 if ( p_data[1] == 0x00 )
2082 result = N_("First Played");
2083 else if ( p_data[1] == 0xC0 )
2084 result = N_("Video Manager");
2085 else if ( p_data[1] == 0x80 )
2087 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2089 sprintf( psz_str, " %d -----", i_title );
2090 result = N_("----- Title");
2099 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2101 demux_sys_t *p_sys = p_demux->p_sys;
2102 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
2103 matroska_segment_c *p_segment = p_vsegment->Segment();
2104 mtime_t i_time_offset = 0;
2108 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2109 if( i_date < 0 && f_percent < 0 )
2111 msg_Warn( p_demux, "cannot seek nowhere !" );
2114 if( f_percent > 1.0 )
2116 msg_Warn( p_demux, "cannot seek so far !" );
2120 /* seek without index or without date */
2121 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2123 if (p_sys->f_duration >= 0)
2125 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2129 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2131 msg_Dbg( p_demux, "inacurate way of seeking" );
2132 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2134 if( p_segment->index[i_index].i_position >= i_pos)
2139 if( i_index == p_segment->i_index )
2144 i_date = p_segment->index[i_index].i_time;
2147 if( p_segment->index[i_index].i_position < i_pos )
2151 msg_Warn( p_demux, "searching for cluster, could take some time" );
2153 /* search a cluster */
2154 while( ( el = p_sys->ep->Get() ) != NULL )
2156 if( MKV_IS_ID( el, KaxCluster ) )
2158 KaxCluster *cluster = (KaxCluster*)el;
2160 /* add it to the index */
2161 p_segment->IndexAppendCluster( cluster );
2163 if( (int64_t)cluster->GetElementPosition() >= i_pos )
2165 p_sys->cluster = cluster;
2176 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
2179 /*****************************************************************************
2180 * Demux: reads and demuxes data packets
2181 *****************************************************************************
2182 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2183 *****************************************************************************/
2184 static int Demux( demux_t *p_demux)
2186 demux_sys_t *p_sys = p_demux->p_sys;
2187 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
2188 matroska_segment_c *p_segmet = p_vsegment->Segment();
2189 if ( p_segmet == NULL ) return 0;
2190 int i_block_count = 0;
2193 int64_t i_block_duration;
2194 int64_t i_block_ref1;
2195 int64_t i_block_ref2;
2199 if ( p_sys->demuxer.b_die )
2202 if( p_sys->i_pts >= p_sys->i_start_pts )
2203 if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
2206 if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
2208 /* nothing left to read in this ordered edition */
2209 if ( !p_vsegment->SelectNext() )
2211 p_segmet->UnSelect( );
2213 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2215 /* switch to the next segment */
2216 p_segmet = p_vsegment->Segment();
2217 if ( !p_segmet->Select( 0 ) )
2219 msg_Err( p_demux, "Failed to select new segment" );
2226 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
2228 if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
2230 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
2231 // check if there are more chapters to read
2232 if ( p_chap != NULL )
2234 /* TODO handle successive chapters with the same user_start_time/user_end_time
2235 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
2236 p_vsegment->SelectNext();
2238 p_sys->i_pts = p_chap->i_user_end_time;
2239 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2246 msg_Warn( p_demux, "cannot get block EOF?" );
2247 p_segmet->UnSelect( );
2249 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2251 /* switch to the next segment */
2252 if ( !p_vsegment->SelectNext() )
2253 // no more segments in this stream
2255 p_segmet = p_vsegment->Segment();
2256 if ( !p_segmet->Select( 0 ) )
2258 msg_Err( p_demux, "Failed to select new segment" );
2265 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2267 if( p_sys->i_pts >= p_sys->i_start_pts )
2269 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2272 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2277 // TODO optimize when there is need to leave or when seeking has been called
2278 if( i_block_count > 5 )
2287 /*****************************************************************************
2289 *****************************************************************************/
2290 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2296 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2298 if( i_size <= 0 || mb_eof )
2303 return stream_Read( s, p_buffer, i_size );
2305 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2311 case seek_beginning:
2315 i_pos = stream_Size( s ) - i_offset;
2318 i_pos= stream_Tell( s ) + i_offset;
2322 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2329 if( stream_Seek( s, i_pos ) )
2335 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2339 uint64 vlc_stream_io_callback::getFilePointer( void )
2341 return stream_Tell( s );
2343 void vlc_stream_io_callback::close( void )
2349 /*****************************************************************************
2350 * Ebml Stream parser
2351 *****************************************************************************/
2352 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2359 mi_remain_size[0] = el_start->GetSize();
2361 for( i = 1; i < 6; i++ )
2367 mb_keep = VLC_FALSE;
2368 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2371 EbmlParser::~EbmlParser( void )
2375 for( i = 1; i < mi_level; i++ )
2381 mb_keep = VLC_FALSE;
2385 void EbmlParser::Up( void )
2387 if( mi_user_level == mi_level )
2389 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2395 void EbmlParser::Down( void )
2401 void EbmlParser::Keep( void )
2406 int EbmlParser::GetLevel( void )
2408 return mi_user_level;
2411 void EbmlParser::Reset( demux_t *p_demux )
2413 while ( mi_level > 0)
2415 delete m_el[mi_level];
2416 m_el[mi_level] = NULL;
2419 mi_user_level = mi_level = 1;
2420 #if LIBEBML_VERSION >= 0x000704
2421 // a little faster and cleaner
2422 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2424 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2426 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2429 EbmlElement *EbmlParser::Get( void )
2433 if( mi_user_level != mi_level )
2439 EbmlElement *ret = m_got;
2445 if( m_el[mi_level] )
2447 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2450 delete m_el[mi_level];
2452 mb_keep = VLC_FALSE;
2455 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2456 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2467 delete m_el[mi_level - 1];
2468 m_got = m_el[mi_level -1] = m_el[mi_level];
2469 m_el[mi_level] = NULL;
2476 else if( m_el[mi_level] == NULL )
2478 fprintf( stderr," m_el[mi_level] == NULL\n" );
2481 return m_el[mi_level];
2485 /*****************************************************************************
2487 * * LoadCues : load the cues element and update index
2489 * * LoadTags : load ... the tags element
2491 * * InformationCreate : create all information, load tags if present
2493 *****************************************************************************/
2494 void matroska_segment_c::LoadCues( )
2496 int64_t i_sav_position = es.I_O().getFilePointer();
2498 EbmlElement *el, *cues;
2500 /* *** Load the cue if found *** */
2501 if( i_cues_position < 0 )
2503 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2505 // IndexAppendCluster( cluster );
2508 vlc_bool_t b_seekable;
2510 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2514 msg_Dbg( &sys.demuxer, "loading cues" );
2515 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2516 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2520 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2521 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2525 ep = new EbmlParser( &es, cues, &sys.demuxer );
2526 while( ( el = ep->Get() ) != NULL )
2528 if( MKV_IS_ID( el, KaxCuePoint ) )
2530 #define idx index[i_index]
2533 idx.i_block_number= -1;
2534 idx.i_position = -1;
2536 idx.b_key = VLC_TRUE;
2539 while( ( el = ep->Get() ) != NULL )
2541 if( MKV_IS_ID( el, KaxCueTime ) )
2543 KaxCueTime &ctime = *(KaxCueTime*)el;
2545 ctime.ReadData( es.I_O() );
2547 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2549 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2552 while( ( el = ep->Get() ) != NULL )
2554 if( MKV_IS_ID( el, KaxCueTrack ) )
2556 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2558 ctrack.ReadData( es.I_O() );
2559 idx.i_track = uint16( ctrack );
2561 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2563 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2565 ccpos.ReadData( es.I_O() );
2566 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2568 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2570 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2572 cbnum.ReadData( es.I_O() );
2573 idx.i_block_number = uint32( cbnum );
2577 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2584 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2590 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2591 " track=%d bnum=%d", idx.i_time, idx.i_position,
2592 idx.i_track, idx.i_block_number );
2596 if( i_index >= i_index_max )
2598 i_index_max += 1024;
2599 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2605 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2613 msg_Dbg( &sys.demuxer, "loading cues done." );
2614 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2617 void matroska_segment_c::LoadTags( )
2619 int64_t i_sav_position = es.I_O().getFilePointer();
2621 EbmlElement *el, *tags;
2623 msg_Dbg( &sys.demuxer, "loading tags" );
2624 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2625 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2629 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2630 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2634 msg_Dbg( &sys.demuxer, "Tags" );
2635 ep = new EbmlParser( &es, tags, &sys.demuxer );
2636 while( ( el = ep->Get() ) != NULL )
2638 if( MKV_IS_ID( el, KaxTag ) )
2640 msg_Dbg( &sys.demuxer, "+ Tag" );
2642 while( ( el = ep->Get() ) != NULL )
2644 if( MKV_IS_ID( el, KaxTagTargets ) )
2646 msg_Dbg( &sys.demuxer, "| + Targets" );
2648 while( ( el = ep->Get() ) != NULL )
2650 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2654 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2656 msg_Dbg( &sys.demuxer, "| + General" );
2658 while( ( el = ep->Get() ) != NULL )
2660 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2664 else if( MKV_IS_ID( el, KaxTagGenres ) )
2666 msg_Dbg( &sys.demuxer, "| + Genres" );
2668 while( ( el = ep->Get() ) != NULL )
2670 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2674 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2676 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2678 while( ( el = ep->Get() ) != NULL )
2680 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2684 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2686 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2688 while( ( el = ep->Get() ) != NULL )
2690 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2694 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2696 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2698 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2700 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2702 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2704 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2706 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2708 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2710 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2712 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2714 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2716 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2718 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2720 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2724 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2731 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2737 msg_Dbg( &sys.demuxer, "loading tags done." );
2738 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2741 /*****************************************************************************
2743 *****************************************************************************/
2744 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2748 int i_upper_level = 0;
2750 msg_Dbg( &sys.demuxer, "| + Seek head" );
2752 /* Master elements */
2753 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2755 for( i = 0; i < seekhead->ListSize(); i++ )
2757 EbmlElement *l = (*seekhead)[i];
2759 if( MKV_IS_ID( l, KaxSeek ) )
2761 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2762 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2765 for( j = 0; j < sk->ListSize(); j++ )
2767 EbmlElement *l = (*sk)[j];
2769 if( MKV_IS_ID( l, KaxSeekID ) )
2771 KaxSeekID &sid = *(KaxSeekID*)l;
2772 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2774 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2776 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2777 i_pos = uint64( spos );
2781 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2787 if( id == KaxCues::ClassInfos.GlobalId )
2789 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2790 i_cues_position = segment->GetGlobalPosition( i_pos );
2792 else if( id == KaxChapters::ClassInfos.GlobalId )
2794 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2795 i_chapters_position = segment->GetGlobalPosition( i_pos );
2797 else if( id == KaxTags::ClassInfos.GlobalId )
2799 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2800 i_tags_position = segment->GetGlobalPosition( i_pos );
2806 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2811 /*****************************************************************************
2813 *****************************************************************************/
2814 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2820 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2822 tk = new mkv_track_t();
2823 tracks.push_back( tk );
2825 /* Init the track */
2826 memset( tk, 0, sizeof( mkv_track_t ) );
2828 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2829 tk->fmt.psz_language = strdup("English");
2830 tk->fmt.psz_description = NULL;
2832 tk->b_default = VLC_TRUE;
2833 tk->b_enabled = VLC_TRUE;
2834 tk->b_silent = VLC_FALSE;
2835 tk->i_number = tracks.size() - 1;
2836 tk->i_extra_data = 0;
2837 tk->p_extra_data = NULL;
2838 tk->psz_codec = NULL;
2839 tk->i_default_duration = 0;
2840 tk->f_timecodescale = 1.0;
2842 tk->b_inited = VLC_FALSE;
2843 tk->i_data_init = 0;
2844 tk->p_data_init = NULL;
2846 tk->psz_codec_name = NULL;
2847 tk->psz_codec_settings = NULL;
2848 tk->psz_codec_info_url = NULL;
2849 tk->psz_codec_download_url = NULL;
2851 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2853 for( i = 0; i < m->ListSize(); i++ )
2855 EbmlElement *l = (*m)[i];
2857 if( MKV_IS_ID( l, KaxTrackNumber ) )
2859 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2861 tk->i_number = uint32( tnum );
2862 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2864 else if( MKV_IS_ID( l, KaxTrackUID ) )
2866 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2868 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2870 else if( MKV_IS_ID( l, KaxTrackType ) )
2873 KaxTrackType &ttype = *(KaxTrackType*)l;
2875 switch( uint8(ttype) )
2879 tk->fmt.i_cat = AUDIO_ES;
2883 tk->fmt.i_cat = VIDEO_ES;
2885 case track_subtitle:
2886 psz_type = "subtitle";
2887 tk->fmt.i_cat = SPU_ES;
2890 psz_type = "unknown";
2891 tk->fmt.i_cat = UNKNOWN_ES;
2895 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2897 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2899 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2901 // tk->b_enabled = uint32( fenb );
2902 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2903 // uint32( fenb ) );
2905 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2907 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2909 tk->b_default = uint32( fdef );
2910 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2912 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2914 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2916 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2918 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2920 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2922 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2924 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2926 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2928 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2930 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2932 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2934 tk->i_default_duration = uint64(defd);
2935 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2937 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2939 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2941 tk->f_timecodescale = float( ttcs );
2942 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2944 else if( MKV_IS_ID( l, KaxTrackName ) )
2946 KaxTrackName &tname = *(KaxTrackName*)l;
2948 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2949 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2951 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2953 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2955 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2956 msg_Dbg( &sys.demuxer,
2957 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2959 else if( MKV_IS_ID( l, KaxCodecID ) )
2961 KaxCodecID &codecid = *(KaxCodecID*)l;
2963 tk->psz_codec = strdup( string( codecid ).c_str() );
2964 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2966 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2968 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2970 tk->i_extra_data = cpriv.GetSize();
2971 if( tk->i_extra_data > 0 )
2973 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2974 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2976 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2978 else if( MKV_IS_ID( l, KaxCodecName ) )
2980 KaxCodecName &cname = *(KaxCodecName*)l;
2982 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2983 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2985 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2987 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2988 MkvTree( sys.demuxer, 3, "Content Encodings" );
2989 for( j = 0; j < cencs->ListSize(); j++ )
2991 EbmlElement *l2 = (*cencs)[j];
2992 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2994 MkvTree( sys.demuxer, 4, "Content Encoding" );
2995 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2996 for( k = 0; k < cenc->ListSize(); k++ )
2998 EbmlElement *l3 = (*cenc)[k];
2999 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
3001 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
3002 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
3004 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
3006 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
3007 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
3009 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
3011 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
3012 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
3014 else if( MKV_IS_ID( l3, KaxContentCompression ) )
3016 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
3017 MkvTree( sys.demuxer, 5, "Content Compression" );
3018 for( n = 0; n < compr->ListSize(); n++ )
3020 EbmlElement *l4 = (*compr)[n];
3021 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
3023 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
3024 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
3025 if( uint32( compalg ) == 0 )
3027 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
3032 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
3039 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
3046 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
3051 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
3053 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
3055 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
3056 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
3058 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
3060 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
3062 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3063 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
3065 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3067 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3069 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3070 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
3072 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3074 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3076 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3078 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3080 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3082 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3084 else if( MKV_IS_ID( l, KaxTrackVideo ) )
3086 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3089 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
3092 for( j = 0; j < tkv->ListSize(); j++ )
3094 EbmlElement *l = (*tkv)[j];
3095 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3097 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3099 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
3101 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3103 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3105 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
3108 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3110 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3112 tk->fmt.video.i_width = uint16( vwidth );
3113 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
3115 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3117 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3119 tk->fmt.video.i_height = uint16( vheight );
3120 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
3122 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3124 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3126 tk->fmt.video.i_visible_width = uint16( vwidth );
3127 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
3129 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
3131 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
3133 tk->fmt.video.i_visible_height = uint16( vheight );
3134 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
3136 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
3138 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
3140 tk->f_fps = float( vfps );
3141 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
3143 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
3145 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
3147 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
3148 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
3150 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
3152 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
3154 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
3156 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
3158 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
3160 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
3164 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
3167 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
3168 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
3170 else if( MKV_IS_ID( l, KaxTrackAudio ) )
3172 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
3175 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
3177 for( j = 0; j < tka->ListSize(); j++ )
3179 EbmlElement *l = (*tka)[j];
3181 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
3183 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
3185 tk->fmt.audio.i_rate = (int)float( afreq );
3186 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
3188 else if( MKV_IS_ID( l, KaxAudioChannels ) )
3190 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
3192 tk->fmt.audio.i_channels = uint8( achan );
3193 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
3195 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
3197 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
3199 tk->fmt.audio.i_bitspersample = uint8( abits );
3200 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
3204 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
3210 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
3211 typeid(*l).name() );
3216 /*****************************************************************************
3218 *****************************************************************************/
3219 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
3223 int i_upper_level = 0;
3225 msg_Dbg( &sys.demuxer, "| + Tracks" );
3227 /* Master elements */
3228 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
3230 for( i = 0; i < tracks->ListSize(); i++ )
3232 EbmlElement *l = (*tracks)[i];
3234 if( MKV_IS_ID( l, KaxTrackEntry ) )
3236 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
3240 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3245 /*****************************************************************************
3247 *****************************************************************************/
3248 void matroska_segment_c::ParseInfo( KaxInfo *info )
3253 int i_upper_level = 0;
3255 msg_Dbg( &sys.demuxer, "| + Information" );
3257 /* Master elements */
3258 m = static_cast<EbmlMaster *>(info);
3259 m->Read( es, info->Generic().Context, i_upper_level, el, true );
3261 for( i = 0; i < m->ListSize(); i++ )
3263 EbmlElement *l = (*m)[i];
3265 if( MKV_IS_ID( l, KaxSegmentUID ) )
3267 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3269 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3271 else if( MKV_IS_ID( l, KaxPrevUID ) )
3273 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3275 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3277 else if( MKV_IS_ID( l, KaxNextUID ) )
3279 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3281 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3283 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3285 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3287 i_timescale = uint64(tcs);
3289 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3292 else if( MKV_IS_ID( l, KaxDuration ) )
3294 KaxDuration &dur = *(KaxDuration*)l;
3296 i_duration = mtime_t( double( dur ) );
3298 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3301 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3303 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3305 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3307 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3308 psz_muxing_application );
3310 else if( MKV_IS_ID( l, KaxWritingApp ) )
3312 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3314 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3316 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3317 psz_writing_application );
3319 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3321 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3323 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3325 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3326 psz_segment_filename );
3328 else if( MKV_IS_ID( l, KaxTitle ) )
3330 KaxTitle &title = *(KaxTitle*)l;
3332 psz_title = UTF8ToStr( UTFstring( title ) );
3334 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3336 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3338 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3340 families.push_back(*uid);
3342 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3344 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3345 else if( MKV_IS_ID( l, KaxDateUTC ) )
3347 KaxDateUTC &date = *(KaxDateUTC*)l;
3352 i_date = date.GetEpochDate();
3353 memset( buffer, 0, 256 );
3354 if( gmtime_r( &i_date, &tmres ) &&
3355 asctime_r( &tmres, buffer ) )
3357 buffer[strlen( buffer)-1]= '\0';
3358 psz_date_utc = strdup( buffer );
3359 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3363 #if LIBMATROSKA_VERSION >= 0x000704
3364 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3366 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3367 chapter_translation_c translated;
3369 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3370 for( j = 0; j < p_trans->ListSize(); j++ )
3372 EbmlElement *l = (*p_trans)[j];
3374 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3376 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3378 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3380 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3382 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3384 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3388 translations.push_back( translated );
3393 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3397 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3398 i_duration = mtime_t(f_dur);
3402 /*****************************************************************************
3404 *****************************************************************************/
3405 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3409 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3410 for( i = 0; i < ca->ListSize(); i++ )
3412 EbmlElement *l = (*ca)[i];
3414 if( MKV_IS_ID( l, KaxChapterUID ) )
3416 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3417 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3419 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3421 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3422 chapters.b_display_seekpoint = uint8( flag ) == 0;
3424 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3426 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3428 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3429 chapters.i_start_time = uint64( start ) / I64C(1000);
3431 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3433 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3435 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3436 chapters.i_end_time = uint64( end ) / I64C(1000);
3438 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3440 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3442 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3444 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3445 for( j = 0; j < cd->ListSize(); j++ )
3447 EbmlElement *l= (*cd)[j];
3449 if( MKV_IS_ID( l, KaxChapterString ) )
3453 KaxChapterString &name =*(KaxChapterString*)l;
3454 for (k = 0; k < i_level; k++)
3455 chapters.psz_name += '+';
3456 chapters.psz_name += ' ';
3457 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3458 chapters.b_user_display = true;
3460 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3462 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3464 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3465 const char *psz = string( lang ).c_str();
3467 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3469 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3471 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3472 const char *psz = string( ct ).c_str();
3474 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3478 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3480 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3482 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3483 chapter_codec_cmds_c *p_ccodec = NULL;
3485 for( j = 0; j < cp->ListSize(); j++ )
3487 EbmlElement *k= (*cp)[j];
3489 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3491 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3492 if ( uint32(*p_codec_id) == 0 )
3493 p_ccodec = new matroska_script_codec_c( sys );
3494 else if ( uint32(*p_codec_id) == 1 )
3495 p_ccodec = new dvd_chapter_codec_c( sys );
3500 if ( p_ccodec != NULL )
3502 for( j = 0; j < cp->ListSize(); j++ )
3504 EbmlElement *k= (*cp)[j];
3506 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3508 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3509 p_ccodec->SetPrivate( *p_private );
3511 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3513 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3516 chapters.codecs.push_back( p_ccodec );
3519 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3521 chapter_item_c *new_sub_chapter = new chapter_item_c();
3522 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3523 new_sub_chapter->psz_parent = &chapters;
3524 chapters.sub_chapters.push_back( new_sub_chapter );
3529 /*****************************************************************************
3531 *****************************************************************************/
3532 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3536 int i_upper_level = 0;
3539 /* Master elements */
3540 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3542 for( i = 0; i < chapters->ListSize(); i++ )
3544 EbmlElement *l = (*chapters)[i];
3546 if( MKV_IS_ID( l, KaxEditionEntry ) )
3548 chapter_edition_c *p_edition = new chapter_edition_c();
3550 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3552 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3553 for( j = 0; j < E->ListSize(); j++ )
3555 EbmlElement *l = (*E)[j];
3557 if( MKV_IS_ID( l, KaxChapterAtom ) )
3559 chapter_item_c *new_sub_chapter = new chapter_item_c();
3560 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3561 p_edition->sub_chapters.push_back( new_sub_chapter );
3563 else if( MKV_IS_ID( l, KaxEditionUID ) )
3565 p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3567 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3569 p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3571 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3573 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3574 i_default_edition = stored_editions.size();
3578 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3581 stored_editions.push_back( p_edition );
3585 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3589 for( i = 0; i < stored_editions.size(); i++ )
3591 stored_editions[i]->RefreshChapters( );
3594 if ( stored_editions[i_default_edition]->b_ordered )
3596 /* update the duration of the segment according to the sum of all sub chapters */
3597 i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3603 void matroska_segment_c::ParseCluster( )
3608 int i_upper_level = 0;
3610 /* Master elements */
3611 m = static_cast<EbmlMaster *>( cluster );
3612 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3614 for( i = 0; i < m->ListSize(); i++ )
3616 EbmlElement *l = (*m)[i];
3618 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3620 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3622 cluster->InitTimecode( uint64( ctc ), i_timescale );
3627 i_start_time = cluster->GlobalTimecode() / 1000;
3630 /*****************************************************************************
3631 * InformationCreate:
3632 *****************************************************************************/
3633 void matroska_segment_c::InformationCreate( )
3637 sys.meta = vlc_meta_New();
3641 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3645 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3647 if( psz_segment_filename )
3649 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3651 if( psz_muxing_application )
3653 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3655 if( psz_writing_application )
3657 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3660 for( i_track = 0; i_track < tracks.size(); i_track++ )
3662 mkv_track_t *tk = tracks[i_track];
3663 vlc_meta_t *mtk = vlc_meta_New();
3665 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3666 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3667 sys.meta->track[sys.meta->i_track++] = mtk;
3669 if( tk->fmt.psz_description )
3671 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3673 if( tk->psz_codec_name )
3675 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3677 if( tk->psz_codec_settings )
3679 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3681 if( tk->psz_codec_info_url )
3683 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3685 if( tk->psz_codec_download_url )
3687 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3691 if( i_tags_position >= 0 )
3693 vlc_bool_t b_seekable;
3695 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3704 /*****************************************************************************
3706 *****************************************************************************/
3708 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3710 #define idx index[i_index]
3712 idx.i_block_number= -1;
3713 idx.i_position = cluster->GetElementPosition();
3715 idx.b_key = VLC_TRUE;
3718 if( i_index >= i_index_max )
3720 i_index_max += 1024;
3721 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3726 static char * UTF8ToStr( const UTFstring &u )
3735 p = dst = (char*)malloc( i_src + 1);
3754 void chapter_edition_c::RefreshChapters( )
3756 chapter_item_c::RefreshChapters( b_ordered, -1 );
3757 b_display_seekpoint = false;
3760 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3762 int64_t i_user_time = i_prev_user_time;
3764 // first the sub-chapters, and then ourself
3765 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3766 while ( index != sub_chapters.end() )
3768 i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3774 // the ordered chapters always start at zero
3775 if ( i_prev_user_time == -1 )
3777 if ( i_user_time == -1 )
3779 i_prev_user_time = 0;
3782 i_user_start_time = i_prev_user_time;
3783 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3785 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3789 i_user_end_time = i_user_time;
3794 std::sort( sub_chapters.begin(), sub_chapters.end() );
3795 i_user_start_time = i_start_time;
3796 if ( i_end_time != -1 )
3797 i_user_end_time = i_end_time;
3798 else if ( i_user_time != -1 )
3799 i_user_end_time = i_user_time;
3801 i_user_end_time = i_user_start_time;
3804 return i_user_end_time;
3807 mtime_t chapter_edition_c::Duration() const
3809 mtime_t i_result = 0;
3811 if ( sub_chapters.size() )
3813 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3815 i_result = (*index)->i_user_end_time;
3821 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3823 chapter_item_c *psz_result = NULL;
3825 if ( i_user_timecode >= i_user_start_time &&
3826 ( i_user_timecode < i_user_end_time ||
3827 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3829 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3830 while ( index != sub_chapters.end() && psz_result == NULL )
3832 psz_result = (*index)->FindTimecode( i_user_timecode );
3836 if ( psz_result == NULL )
3843 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
3845 if ( &item == this )
3848 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
3849 while ( index != sub_chapters.end() )
3851 if ( (*index)->ParentOf( item ) )
3859 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3861 for (size_t i=0; i<opened_segments.size(); i++)
3863 opened_segments[i]->PreloadFamily( of_segment );
3866 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3871 for (size_t i=0; i<families.size(); i++)
3873 for (size_t j=0; j<of_segment.families.size(); j++)
3875 if ( families[i] == of_segment.families[j] )
3883 // preload all the linked segments for all preloaded segments
3884 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3886 size_t i_preloaded, i, j;
3887 virtual_segment_c *p_seg;
3889 p_current_segment = VirtualFromSegments( p_segment );
3891 used_segments.push_back( p_current_segment );
3893 // create all the other virtual segments of the family
3896 for ( i=0; i< opened_segments.size(); i++ )
3898 if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
3900 p_seg = VirtualFromSegments( opened_segments[i] );
3901 used_segments.push_back( p_seg );
3905 } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
3907 // publish all editions of all usable segment
3908 for ( i=0; i< used_segments.size(); i++ )
3910 p_seg = used_segments[i];
3911 if ( p_seg->p_editions != NULL )
3913 std::string sz_name;
3914 input_title_t *p_title = vlc_input_title_New();
3915 p_seg->i_sys_title = i;
3918 // TODO use a name for each edition, let the TITLE deal with a codec name
3919 for ( j=0; j<p_seg->p_editions->size(); j++ )
3921 if ( p_title->psz_name == NULL )
3923 sz_name = (*p_seg->p_editions)[j]->GetMainName();
3924 if ( sz_name != "" )
3925 p_title->psz_name = strdup( sz_name.c_str() );
3928 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
3931 p_edition->PublishChapters( *p_title, i_chapters, 0 );
3934 // create a name if there is none
3935 if ( p_title->psz_name == NULL )
3937 sz_name = N_("Segment ");
3939 sprintf( psz_str, "%d", i );
3941 p_title->psz_name = strdup( sz_name.c_str() );
3944 titles.push_back( *p_title );
3949 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
3951 for ( size_t i=0; i< used_segments.size(); i++ )
3953 if ( used_segments[i]->FindUID( segment.segment_uid ) )
3959 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
3961 size_t i_preloaded, i;
3963 virtual_segment_c *p_result = new virtual_segment_c( p_segment );
3965 // fill our current virtual segment with all hard linked segments
3968 for ( i=0; i< opened_segments.size(); i++ )
3970 i_preloaded += p_result->AddSegment( opened_segments[i] );
3972 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3976 p_result->PreloadLinked( );
3978 p_result->PrepareChapters( );
3983 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
3985 if ( p_new_segment != NULL && p_new_segment != p_current_segment )
3987 if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
3988 p_current_segment->Segment()->UnSelect();
3990 p_current_segment = p_new_segment;
3991 i_current_title = p_new_segment->i_sys_title;
3994 p_current_segment->LoadCues();
3995 f_duration = p_current_segment->Duration();
3997 /* add information */
3998 p_current_segment->Segment()->InformationCreate( );
4000 p_current_segment->Segment()->Select( 0 );
4005 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
4007 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
4008 if ( *p_itema == p_item_b->prev_segment_uid )
4011 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
4012 if ( *p_itema == p_item_b->segment_uid )
4015 if ( *p_itema == p_item_b->prev_segment_uid )
4021 bool matroska_segment_c::Preload( )
4026 EbmlElement *el = NULL;
4028 ep->Reset( &sys.demuxer );
4030 while( ( el = ep->Get() ) != NULL )
4032 if( MKV_IS_ID( el, KaxInfo ) )
4034 ParseInfo( static_cast<KaxInfo*>( el ) );
4036 else if( MKV_IS_ID( el, KaxTracks ) )
4038 ParseTracks( static_cast<KaxTracks*>( el ) );
4040 else if( MKV_IS_ID( el, KaxSeekHead ) )
4042 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
4044 else if( MKV_IS_ID( el, KaxCues ) )
4046 msg_Dbg( &sys.demuxer, "| + Cues" );
4048 else if( MKV_IS_ID( el, KaxCluster ) )
4050 msg_Dbg( &sys.demuxer, "| + Cluster" );
4052 cluster = (KaxCluster*)el;
4054 i_start_pos = cluster->GetElementPosition();
4058 /* stop parsing the stream */
4061 else if( MKV_IS_ID( el, KaxAttachments ) )
4063 msg_Dbg( &sys.demuxer, "| + Attachments FIXME (but probably never supported)" );
4065 else if( MKV_IS_ID( el, KaxChapters ) )
4067 msg_Dbg( &sys.demuxer, "| + Chapters" );
4068 ParseChapters( static_cast<KaxChapters*>( el ) );
4070 else if( MKV_IS_ID( el, KaxTag ) )
4072 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
4076 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
4085 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4087 for (size_t i=0; i<opened_segments.size(); i++)
4089 if ( opened_segments[i]->segment_uid == uid )
4090 return opened_segments[i];
4095 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id,
4096 bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ),
4097 const void *p_cookie,
4098 size_t i_cookie_size,
4099 virtual_segment_c * &p_segment_found )
4101 chapter_item_c *p_result = NULL;
4102 for (size_t i=0; i<used_segments.size(); i++)
4104 p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4105 if ( p_result != NULL )
4107 p_segment_found = used_segments[i];
4114 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
4116 chapter_item_c *p_result = NULL;
4117 for (size_t i=0; i<used_segments.size(); i++)
4119 p_result = used_segments[i]->FindChapter( i_find_uid );
4120 if ( p_result != NULL )
4122 p_segment_found = used_segments[i];
4129 void virtual_segment_c::Sort()
4131 // keep the current segment index
4132 matroska_segment_c *p_segment = linked_segments[i_current_segment];
4134 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
4136 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
4137 if ( linked_segments[i_current_segment] == p_segment )
4141 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
4144 // check if it's not already in here
4145 for ( i=0; i<linked_segments.size(); i++ )
4147 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
4151 // find possible mates
4152 for ( i=0; i<linked_uids.size(); i++ )
4154 if ( p_segment->segment_uid == linked_uids[i]
4155 || p_segment->prev_segment_uid == linked_uids[i]
4156 || p_segment->next_segment_uid == linked_uids[i] )
4158 linked_segments.push_back( p_segment );
4160 AppendUID( p_segment->prev_segment_uid );
4161 AppendUID( p_segment->next_segment_uid );
4169 void virtual_segment_c::PreloadLinked( )
4171 for ( size_t i=0; i<linked_segments.size(); i++ )
4173 linked_segments[i]->Preload( );
4175 i_current_edition = linked_segments[0]->i_default_edition;
4178 mtime_t virtual_segment_c::Duration() const
4181 if ( linked_segments.size() == 0 )
4184 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
4185 // p_last_segment->ParseCluster( );
4187 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
4192 void virtual_segment_c::LoadCues( )
4194 for ( size_t i=0; i<linked_segments.size(); i++ )
4196 linked_segments[i]->LoadCues();
4200 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
4202 if ( UID.GetBuffer() == NULL )
4205 for (size_t i=0; i<linked_uids.size(); i++)
4207 if ( UID == linked_uids[i] )
4210 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
4213 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
4216 int i_track_skipping;
4217 int64_t i_block_duration;
4218 int64_t i_block_ref1;
4219 int64_t i_block_ref2;
4221 int64_t i_seek_position = i_start_pos;
4222 int64_t i_seek_time = i_start_time;
4228 for( ; i_idx < i_index; i_idx++ )
4230 if( index[i_idx].i_time + i_time_offset > i_date )
4241 i_seek_position = index[i_idx].i_position;
4242 i_seek_time = index[i_idx].i_time;
4245 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
4246 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
4248 es.I_O().setFilePointer( i_seek_position, seek_beginning );
4251 ep = new EbmlParser( &es, segment, &sys.demuxer );
4254 sys.i_start_pts = i_date;
4256 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
4258 /* now parse until key frame */
4259 #define tk tracks[i_track]
4260 i_track_skipping = 0;
4261 for( i_track = 0; i_track < tracks.size(); i_track++ )
4263 if( tk->fmt.i_cat == VIDEO_ES )
4265 tk->b_search_keyframe = VLC_TRUE;
4268 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
4272 while( i_track_skipping > 0 )
4274 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
4276 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
4281 for( i_track = 0; i_track < tracks.size(); i_track++ )
4283 if( tk->i_number == block->TrackNum() )
4289 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
4291 if( i_track < tracks.size() )
4293 if( sys.i_pts >= sys.i_start_pts )
4295 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4296 i_track_skipping = 0;
4298 else if( tk->fmt.i_cat == VIDEO_ES )
4300 if( i_block_ref1 == -1 && tk->b_search_keyframe )
4302 tk->b_search_keyframe = VLC_FALSE;
4305 if( !tk->b_search_keyframe )
4307 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4317 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
4319 demux_sys_t *p_sys = demuxer.p_sys;
4322 // find the actual time for an ordered edition
4323 if ( psz_chapter == NULL )
4325 if ( Edition() && Edition()->b_ordered )
4327 /* 1st, we need to know in which chapter we are */
4328 psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
4332 if ( psz_chapter != NULL )
4334 psz_current_chapter = psz_chapter;
4335 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
4336 if ( psz_chapter->i_seekpoint_num > 0 )
4338 demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
4339 demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
4340 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
4344 // find the best matching segment
4345 for ( i=0; i<linked_segments.size(); i++ )
4347 if ( i_date < linked_segments[i]->i_start_time )
4354 if ( i_current_segment != i )
4356 linked_segments[i_current_segment]->UnSelect();
4357 linked_segments[i]->Select( i_date );
4358 i_current_segment = i;
4361 linked_segments[i]->Seek( i_date, i_time_offset );
4364 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
4368 uint32 codec_time = uint32(-1);
4369 for( i = 0; i < command.ListSize(); i++ )
4371 const EbmlElement *k = command[i];
4373 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
4375 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
4380 for( i = 0; i < command.ListSize(); i++ )
4382 const EbmlElement *k = command[i];
4384 if( MKV_IS_ID( k, KaxChapterProcessData ) )
4386 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4387 switch ( codec_time )
4390 during_cmds.push_back( *p_data );
4393 enter_cmds.push_back( *p_data );
4396 leave_cmds.push_back( *p_data );
4405 bool chapter_item_c::Enter( bool b_do_subs )
4407 bool f_result = false;
4408 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4409 while ( index != codecs.end() )
4411 f_result |= (*index)->Enter();
4418 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4419 while ( index_ != sub_chapters.end() )
4421 f_result |= (*index_)->Enter( true );
4428 bool chapter_item_c::Leave( bool b_do_subs )
4430 bool f_result = false;
4431 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4432 while ( index != codecs.end() )
4434 f_result |= (*index)->Leave();
4441 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4442 while ( index_ != sub_chapters.end() )
4444 f_result |= (*index_)->Leave( true );
4451 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item )
4453 chapter_item_c *p_common_parent = p_item;
4455 // leave, up to a common parent
4456 while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
4458 if ( p_common_parent->Leave( false ) )
4460 p_common_parent = p_common_parent->psz_parent;
4463 // enter from the parent to <this>
4464 if ( p_common_parent != NULL )
4468 for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
4470 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
4472 p_common_parent = p_common_parent->sub_chapters[i];
4477 if ( p_common_parent == this )
4480 if ( p_common_parent->Enter( false ) )
4485 return Enter( true );
4488 bool dvd_chapter_codec_c::Enter()
4490 bool f_result = false;
4491 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4492 while ( index != enter_cmds.end() )
4494 if ( (*index).GetSize() )
4496 binary *p_data = (*index).GetBuffer();
4497 size_t i_size = *p_data++;
4498 // avoid reading too much from the buffer
4499 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4500 for ( ; i_size > 0; i_size--, p_data += 8 )
4502 f_result |= interpretor.Interpret( p_data );
4510 bool dvd_chapter_codec_c::Leave()
4512 bool f_result = false;
4513 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4514 while ( index != leave_cmds.end() )
4516 if ( (*index).GetSize() )
4518 binary *p_data = (*index).GetBuffer();
4519 size_t i_size = *p_data++;
4520 // avoid reading too much from the buffer
4521 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4522 for ( ; i_size > 0; i_size--, p_data += 8 )
4524 f_result |= interpretor.Interpret( p_data );
4532 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
4533 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4538 virtual_segment_c *p_segment;
4539 chapter_item_c *p_chapter;
4540 bool f_result = false;
4541 uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4543 switch ( i_command )
4547 uint8 i_title = p_command[5];
4548 msg_Dbg( &sys.demuxer, "DVD command: JumpTT %d", i_title );
4550 // find in the ChapProcessPrivate matching this Title level
4551 p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
4552 if ( p_chapter != NULL )
4554 // if the segment is not part of the current segment, select the new one
4555 if ( p_segment != sys.p_current_segment )
4557 sys.PreparePlayback( p_segment );
4560 // jump to the location in the found segment
4561 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, NULL );
4562 p_chapter->Enter( true );
4569 case CMD_CALLSS_VTSM:
4571 msg_Dbg( &sys.demuxer, "DVD command: CallSS VTSM" );
4572 switch( (p_command[6] & 0xC0) >> 6 ) {
4574 switch ( p_command[5] )
4577 msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[5]);
4580 msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[5]);
4583 msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[5]);
4586 msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[5]);
4589 msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[5]);
4592 msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[5]);
4595 msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[5]);
4598 msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[5]);
4601 p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_command[5], 1, p_segment );
4602 if ( p_chapter != NULL )
4604 // if the segment is not part of the current segment, select the new one
4605 if ( p_segment != sys.p_current_segment )
4607 sys.PreparePlayback( p_segment );
4610 p_chapter->Enter( true );
4612 // jump to the location in the found segment
4613 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
4618 msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4621 msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4624 msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[3] << 8) + p_command[4], p_command[5]);
4631 msg_Dbg( &sys.demuxer, "DVD command: unsupported %02X %02X %02X %02X %02X %02X %02X %02X"
4647 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4649 if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
4652 if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
4655 uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
4656 uint8 i_title = *(uint8*)p_cookie;
4658 return (i_gtitle == i_title);
4661 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4663 if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 7 )
4666 if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
4669 uint8 i_pgc_type = data.m_private_data.GetBuffer()[3];
4670 uint8 i_pgc = *(uint8*)p_cookie;
4672 return (i_pgc_type == i_pgc);
4675 bool matroska_script_codec_c::Enter()
4677 bool f_result = false;
4678 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4679 while ( index != enter_cmds.end() )
4681 if ( (*index).GetSize() )
4683 f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4690 bool matroska_script_codec_c::Leave()
4692 bool f_result = false;
4693 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4694 while ( index != leave_cmds.end() )
4696 if ( (*index).GetSize() )
4698 f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4705 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript
4706 // for a description of existing commands
4707 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4709 bool b_result = false;
4711 char *psz_str = (char*) malloc( i_size + 1 );
4712 memcpy( psz_str, p_command, i_size );
4713 psz_str[ i_size ] = '\0';
4715 std::string sz_command = psz_str;
4717 msg_Dbg( &sys.demuxer, "Matroska Script command : %s", sz_command.c_str() );
4719 if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
4724 for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
4726 if ( sz_command[i] == '(' )
4733 for ( j=i; j<sz_command.size(); j++)
4735 if ( sz_command[j] == ')' )
4742 std::string st = sz_command.substr( i+1, j-i-1 );
4743 int64_t i_chapter_uid = atoi( st.c_str() );
4745 virtual_segment_c *p_segment;
4746 chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
4748 if ( p_chapter == NULL )
4749 msg_Dbg( &sys.demuxer, "Chapter %d not found", i_chapter_uid);
4752 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );