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;
333 class chapter_codec_cmds_c
336 void SetPrivate( const KaxChapterProcessPrivate & private_data )
338 m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
341 void AddCommand( const KaxChapterProcessCommand & command );
343 virtual bool Enter() { return true; }
344 virtual bool Leave() { return true; }
347 KaxChapterProcessPrivate m_private_data;
349 std::vector<KaxChapterProcessData> enter_cmds;
350 std::vector<KaxChapterProcessData> during_cmds;
351 std::vector<KaxChapterProcessData> leave_cmds;
354 class dvd_command_interpretor_c
357 dvd_command_interpretor_c()
359 memset( p_GPRM, 0, sizeof(p_GPRM) );
360 memset( p_SPRM, 0, sizeof(p_SPRM) );
367 p_SPRM[ 16 ] = 0xFFFFu;
368 p_SPRM[ 18 ] = 0xFFFFu;
371 bool Interpret( const binary * p_command, size_t i_size = 8 );
374 uint16 GetGPRM( size_t index ) const
376 if ( index >= 0 && index < 16 )
377 return p_GPRM[ index ];
381 uint16 GetSPRM( size_t index ) const
383 // 21,22,23 reserved for future use
384 if ( index >= 0 && index < 21 )
385 return p_SPRM[ index ];
389 bool SetGPRM( size_t index, uint16 value )
391 if ( index >= 0 && index < 16 )
393 p_GPRM[ index ] = value;
399 bool SetSPRM( size_t index, uint16 value )
401 if ( index > 0 && index <= 13 && index != 12 )
403 p_SPRM[ index ] = value;
412 static const uint16 CMD_JUMP_TT = 0x3002;
415 class dvd_chapter_codec_c : public chapter_codec_cmds_c
422 dvd_command_interpretor_c interpretor;
425 class matroska_script_codec_c : public chapter_codec_cmds_c
429 class chapter_translation_c
432 KaxChapterTranslateID translated;
433 unsigned int codec_id;
434 std::vector<uint64_t> editions;
443 ,i_user_start_time(-1)
446 ,b_display_seekpoint(true)
452 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
453 while ( index != codecs.end() )
458 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
459 while ( index_ != sub_chapters.end() )
466 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
467 void PublishChapters( input_title_t & title, int i_level );
468 chapter_item_c * FindTimecode( mtime_t i_timecode );
469 void Append( const chapter_item_c & edition );
470 chapter_item_c * FindChapter( const chapter_item_c & chapter );
472 int64_t i_start_time, i_end_time;
473 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
474 std::vector<chapter_item_c*> sub_chapters;
477 bool b_display_seekpoint;
478 std::string psz_name;
479 chapter_item_c *psz_parent;
481 std::vector<chapter_codec_cmds_c*> codecs;
483 bool operator<( const chapter_item_c & item ) const
485 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) );
492 class chapter_edition_c : public chapter_item_c
499 void RefreshChapters( );
500 mtime_t Duration() const;
501 void PublishChapters( input_title_t & title );
508 class matroska_segment_c
511 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
514 ,i_timescale(MKVD_TIMECODESCALE)
518 ,i_chapters_position(-1)
525 ,psz_muxing_application(NULL)
526 ,psz_writing_application(NULL)
527 ,psz_segment_filename(NULL)
530 ,i_default_edition(0)
535 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
538 virtual ~matroska_segment_c()
540 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
542 #define tk tracks[i_track]
543 if( tk->fmt.psz_description )
545 free( tk->fmt.psz_description );
549 free( tk->psz_codec );
551 if( tk->fmt.psz_language )
553 free( tk->fmt.psz_language );
559 if( psz_writing_application )
561 free( psz_writing_application );
563 if( psz_muxing_application )
565 free( psz_muxing_application );
567 if( psz_segment_filename )
569 free( psz_segment_filename );
577 free( psz_date_utc );
584 std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
585 while ( index != stored_editions.end() )
596 uint64_t i_timescale;
598 /* duration of the segment */
600 mtime_t i_start_time;
603 std::vector<mkv_track_t*> tracks;
606 int64_t i_cues_position;
607 int64_t i_chapters_position;
608 int64_t i_tags_position;
612 KaxSegmentUID segment_uid;
613 KaxPrevUID prev_segment_uid;
614 KaxNextUID next_segment_uid;
622 char *psz_muxing_application;
623 char *psz_writing_application;
624 char *psz_segment_filename;
628 std::vector<chapter_edition_c*> stored_editions;
629 int i_default_edition;
631 std::vector<chapter_translation_c> translations;
632 std::vector<KaxSegmentFamily> families;
639 bool PreloadFamily( const matroska_segment_c & segment );
640 void ParseInfo( KaxInfo *info );
641 void ParseChapters( KaxChapters *chapters );
642 void ParseSeekHead( KaxSeekHead *seekhead );
643 void ParseTracks( KaxTracks *tracks );
644 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
645 void ParseTrackEntry( KaxTrackEntry *m );
646 void ParseCluster( );
647 void IndexAppendCluster( KaxCluster *cluster );
650 void InformationCreate( );
651 void Seek( mtime_t i_date, mtime_t i_time_offset );
652 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
653 bool Select( mtime_t i_start_time );
655 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
658 // class holding hard-linked segment together in the playback order
659 class virtual_segment_c
662 virtual_segment_c( matroska_segment_c *p_segment )
663 :i_current_segment(0)
665 ,i_current_edition(-1)
666 ,psz_current_chapter(NULL)
668 linked_segments.push_back( p_segment );
670 AppendUID( p_segment->segment_uid );
671 AppendUID( p_segment->prev_segment_uid );
672 AppendUID( p_segment->next_segment_uid );
676 size_t AddSegment( matroska_segment_c *p_segment );
677 void PreloadLinked( );
678 mtime_t Duration( ) const;
680 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
682 inline chapter_edition_c *Edition()
684 if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
685 return (*p_editions)[i_current_edition];
689 inline bool EditionIsOrdered() const
691 return (p_editions->size() != 0 && i_current_edition >= 0 && (*p_editions)[i_current_edition]->b_ordered);
694 matroska_segment_c * Segment() const
696 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
698 return linked_segments[i_current_segment];
701 inline const chapter_item_c *CurrentChapter() const {
702 return psz_current_chapter;
707 if ( i_current_segment < linked_segments.size()-1 )
715 /* TODO handle/merge chapters here */
716 void UpdateCurrentToChapter( demux_t & demux );
717 bool Select( input_title_t & title );
720 std::vector<matroska_segment_c*> linked_segments;
721 std::vector<KaxSegmentUID> linked_uids;
722 size_t i_current_segment;
724 std::vector<chapter_edition_c*> *p_editions;
725 int i_current_edition;
726 chapter_item_c *psz_current_chapter;
728 void AppendUID( const EbmlBinary & UID );
731 class matroska_stream_c
734 matroska_stream_c( demux_sys_t & demuxer )
740 virtual ~matroska_stream_c()
749 std::vector<matroska_segment_c*> segments;
757 demux_sys_t( demux_t & demux )
764 ,p_current_segment(NULL)
768 virtual ~demux_sys_t()
770 for (size_t i=0; i<streams.size(); i++)
772 for ( size_t i=0; i<opened_segments.size(); i++ )
773 delete opened_segments[i];
781 mtime_t i_chapter_time;
785 input_title_t *title;
787 std::vector<matroska_stream_c*> streams;
788 std::vector<matroska_segment_c*> opened_segments;
789 virtual_segment_c *p_current_segment;
791 /* duration of the stream */
794 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
795 void PreloadFamily( const matroska_segment_c & of_segment );
796 void PreloadLinked( matroska_segment_c *p_segment );
797 bool PreparePlayback( );
798 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
801 static int Demux ( demux_t * );
802 static int Control( demux_t *, int, va_list );
803 static void Seek ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
805 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
807 static char *UTF8ToStr ( const UTFstring &u );
809 /*****************************************************************************
810 * Open: initializes matroska demux structures
811 *****************************************************************************/
812 static int Open( vlc_object_t * p_this )
814 demux_t *p_demux = (demux_t*)p_this;
816 matroska_stream_c *p_stream;
817 matroska_segment_c *p_segment;
819 std::string s_path, s_filename;
820 vlc_stream_io_callback *p_io_callback;
821 EbmlStream *p_io_stream;
823 /* peek the begining */
824 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
826 /* is a valid file */
827 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
828 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
830 /* Set the demux function */
831 p_demux->pf_demux = Demux;
832 p_demux->pf_control = Control;
833 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
835 p_io_callback = new vlc_stream_io_callback( p_demux->s );
836 p_io_stream = new EbmlStream( *p_io_callback );
838 if( p_io_stream == NULL )
840 msg_Err( p_demux, "failed to create EbmlStream" );
841 delete p_io_callback;
846 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
847 if( p_stream == NULL )
849 msg_Err( p_demux, "cannot find KaxSegment" );
852 p_sys->streams.push_back( p_stream );
854 p_stream->p_in = p_io_callback;
855 p_stream->p_es = p_io_stream;
857 for (size_t i=0; i<p_stream->segments.size(); i++)
859 p_stream->segments[i]->Preload();
862 p_segment = p_stream->segments[0];
863 if( p_segment->cluster != NULL )
865 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
867 // reset the stream reading to the first cluster of the segment used
868 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
871 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
872 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
874 // assume it's a regular file
875 // get the directory path
876 s_path = p_demux->psz_path;
877 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
879 s_path = s_path.substr(0,s_path.length()-1);
883 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
885 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
889 struct dirent *p_file_item;
890 DIR *p_src_dir = opendir(s_path.c_str());
892 if (p_src_dir != NULL)
894 while ((p_file_item = (dirent *) readdir(p_src_dir)))
896 if (strlen(p_file_item->d_name) > 4)
898 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
900 if (!s_filename.compare(p_demux->psz_path))
901 continue; // don't reuse the original opened file
903 #if defined(__GNUC__) && (__GNUC__ < 3)
904 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
905 !s_filename.compare("mka", s_filename.length() - 3, 3))
907 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
908 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
911 // test wether this file belongs to the our family
912 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
913 EbmlStream *p_estream = new EbmlStream(*p_file_io);
915 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
916 if ( p_stream == NULL )
918 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
924 p_stream->p_in = p_file_io;
925 p_stream->p_es = p_estream;
926 p_sys->streams.push_back( p_stream );
931 closedir( p_src_dir );
935 p_sys->PreloadFamily( *p_segment );
936 p_sys->PreloadLinked( p_segment );
937 if ( !p_sys->PreparePlayback( ) )
939 msg_Err( p_demux, "cannot use the segment" );
950 /*****************************************************************************
951 * Close: frees unused data
952 *****************************************************************************/
953 static void Close( vlc_object_t *p_this )
955 demux_t *p_demux = (demux_t*)p_this;
956 demux_sys_t *p_sys = p_demux->p_sys;
961 /*****************************************************************************
963 *****************************************************************************/
964 static int Control( demux_t *p_demux, int i_query, va_list args )
966 demux_sys_t *p_sys = p_demux->p_sys;
971 vlc_meta_t **pp_meta;
976 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
977 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
980 case DEMUX_GET_LENGTH:
981 pi64 = (int64_t*)va_arg( args, int64_t * );
982 if( p_sys->f_duration > 0.0 )
984 *pi64 = (int64_t)(p_sys->f_duration * 1000);
989 case DEMUX_GET_POSITION:
990 pf = (double*)va_arg( args, double * );
991 if ( p_sys->f_duration > 0.0 )
992 *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);
995 case DEMUX_SET_POSITION:
996 f = (double)va_arg( args, double );
997 Seek( p_demux, -1, f, NULL );
1000 case DEMUX_GET_TIME:
1001 pi64 = (int64_t*)va_arg( args, int64_t * );
1002 *pi64 = p_sys->i_pts;
1005 case DEMUX_GET_TITLE_INFO:
1006 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1008 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1009 int *pi_int = (int*)va_arg( args, int* );
1012 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1014 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1018 return VLC_EGENERIC;
1020 case DEMUX_SET_TITLE:
1021 /* TODO handle editions as titles & DVD titles as well */
1022 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1026 return VLC_EGENERIC;
1028 case DEMUX_SET_SEEKPOINT:
1029 /* FIXME do a better implementation */
1030 i_skp = (int)va_arg( args, int );
1032 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1034 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1035 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1036 p_demux->info.i_seekpoint = i_skp;
1039 return VLC_EGENERIC;
1041 case DEMUX_SET_TIME:
1044 return VLC_EGENERIC;
1048 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1060 i_level = ep->GetLevel();
1062 if( el == NULL && *pp_block != NULL )
1064 /* update the index */
1065 #define idx index[i_index - 1]
1066 if( i_index > 0 && idx.i_time == -1 )
1068 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1069 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1077 if( ep->GetLevel() > 1 )
1082 msg_Warn( &sys.demuxer, "EOF" );
1083 return VLC_EGENERIC;
1089 if( MKV_IS_ID( el, KaxCluster ) )
1091 cluster = (KaxCluster*)el;
1093 /* add it to the index */
1095 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1097 IndexAppendCluster( cluster );
1100 // reset silent tracks
1101 for (size_t i=0; i<tracks.size(); i++)
1103 tracks[i]->b_silent = VLC_FALSE;
1108 else if( MKV_IS_ID( el, KaxCues ) )
1110 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1111 return VLC_EGENERIC;
1115 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1118 else if( i_level == 2 )
1120 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1122 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1124 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1125 cluster->InitTimecode( uint64( ctc ), i_timescale );
1127 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1131 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1136 else if( i_level == 3 )
1138 if( MKV_IS_ID( el, KaxBlock ) )
1140 *pp_block = (KaxBlock*)el;
1142 (*pp_block)->ReadData( es.I_O() );
1143 (*pp_block)->SetParent( *cluster );
1147 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1149 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1151 dur.ReadData( es.I_O() );
1152 *pi_duration = uint64( dur );
1154 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1156 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1158 ref.ReadData( es.I_O() );
1159 if( *pi_ref1 == -1 )
1161 *pi_ref1 = int64( ref );
1165 *pi_ref2 = int64( ref );
1168 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1170 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1171 track_num.ReadData( es.I_O() );
1173 for (size_t i=0; i<tracks.size(); i++)
1175 if ( tracks[i]->i_number == uint32(track_num))
1177 tracks[i]->b_silent = VLC_TRUE;
1185 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1186 return VLC_EGENERIC;
1191 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1194 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1195 memcpy( p_block->p_buffer, p_mem, i_mem );
1196 //p_block->i_rate = p_input->stream.control.i_rate;
1200 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1201 mtime_t i_duration )
1203 demux_sys_t *p_sys = p_demux->p_sys;
1204 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1210 #define tk p_segment->tracks[i_track]
1211 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1213 if( tk->i_number == block->TrackNum() )
1219 if( i_track >= p_segment->tracks.size() )
1221 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1224 if( tk->p_es == NULL )
1226 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1229 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1231 return; /* discard audio packets that shouldn't be rendered */
1234 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1237 tk->b_inited = VLC_FALSE;
1241 /* First send init data */
1242 if( !tk->b_inited && tk->i_data_init > 0 )
1246 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1247 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1248 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1250 tk->b_inited = VLC_TRUE;
1253 for( i = 0; i < block->NumberFrames(); i++ )
1256 DataBuffer &data = block->GetBuffer(i);
1258 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1260 if( p_block == NULL )
1265 #if defined(HAVE_ZLIB_H)
1266 if( tk->i_compression_type )
1268 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1272 // TODO implement correct timestamping when B frames are used
1273 if( tk->fmt.i_cat != VIDEO_ES )
1275 p_block->i_dts = p_block->i_pts = i_pts;
1279 p_block->i_dts = i_pts;
1283 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1285 p_block->i_length = i_duration * 1000;
1288 es_out_Send( p_demux->out, tk->p_es, p_block );
1290 /* use time stamp only for first block */
1297 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1299 int i_upper_lvl = 0;
1301 EbmlElement *p_l0, *p_l1, *p_l2;
1302 bool b_keep_stream = false, b_keep_segment;
1304 // verify the EBML Header
1305 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1310 p_l0->SkipData(*p_estream, EbmlHead_Context);
1313 // find all segments in this file
1314 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1320 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1324 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1327 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1328 b_keep_segment = false;
1330 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1331 p_segment1->ep = ep;
1332 p_segment1->segment = (KaxSegment*)p_l0;
1334 while ((p_l1 = ep->Get()))
1336 if (MKV_IS_ID(p_l1, KaxInfo))
1338 // find the families of this segment
1339 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1341 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1342 for( i = 0; i < p_info->ListSize(); i++ )
1344 EbmlElement *l = (*p_info)[i];
1346 if( MKV_IS_ID( l, KaxSegmentUID ) )
1348 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1349 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1350 if ( !b_keep_segment )
1351 break; // this segment is already known
1352 opened_segments.push_back( p_segment1 );
1353 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1355 else if( MKV_IS_ID( l, KaxPrevUID ) )
1357 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1359 else if( MKV_IS_ID( l, KaxNextUID ) )
1361 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1363 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1365 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1366 p_segment1->families.push_back( *p_fam );
1372 if ( b_keep_segment )
1374 b_keep_stream = true;
1375 p_stream1->segments.push_back( p_segment1 );
1381 p_l0->SkipData(*p_estream, EbmlHead_Context);
1382 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1385 if ( !b_keep_stream )
1394 bool matroska_segment_c::Select( mtime_t i_start_time )
1399 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1400 for( i_track = 0; i_track < tracks.size(); i_track++ )
1402 #define tk tracks[i_track]
1403 if( tk->fmt.i_cat == UNKNOWN_ES )
1405 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1410 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1412 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1414 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1415 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1419 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1421 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1422 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1423 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1425 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1426 if( tk->fmt.i_extra > 0 )
1428 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1429 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1433 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1434 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1436 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1438 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1440 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1442 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1444 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1446 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1447 tk->fmt.b_packetized = VLC_FALSE;
1448 tk->fmt.i_extra = tk->i_extra_data;
1449 tk->fmt.p_extra = malloc( tk->i_extra_data );
1450 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1454 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1457 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1459 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1461 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1465 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1470 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1471 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1472 tk->fmt.i_codec = p_box->i_type;
1473 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1474 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1475 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1476 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1477 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1478 MP4_FreeBox_sample_vide( p_box );
1480 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1482 stream_Delete( p_mp4_stream );
1485 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1487 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1489 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1490 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1494 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1496 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1498 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1499 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1500 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1501 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1502 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1504 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1505 if( tk->fmt.i_extra > 0 )
1507 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1508 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1512 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1513 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1514 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1516 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1518 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1520 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1522 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1524 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1526 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1528 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1529 tk->fmt.i_extra = tk->i_extra_data;
1530 tk->fmt.p_extra = malloc( tk->i_extra_data );
1531 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1533 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1535 int i, i_offset = 1, i_size[3], i_extra;
1538 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1540 /* Split the 3 headers */
1541 if( tk->p_extra_data[0] != 0x02 )
1542 msg_Err( &sys.demuxer, "invalid vorbis header" );
1544 for( i = 0; i < 2; i++ )
1547 while( i_offset < tk->i_extra_data )
1549 i_size[i] += tk->p_extra_data[i_offset];
1550 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1554 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1555 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1556 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1558 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1559 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1560 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1561 for( i = 0; i < 3; i++ )
1563 *(p_extra++) = i_size[i] >> 8;
1564 *(p_extra++) = i_size[i] & 0xFF;
1565 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1567 p_extra += i_size[i];
1568 i_extra += i_size[i];
1571 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1572 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1574 int i_profile, i_srate;
1575 static unsigned int i_sample_rates[] =
1577 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1578 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1581 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1582 /* create data for faad (MP4DecSpecificDescrTag)*/
1584 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1588 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1592 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1601 for( i_srate = 0; i_srate < 13; i_srate++ )
1603 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1608 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1610 tk->fmt.i_extra = 2;
1611 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1612 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1613 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1615 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1616 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1617 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1619 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1621 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1625 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1627 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1629 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1631 /* FIXME: support this codec */
1632 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1633 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1635 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1637 /* FIXME: support this codec */
1638 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1639 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1641 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1643 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1644 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1646 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1647 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1648 !strcmp( tk->psz_codec, "S_SSA" ) ||
1649 !strcmp( tk->psz_codec, "S_ASS" ))
1651 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1652 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1654 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1656 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1657 if( tk->i_extra_data )
1660 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1661 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1662 p_buf[tk->i_extra_data] = '\0';
1664 p_start = strstr( p_buf, "size:" );
1665 if( sscanf( p_start, "size: %dx%d",
1666 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1668 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 );
1672 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1677 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1679 /* FIXME: support this codec */
1680 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1681 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1685 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1686 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1690 tk->fmt.i_priority = 1000;
1693 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1695 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1699 sys.i_start_pts = i_start_time;
1700 // reset the stream reading to the first cluster of the segment used
1701 es.I_O().setFilePointer( i_start_pos );
1704 ep = new EbmlParser( &es, segment, &sys.demuxer );
1709 void matroska_segment_c::UnSelect( )
1713 for( i_track = 0; i_track < tracks.size(); i_track++ )
1715 #define tk tracks[i_track]
1716 if ( tk->p_es != NULL )
1718 es_out_Del( sys.demuxer.out, tk->p_es );
1727 bool virtual_segment_c::Select( input_title_t & title )
1729 if ( linked_segments.size() == 0 )
1732 // !!! should be called only once !!!
1733 matroska_segment_c *p_segment;
1736 // copy editions from the first segment
1737 p_segment = linked_segments[0];
1738 p_editions = &p_segment->stored_editions;
1740 for ( i=1 ; i<linked_segments.size(); i++ )
1742 p_segment = linked_segments[i];
1743 // FIXME assume we have the same editions in all segments
1744 for (j=0; j<p_segment->stored_editions.size(); j++)
1745 (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
1748 if ( Edition() != NULL )
1749 Edition()->PublishChapters( title );
1754 void chapter_edition_c::PublishChapters( input_title_t & title )
1756 title.i_seekpoint = 0;
1757 if ( title.seekpoint != NULL )
1758 free( title.seekpoint );
1759 chapter_item_c::PublishChapters( title, 0 );
1762 void chapter_item_c::PublishChapters( input_title_t & title, int i_level )
1764 if (b_display_seekpoint)
1766 seekpoint_t *sk = vlc_seekpoint_New();
1768 sk->i_level = i_level;
1769 sk->i_time_offset = i_start_time;
1770 sk->psz_name = strdup( psz_name.c_str() );
1772 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1773 title.i_seekpoint++;
1774 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1775 title.seekpoint[title.i_seekpoint-1] = sk;
1777 i_seekpoint_num = title.i_seekpoint;
1780 for ( size_t i=0; i<sub_chapters.size() ; i++)
1782 sub_chapters[i]->PublishChapters( title, i_level+1 );
1786 void virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1788 demux_sys_t & sys = *demux.p_sys;
1789 chapter_item_c *psz_curr_chapter;
1791 /* update current chapter/seekpoint */
1792 if ( p_editions->size() )
1794 /* 1st, we need to know in which chapter we are */
1795 psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
1797 /* we have moved to a new chapter */
1798 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1800 if ( psz_current_chapter != NULL )
1801 psz_current_chapter->Leave();
1803 if ( psz_curr_chapter->i_seekpoint_num > 0 )
1805 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1806 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1809 if ( (*p_editions)[i_current_edition]->b_ordered )
1811 psz_curr_chapter->Enter();
1813 // only seek if necessary
1814 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1815 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1818 psz_current_chapter = psz_curr_chapter;
1822 void chapter_item_c::Append( const chapter_item_c & chapter )
1824 // we are appending content for the same chapter UID
1826 chapter_item_c *p_chapter;
1828 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1830 p_chapter = FindChapter( *chapter.sub_chapters[i] );
1831 if ( p_chapter != NULL )
1833 p_chapter->Append( *chapter.sub_chapters[i] );
1837 sub_chapters.push_back( chapter.sub_chapters[i] );
1841 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1842 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1845 chapter_item_c * chapter_item_c::FindChapter( const chapter_item_c & chapter )
1848 for ( i=0; i<sub_chapters.size(); i++)
1850 if ( sub_chapters[i]->i_uid == chapter.i_uid )
1851 return sub_chapters[i];
1856 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
1858 demux_sys_t *p_sys = p_demux->p_sys;
1859 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1860 matroska_segment_c *p_segment = p_vsegment->Segment();
1861 mtime_t i_time_offset = 0;
1865 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1866 if( i_date < 0 && f_percent < 0 )
1868 msg_Warn( p_demux, "cannot seek nowhere !" );
1871 if( f_percent > 1.0 )
1873 msg_Warn( p_demux, "cannot seek so far !" );
1877 /* seek without index or without date */
1878 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1880 if (p_sys->f_duration >= 0)
1882 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1886 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1888 msg_Dbg( p_demux, "inacurate way of seeking" );
1889 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1891 if( p_segment->index[i_index].i_position >= i_pos)
1896 if( i_index == p_segment->i_index )
1901 i_date = p_segment->index[i_index].i_time;
1904 if( p_segment->index[i_index].i_position < i_pos )
1908 msg_Warn( p_demux, "searching for cluster, could take some time" );
1910 /* search a cluster */
1911 while( ( el = p_sys->ep->Get() ) != NULL )
1913 if( MKV_IS_ID( el, KaxCluster ) )
1915 KaxCluster *cluster = (KaxCluster*)el;
1917 /* add it to the index */
1918 p_segment->IndexAppendCluster( cluster );
1920 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1922 p_sys->cluster = cluster;
1933 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1936 /*****************************************************************************
1937 * Demux: reads and demuxes data packets
1938 *****************************************************************************
1939 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1940 *****************************************************************************/
1941 static int Demux( demux_t *p_demux)
1943 demux_sys_t *p_sys = p_demux->p_sys;
1944 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1945 matroska_segment_c *p_segmet = p_vsegment->Segment();
1946 if ( p_segmet == NULL ) return 0;
1947 int i_block_count = 0;
1950 int64_t i_block_duration;
1951 int64_t i_block_ref1;
1952 int64_t i_block_ref2;
1956 if ( p_sys->demuxer.b_die )
1959 if( p_sys->i_pts >= p_sys->i_start_pts )
1960 p_vsegment->UpdateCurrentToChapter( *p_demux );
1962 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1964 /* nothing left to read in this ordered edition */
1965 if ( !p_vsegment->SelectNext() )
1967 p_segmet->UnSelect( );
1969 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1971 /* switch to the next segment */
1972 p_segmet = p_vsegment->Segment();
1973 if ( !p_segmet->Select( 0 ) )
1975 msg_Err( p_demux, "Failed to select new segment" );
1982 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1984 if ( p_vsegment->EditionIsOrdered() )
1986 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
1987 // check if there are more chapters to read
1988 if ( p_chap != NULL )
1990 /* TODO handle successive chapters with the same user_start_time/user_end_time
1991 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
1992 p_vsegment->SelectNext();
1994 p_sys->i_pts = p_chap->i_user_end_time;
1995 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2002 msg_Warn( p_demux, "cannot get block EOF?" );
2003 p_segmet->UnSelect( );
2005 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2007 /* switch to the next segment */
2008 if ( !p_vsegment->SelectNext() )
2009 // no more segments in this stream
2011 p_segmet = p_vsegment->Segment();
2012 if ( !p_segmet->Select( 0 ) )
2014 msg_Err( p_demux, "Failed to select new segment" );
2021 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2023 if( p_sys->i_pts >= p_sys->i_start_pts )
2025 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2028 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2033 // TODO optimize when there is need to leave or when seeking has been called
2034 if( i_block_count > 5 )
2043 /*****************************************************************************
2045 *****************************************************************************/
2046 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2052 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2054 if( i_size <= 0 || mb_eof )
2059 return stream_Read( s, p_buffer, i_size );
2061 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2067 case seek_beginning:
2071 i_pos = stream_Size( s ) - i_offset;
2074 i_pos= stream_Tell( s ) + i_offset;
2078 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2085 if( stream_Seek( s, i_pos ) )
2091 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2095 uint64 vlc_stream_io_callback::getFilePointer( void )
2097 return stream_Tell( s );
2099 void vlc_stream_io_callback::close( void )
2105 /*****************************************************************************
2106 * Ebml Stream parser
2107 *****************************************************************************/
2108 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2115 mi_remain_size[0] = el_start->GetSize();
2117 for( i = 1; i < 6; i++ )
2123 mb_keep = VLC_FALSE;
2124 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2127 EbmlParser::~EbmlParser( void )
2131 for( i = 1; i < mi_level; i++ )
2137 mb_keep = VLC_FALSE;
2141 void EbmlParser::Up( void )
2143 if( mi_user_level == mi_level )
2145 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2151 void EbmlParser::Down( void )
2157 void EbmlParser::Keep( void )
2162 int EbmlParser::GetLevel( void )
2164 return mi_user_level;
2167 void EbmlParser::Reset( demux_t *p_demux )
2169 while ( mi_level > 0)
2171 delete m_el[mi_level];
2172 m_el[mi_level] = NULL;
2175 mi_user_level = mi_level = 1;
2176 #if LIBEBML_VERSION >= 0x000704
2177 // a little faster and cleaner
2178 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2180 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2182 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2185 EbmlElement *EbmlParser::Get( void )
2189 if( mi_user_level != mi_level )
2195 EbmlElement *ret = m_got;
2201 if( m_el[mi_level] )
2203 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2206 delete m_el[mi_level];
2208 mb_keep = VLC_FALSE;
2211 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2212 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2223 delete m_el[mi_level - 1];
2224 m_got = m_el[mi_level -1] = m_el[mi_level];
2225 m_el[mi_level] = NULL;
2232 else if( m_el[mi_level] == NULL )
2234 fprintf( stderr," m_el[mi_level] == NULL\n" );
2237 return m_el[mi_level];
2241 /*****************************************************************************
2243 * * LoadCues : load the cues element and update index
2245 * * LoadTags : load ... the tags element
2247 * * InformationCreate : create all information, load tags if present
2249 *****************************************************************************/
2250 void matroska_segment_c::LoadCues( )
2252 int64_t i_sav_position = es.I_O().getFilePointer();
2254 EbmlElement *el, *cues;
2256 /* *** Load the cue if found *** */
2257 if( i_cues_position < 0 )
2259 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2261 // IndexAppendCluster( cluster );
2264 vlc_bool_t b_seekable;
2266 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2270 msg_Dbg( &sys.demuxer, "loading cues" );
2271 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2272 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2276 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2277 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2281 ep = new EbmlParser( &es, cues, &sys.demuxer );
2282 while( ( el = ep->Get() ) != NULL )
2284 if( MKV_IS_ID( el, KaxCuePoint ) )
2286 #define idx index[i_index]
2289 idx.i_block_number= -1;
2290 idx.i_position = -1;
2292 idx.b_key = VLC_TRUE;
2295 while( ( el = ep->Get() ) != NULL )
2297 if( MKV_IS_ID( el, KaxCueTime ) )
2299 KaxCueTime &ctime = *(KaxCueTime*)el;
2301 ctime.ReadData( es.I_O() );
2303 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2305 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2308 while( ( el = ep->Get() ) != NULL )
2310 if( MKV_IS_ID( el, KaxCueTrack ) )
2312 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2314 ctrack.ReadData( es.I_O() );
2315 idx.i_track = uint16( ctrack );
2317 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2319 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2321 ccpos.ReadData( es.I_O() );
2322 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2324 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2326 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2328 cbnum.ReadData( es.I_O() );
2329 idx.i_block_number = uint32( cbnum );
2333 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2340 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2346 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2347 " track=%d bnum=%d", idx.i_time, idx.i_position,
2348 idx.i_track, idx.i_block_number );
2352 if( i_index >= i_index_max )
2354 i_index_max += 1024;
2355 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2361 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2369 msg_Dbg( &sys.demuxer, "loading cues done." );
2370 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2373 void matroska_segment_c::LoadTags( )
2375 int64_t i_sav_position = es.I_O().getFilePointer();
2377 EbmlElement *el, *tags;
2379 msg_Dbg( &sys.demuxer, "loading tags" );
2380 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2381 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2385 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2386 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2390 msg_Dbg( &sys.demuxer, "Tags" );
2391 ep = new EbmlParser( &es, tags, &sys.demuxer );
2392 while( ( el = ep->Get() ) != NULL )
2394 if( MKV_IS_ID( el, KaxTag ) )
2396 msg_Dbg( &sys.demuxer, "+ Tag" );
2398 while( ( el = ep->Get() ) != NULL )
2400 if( MKV_IS_ID( el, KaxTagTargets ) )
2402 msg_Dbg( &sys.demuxer, "| + Targets" );
2404 while( ( el = ep->Get() ) != NULL )
2406 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2410 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2412 msg_Dbg( &sys.demuxer, "| + General" );
2414 while( ( el = ep->Get() ) != NULL )
2416 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2420 else if( MKV_IS_ID( el, KaxTagGenres ) )
2422 msg_Dbg( &sys.demuxer, "| + Genres" );
2424 while( ( el = ep->Get() ) != NULL )
2426 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2430 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2432 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2434 while( ( el = ep->Get() ) != NULL )
2436 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2440 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2442 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2444 while( ( el = ep->Get() ) != NULL )
2446 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2450 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2452 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2454 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2456 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2458 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2460 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2462 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2464 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2466 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2468 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2470 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2472 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2474 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2476 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2480 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2487 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2493 msg_Dbg( &sys.demuxer, "loading tags done." );
2494 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2497 /*****************************************************************************
2499 *****************************************************************************/
2500 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2504 int i_upper_level = 0;
2506 msg_Dbg( &sys.demuxer, "| + Seek head" );
2508 /* Master elements */
2509 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2511 for( i = 0; i < seekhead->ListSize(); i++ )
2513 EbmlElement *l = (*seekhead)[i];
2515 if( MKV_IS_ID( l, KaxSeek ) )
2517 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2518 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2521 for( j = 0; j < sk->ListSize(); j++ )
2523 EbmlElement *l = (*sk)[j];
2525 if( MKV_IS_ID( l, KaxSeekID ) )
2527 KaxSeekID &sid = *(KaxSeekID*)l;
2528 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2530 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2532 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2533 i_pos = uint64( spos );
2537 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2543 if( id == KaxCues::ClassInfos.GlobalId )
2545 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2546 i_cues_position = segment->GetGlobalPosition( i_pos );
2548 else if( id == KaxChapters::ClassInfos.GlobalId )
2550 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2551 i_chapters_position = segment->GetGlobalPosition( i_pos );
2553 else if( id == KaxTags::ClassInfos.GlobalId )
2555 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2556 i_tags_position = segment->GetGlobalPosition( i_pos );
2562 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2567 /*****************************************************************************
2569 *****************************************************************************/
2570 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2576 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2578 tk = new mkv_track_t();
2579 tracks.push_back( tk );
2581 /* Init the track */
2582 memset( tk, 0, sizeof( mkv_track_t ) );
2584 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2585 tk->fmt.psz_language = strdup("English");
2586 tk->fmt.psz_description = NULL;
2588 tk->b_default = VLC_TRUE;
2589 tk->b_enabled = VLC_TRUE;
2590 tk->b_silent = VLC_FALSE;
2591 tk->i_number = tracks.size() - 1;
2592 tk->i_extra_data = 0;
2593 tk->p_extra_data = NULL;
2594 tk->psz_codec = NULL;
2595 tk->i_default_duration = 0;
2596 tk->f_timecodescale = 1.0;
2598 tk->b_inited = VLC_FALSE;
2599 tk->i_data_init = 0;
2600 tk->p_data_init = NULL;
2602 tk->psz_codec_name = NULL;
2603 tk->psz_codec_settings = NULL;
2604 tk->psz_codec_info_url = NULL;
2605 tk->psz_codec_download_url = NULL;
2607 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2609 for( i = 0; i < m->ListSize(); i++ )
2611 EbmlElement *l = (*m)[i];
2613 if( MKV_IS_ID( l, KaxTrackNumber ) )
2615 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2617 tk->i_number = uint32( tnum );
2618 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2620 else if( MKV_IS_ID( l, KaxTrackUID ) )
2622 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2624 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2626 else if( MKV_IS_ID( l, KaxTrackType ) )
2629 KaxTrackType &ttype = *(KaxTrackType*)l;
2631 switch( uint8(ttype) )
2635 tk->fmt.i_cat = AUDIO_ES;
2639 tk->fmt.i_cat = VIDEO_ES;
2641 case track_subtitle:
2642 psz_type = "subtitle";
2643 tk->fmt.i_cat = SPU_ES;
2646 psz_type = "unknown";
2647 tk->fmt.i_cat = UNKNOWN_ES;
2651 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2653 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2655 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2657 // tk->b_enabled = uint32( fenb );
2658 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2659 // uint32( fenb ) );
2661 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2663 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2665 tk->b_default = uint32( fdef );
2666 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2668 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2670 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2672 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2674 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2676 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2678 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2680 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2682 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2684 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2686 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2688 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2690 tk->i_default_duration = uint64(defd);
2691 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2693 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2695 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2697 tk->f_timecodescale = float( ttcs );
2698 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2700 else if( MKV_IS_ID( l, KaxTrackName ) )
2702 KaxTrackName &tname = *(KaxTrackName*)l;
2704 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2705 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2707 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2709 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2711 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2712 msg_Dbg( &sys.demuxer,
2713 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2715 else if( MKV_IS_ID( l, KaxCodecID ) )
2717 KaxCodecID &codecid = *(KaxCodecID*)l;
2719 tk->psz_codec = strdup( string( codecid ).c_str() );
2720 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2722 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2724 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2726 tk->i_extra_data = cpriv.GetSize();
2727 if( tk->i_extra_data > 0 )
2729 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2730 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2732 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2734 else if( MKV_IS_ID( l, KaxCodecName ) )
2736 KaxCodecName &cname = *(KaxCodecName*)l;
2738 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2739 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2741 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2743 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2744 MkvTree( sys.demuxer, 3, "Content Encodings" );
2745 for( j = 0; j < cencs->ListSize(); j++ )
2747 EbmlElement *l2 = (*cencs)[j];
2748 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2750 MkvTree( sys.demuxer, 4, "Content Encoding" );
2751 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2752 for( k = 0; k < cenc->ListSize(); k++ )
2754 EbmlElement *l3 = (*cenc)[k];
2755 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2757 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2758 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2760 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2762 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2763 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2765 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2767 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2768 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2770 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2772 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2773 MkvTree( sys.demuxer, 5, "Content Compression" );
2774 for( n = 0; n < compr->ListSize(); n++ )
2776 EbmlElement *l4 = (*compr)[n];
2777 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2779 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2780 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2781 if( uint32( compalg ) == 0 )
2783 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2788 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2795 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2802 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2807 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2809 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2811 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2812 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2814 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2816 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2818 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2819 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2821 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2823 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2825 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2826 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2828 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2830 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2832 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2834 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2836 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2838 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2840 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2842 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2845 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2848 for( j = 0; j < tkv->ListSize(); j++ )
2850 EbmlElement *l = (*tkv)[j];
2851 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2853 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2855 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2857 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2859 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2861 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2864 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2866 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2868 tk->fmt.video.i_width = uint16( vwidth );
2869 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2871 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2873 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2875 tk->fmt.video.i_height = uint16( vheight );
2876 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2878 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2880 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2882 tk->fmt.video.i_visible_width = uint16( vwidth );
2883 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2885 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2887 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2889 tk->fmt.video.i_visible_height = uint16( vheight );
2890 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2892 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2894 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2896 tk->f_fps = float( vfps );
2897 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2899 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2901 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2903 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2904 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2906 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2908 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2910 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2912 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2914 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2916 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2920 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2923 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2924 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2926 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2928 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2931 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2933 for( j = 0; j < tka->ListSize(); j++ )
2935 EbmlElement *l = (*tka)[j];
2937 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2939 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2941 tk->fmt.audio.i_rate = (int)float( afreq );
2942 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2944 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2946 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2948 tk->fmt.audio.i_channels = uint8( achan );
2949 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2951 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2953 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2955 tk->fmt.audio.i_bitspersample = uint8( abits );
2956 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2960 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2966 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2967 typeid(*l).name() );
2972 /*****************************************************************************
2974 *****************************************************************************/
2975 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
2979 int i_upper_level = 0;
2981 msg_Dbg( &sys.demuxer, "| + Tracks" );
2983 /* Master elements */
2984 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2986 for( i = 0; i < tracks->ListSize(); i++ )
2988 EbmlElement *l = (*tracks)[i];
2990 if( MKV_IS_ID( l, KaxTrackEntry ) )
2992 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
2996 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3001 /*****************************************************************************
3003 *****************************************************************************/
3004 void matroska_segment_c::ParseInfo( KaxInfo *info )
3009 int i_upper_level = 0;
3011 msg_Dbg( &sys.demuxer, "| + Information" );
3013 /* Master elements */
3014 m = static_cast<EbmlMaster *>(info);
3015 m->Read( es, info->Generic().Context, i_upper_level, el, true );
3017 for( i = 0; i < m->ListSize(); i++ )
3019 EbmlElement *l = (*m)[i];
3021 if( MKV_IS_ID( l, KaxSegmentUID ) )
3023 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3025 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3027 else if( MKV_IS_ID( l, KaxPrevUID ) )
3029 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3031 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3033 else if( MKV_IS_ID( l, KaxNextUID ) )
3035 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3037 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3039 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3041 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3043 i_timescale = uint64(tcs);
3045 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3048 else if( MKV_IS_ID( l, KaxDuration ) )
3050 KaxDuration &dur = *(KaxDuration*)l;
3052 i_duration = mtime_t( double( dur ) );
3054 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3057 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3059 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3061 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3063 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3064 psz_muxing_application );
3066 else if( MKV_IS_ID( l, KaxWritingApp ) )
3068 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3070 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3072 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3073 psz_writing_application );
3075 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3077 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3079 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3081 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3082 psz_segment_filename );
3084 else if( MKV_IS_ID( l, KaxTitle ) )
3086 KaxTitle &title = *(KaxTitle*)l;
3088 psz_title = UTF8ToStr( UTFstring( title ) );
3090 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3092 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3094 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3096 families.push_back(*uid);
3098 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3100 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3101 else if( MKV_IS_ID( l, KaxDateUTC ) )
3103 KaxDateUTC &date = *(KaxDateUTC*)l;
3108 i_date = date.GetEpochDate();
3109 memset( buffer, 0, 256 );
3110 if( gmtime_r( &i_date, &tmres ) &&
3111 asctime_r( &tmres, buffer ) )
3113 buffer[strlen( buffer)-1]= '\0';
3114 psz_date_utc = strdup( buffer );
3115 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3119 #if LIBMATROSKA_VERSION >= 0x000704
3120 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3122 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3123 chapter_translation_c translated;
3125 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3126 for( j = 0; j < p_trans->ListSize(); j++ )
3128 EbmlElement *l = (*p_trans)[j];
3130 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3132 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3134 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3136 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3138 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3140 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3144 translations.push_back( translated );
3149 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3153 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3154 i_duration = mtime_t(f_dur);
3158 /*****************************************************************************
3160 *****************************************************************************/
3161 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3165 if( sys.title == NULL )
3167 sys.title = vlc_input_title_New();
3170 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3171 for( i = 0; i < ca->ListSize(); i++ )
3173 EbmlElement *l = (*ca)[i];
3175 if( MKV_IS_ID( l, KaxChapterUID ) )
3177 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3178 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3180 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3182 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3183 chapters.b_display_seekpoint = uint8( flag ) == 0;
3185 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3187 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3189 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3190 chapters.i_start_time = uint64( start ) / I64C(1000);
3192 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3194 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3196 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3197 chapters.i_end_time = uint64( end ) / I64C(1000);
3199 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3201 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3203 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3205 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3206 for( j = 0; j < cd->ListSize(); j++ )
3208 EbmlElement *l= (*cd)[j];
3210 if( MKV_IS_ID( l, KaxChapterString ) )
3214 KaxChapterString &name =*(KaxChapterString*)l;
3215 for (k = 0; k < i_level; k++)
3216 chapters.psz_name += '+';
3217 chapters.psz_name += ' ';
3218 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3220 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3222 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3224 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3225 const char *psz = string( lang ).c_str();
3227 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3229 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3231 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3232 const char *psz = string( ct ).c_str();
3234 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3238 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3240 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3242 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3243 chapter_codec_cmds_c *p_ccodec = NULL;
3245 for( j = 0; j < cp->ListSize(); j++ )
3247 EbmlElement *k= (*cp)[j];
3249 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3251 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3252 if ( uint32(*p_codec_id) == 0 )
3253 p_ccodec = new matroska_script_codec_c();
3254 else if ( uint32(*p_codec_id) == 1 )
3255 p_ccodec = new dvd_chapter_codec_c();
3260 if ( p_ccodec != NULL )
3262 for( j = 0; j < cp->ListSize(); j++ )
3264 EbmlElement *k= (*cp)[j];
3266 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3268 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3269 p_ccodec->SetPrivate( *p_private );
3271 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3273 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3276 chapters.codecs.push_back( p_ccodec );
3279 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3281 chapter_item_c *new_sub_chapter = new chapter_item_c();
3282 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3283 new_sub_chapter->psz_parent = &chapters;
3284 chapters.sub_chapters.push_back( new_sub_chapter );
3289 /*****************************************************************************
3291 *****************************************************************************/
3292 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3296 int i_upper_level = 0;
3299 /* Master elements */
3300 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3302 for( i = 0; i < chapters->ListSize(); i++ )
3304 EbmlElement *l = (*chapters)[i];
3306 if( MKV_IS_ID( l, KaxEditionEntry ) )
3308 chapter_edition_c *p_edition = new chapter_edition_c();
3310 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3312 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3313 for( j = 0; j < E->ListSize(); j++ )
3315 EbmlElement *l = (*E)[j];
3317 if( MKV_IS_ID( l, KaxChapterAtom ) )
3319 chapter_item_c *new_sub_chapter = new chapter_item_c();
3320 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3321 p_edition->sub_chapters.push_back( new_sub_chapter );
3323 else if( MKV_IS_ID( l, KaxEditionUID ) )
3325 p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3327 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3329 p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3331 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3333 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3334 i_default_edition = stored_editions.size();
3338 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3341 stored_editions.push_back( p_edition );
3345 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3349 for( i = 0; i < stored_editions.size(); i++ )
3351 stored_editions[i]->RefreshChapters( );
3354 if ( stored_editions[i_default_edition]->b_ordered )
3356 /* update the duration of the segment according to the sum of all sub chapters */
3357 i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3363 void matroska_segment_c::ParseCluster( )
3368 int i_upper_level = 0;
3370 /* Master elements */
3371 m = static_cast<EbmlMaster *>( cluster );
3372 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3374 for( i = 0; i < m->ListSize(); i++ )
3376 EbmlElement *l = (*m)[i];
3378 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3380 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3382 cluster->InitTimecode( uint64( ctc ), i_timescale );
3387 i_start_time = cluster->GlobalTimecode() / 1000;
3390 /*****************************************************************************
3391 * InformationCreate:
3392 *****************************************************************************/
3393 void matroska_segment_c::InformationCreate( )
3397 sys.meta = vlc_meta_New();
3401 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3405 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3407 if( psz_segment_filename )
3409 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3411 if( psz_muxing_application )
3413 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3415 if( psz_writing_application )
3417 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3420 for( i_track = 0; i_track < tracks.size(); i_track++ )
3422 mkv_track_t *tk = tracks[i_track];
3423 vlc_meta_t *mtk = vlc_meta_New();
3425 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3426 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3427 sys.meta->track[sys.meta->i_track++] = mtk;
3429 if( tk->fmt.psz_description )
3431 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3433 if( tk->psz_codec_name )
3435 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3437 if( tk->psz_codec_settings )
3439 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3441 if( tk->psz_codec_info_url )
3443 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3445 if( tk->psz_codec_download_url )
3447 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3451 if( i_tags_position >= 0 )
3453 vlc_bool_t b_seekable;
3455 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3464 /*****************************************************************************
3466 *****************************************************************************/
3468 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3470 #define idx index[i_index]
3472 idx.i_block_number= -1;
3473 idx.i_position = cluster->GetElementPosition();
3475 idx.b_key = VLC_TRUE;
3478 if( i_index >= i_index_max )
3480 i_index_max += 1024;
3481 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3486 static char * UTF8ToStr( const UTFstring &u )
3495 p = dst = (char*)malloc( i_src + 1);
3514 void chapter_edition_c::RefreshChapters( )
3516 chapter_item_c::RefreshChapters( b_ordered, -1 );
3517 b_display_seekpoint = false;
3520 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3522 int64_t i_user_time = i_prev_user_time;
3524 // first the sub-chapters, and then ourself
3525 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3526 while ( index != sub_chapters.end() )
3528 i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3534 // the ordered chapters always start at zero
3535 if ( i_prev_user_time == -1 )
3537 if ( i_user_time == -1 )
3539 i_prev_user_time = 0;
3542 i_user_start_time = i_prev_user_time;
3543 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3545 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3549 i_user_end_time = i_user_time;
3554 std::sort( sub_chapters.begin(), sub_chapters.end() );
3555 i_user_start_time = i_start_time;
3556 if ( i_end_time != -1 )
3557 i_user_end_time = i_end_time;
3558 else if ( i_user_time != -1 )
3559 i_user_end_time = i_user_time;
3561 i_user_end_time = i_user_start_time;
3564 return i_user_end_time;
3567 mtime_t chapter_edition_c::Duration() const
3569 mtime_t i_result = 0;
3571 if ( sub_chapters.size() )
3573 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3575 i_result = (*index)->i_user_end_time;
3581 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3583 chapter_item_c *psz_result = NULL;
3585 if ( i_user_timecode >= i_user_start_time &&
3586 ( i_user_timecode < i_user_end_time ||
3587 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3589 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3590 while ( index != sub_chapters.end() && psz_result == NULL )
3592 psz_result = (*index)->FindTimecode( i_user_timecode );
3596 if ( psz_result == NULL )
3603 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3605 for (size_t i=0; i<opened_segments.size(); i++)
3607 opened_segments[i]->PreloadFamily( of_segment );
3610 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3615 for (size_t i=0; i<families.size(); i++)
3617 for (size_t j=0; j<of_segment.families.size(); j++)
3619 if ( families[i] == of_segment.families[j] )
3627 // preload all the linked segments for all preloaded segments
3628 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3630 size_t i_preloaded, i;
3632 delete p_current_segment;
3633 p_current_segment = new virtual_segment_c( p_segment );
3635 // fill our current virtual segment with all hard linked segments
3638 for ( i=0; i< opened_segments.size(); i++ )
3640 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3642 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3644 p_current_segment->Sort( );
3646 p_current_segment->PreloadLinked( );
3649 bool demux_sys_t::PreparePlayback( )
3651 p_current_segment->LoadCues();
3652 f_duration = p_current_segment->Duration();
3654 /* add information */
3655 p_current_segment->Segment()->InformationCreate( );
3657 p_current_segment->Segment()->Select( 0 );
3659 return p_current_segment->Select( *title );
3662 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
3664 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3665 if ( *p_itema == p_item_b->prev_segment_uid )
3668 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3669 if ( *p_itema == p_item_b->segment_uid )
3672 if ( *p_itema == p_item_b->prev_segment_uid )
3678 bool matroska_segment_c::Preload( )
3683 EbmlElement *el = NULL;
3685 ep->Reset( &sys.demuxer );
3687 while( ( el = ep->Get() ) != NULL )
3689 if( MKV_IS_ID( el, KaxInfo ) )
3691 ParseInfo( static_cast<KaxInfo*>( el ) );
3693 else if( MKV_IS_ID( el, KaxTracks ) )
3695 ParseTracks( static_cast<KaxTracks*>( el ) );
3697 else if( MKV_IS_ID( el, KaxSeekHead ) )
3699 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3701 else if( MKV_IS_ID( el, KaxCues ) )
3703 msg_Dbg( &sys.demuxer, "| + Cues" );
3705 else if( MKV_IS_ID( el, KaxCluster ) )
3707 msg_Dbg( &sys.demuxer, "| + Cluster" );
3709 cluster = (KaxCluster*)el;
3711 i_start_pos = cluster->GetElementPosition();
3715 /* stop parsing the stream */
3718 else if( MKV_IS_ID( el, KaxAttachments ) )
3720 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3722 else if( MKV_IS_ID( el, KaxChapters ) )
3724 msg_Dbg( &sys.demuxer, "| + Chapters" );
3725 ParseChapters( static_cast<KaxChapters*>( el ) );
3727 else if( MKV_IS_ID( el, KaxTag ) )
3729 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3733 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3742 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3744 for (size_t i=0; i<opened_segments.size(); i++)
3746 if ( opened_segments[i]->segment_uid == uid )
3747 return opened_segments[i];
3752 void virtual_segment_c::Sort()
3754 // keep the current segment index
3755 matroska_segment_c *p_segment = linked_segments[i_current_segment];
3757 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
3759 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3760 if ( linked_segments[i_current_segment] == p_segment )
3764 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
3767 // check if it's not already in here
3768 for ( i=0; i<linked_segments.size(); i++ )
3770 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3774 // find possible mates
3775 for ( i=0; i<linked_uids.size(); i++ )
3777 if ( p_segment->segment_uid == linked_uids[i]
3778 || p_segment->prev_segment_uid == linked_uids[i]
3779 || p_segment->next_segment_uid == linked_uids[i] )
3781 linked_segments.push_back( p_segment );
3783 AppendUID( p_segment->prev_segment_uid );
3784 AppendUID( p_segment->next_segment_uid );
3792 void virtual_segment_c::PreloadLinked( )
3794 for ( size_t i=0; i<linked_segments.size(); i++ )
3796 linked_segments[i]->Preload( );
3798 i_current_edition = linked_segments[0]->i_default_edition;
3801 mtime_t virtual_segment_c::Duration() const
3804 if ( linked_segments.size() == 0 )
3807 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
3808 // p_last_segment->ParseCluster( );
3810 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3815 void virtual_segment_c::LoadCues( )
3817 for ( size_t i=0; i<linked_segments.size(); i++ )
3819 linked_segments[i]->LoadCues();
3823 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
3825 if ( UID.GetBuffer() == NULL )
3828 for (size_t i=0; i<linked_uids.size(); i++)
3830 if ( UID == linked_uids[i] )
3833 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3836 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
3839 int i_track_skipping;
3840 int64_t i_block_duration;
3841 int64_t i_block_ref1;
3842 int64_t i_block_ref2;
3844 int64_t i_seek_position = i_start_pos;
3845 int64_t i_seek_time = i_start_time;
3851 for( ; i_idx < i_index; i_idx++ )
3853 if( index[i_idx].i_time + i_time_offset > i_date )
3864 i_seek_position = index[i_idx].i_position;
3865 i_seek_time = index[i_idx].i_time;
3868 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3869 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3871 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3874 ep = new EbmlParser( &es, segment, &sys.demuxer );
3877 sys.i_start_pts = i_date;
3879 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3881 /* now parse until key frame */
3882 #define tk tracks[i_track]
3883 i_track_skipping = 0;
3884 for( i_track = 0; i_track < tracks.size(); i_track++ )
3886 if( tk->fmt.i_cat == VIDEO_ES )
3888 tk->b_search_keyframe = VLC_TRUE;
3891 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3895 while( i_track_skipping > 0 )
3897 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3899 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3904 for( i_track = 0; i_track < tracks.size(); i_track++ )
3906 if( tk->i_number == block->TrackNum() )
3912 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3914 if( i_track < tracks.size() )
3916 if( sys.i_pts >= sys.i_start_pts )
3918 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3919 i_track_skipping = 0;
3921 else if( tk->fmt.i_cat == VIDEO_ES )
3923 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3925 tk->b_search_keyframe = VLC_FALSE;
3928 if( !tk->b_search_keyframe )
3930 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3940 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
3942 demux_sys_t *p_sys = demuxer.p_sys;
3945 // find the actual time for an ordered edition
3946 if ( psz_chapter == NULL )
3948 if ( EditionIsOrdered() )
3950 /* 1st, we need to know in which chapter we are */
3951 psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
3955 if ( psz_chapter != NULL )
3957 psz_current_chapter = psz_chapter;
3958 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3959 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3960 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3963 // find the best matching segment
3964 for ( i=0; i<linked_segments.size(); i++ )
3966 if ( i_date < linked_segments[i]->i_start_time )
3973 if ( i_current_segment != i )
3975 linked_segments[i_current_segment]->UnSelect();
3976 linked_segments[i]->Select( i_date );
3977 i_current_segment = i;
3980 linked_segments[i]->Seek( i_date, i_time_offset );
3983 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
3987 uint32 codec_time = uint32(-1);
3988 for( i = 0; i < command.ListSize(); i++ )
3990 const EbmlElement *k = command[i];
3992 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
3994 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
3999 for( i = 0; i < command.ListSize(); i++ )
4001 const EbmlElement *k = command[i];
4003 if( MKV_IS_ID( k, KaxChapterProcessData ) )
4005 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4006 switch ( codec_time )
4009 during_cmds.push_back( *p_data );
4012 enter_cmds.push_back( *p_data );
4015 leave_cmds.push_back( *p_data );
4024 bool chapter_item_c::Enter()
4026 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4027 while ( index != codecs.end() )
4035 bool chapter_item_c::Leave()
4037 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4038 while ( index != codecs.end() )
4046 bool dvd_chapter_codec_c::Enter()
4048 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4049 while ( index != enter_cmds.end() )
4051 if ( (*index).GetSize() )
4053 binary *p_data = (*index).GetBuffer();
4054 size_t i_size = *p_data++;
4055 // avoid reading too much from the buffer
4056 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4057 for ( ; i_size > 0; i_size--, p_data += 8 )
4059 interpretor.Interpret( p_data );
4067 bool dvd_chapter_codec_c::Leave()
4069 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4070 while ( index != leave_cmds.end() )
4072 if ( (*index).GetSize() )
4074 binary *p_data = (*index).GetBuffer();
4075 size_t i_size = *p_data++;
4076 // avoid reading too much from the buffer
4077 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4078 for ( ; i_size > 0; i_size--, p_data += 8 )
4080 interpretor.Interpret( p_data );
4088 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4093 uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4095 switch ( i_command )
4099 uint8 i_title = p_command[5];
4100 // TODO find in the ChapProcessPrivate matching this Title level