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;
413 class dvd_chapter_codec_c : public chapter_codec_cmds_c
420 dvd_command_interpretor_c interpretor;
423 class matroska_script_codec_c : public chapter_codec_cmds_c
427 class chapter_translation_c
430 KaxChapterTranslateID translated;
431 unsigned int codec_id;
432 std::vector<uint64_t> editions;
441 ,i_user_start_time(-1)
444 ,b_display_seekpoint(true)
450 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
451 while ( index != codecs.end() )
456 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
457 while ( index_ != sub_chapters.end() )
464 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
465 void PublishChapters( input_title_t & title, int i_level );
466 chapter_item_c * FindTimecode( mtime_t i_timecode );
467 void Append( const chapter_item_c & edition );
468 chapter_item_c * FindChapter( const chapter_item_c & chapter );
470 int64_t i_start_time, i_end_time;
471 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
472 std::vector<chapter_item_c*> sub_chapters;
475 bool b_display_seekpoint;
476 std::string psz_name;
477 chapter_item_c *psz_parent;
479 std::vector<chapter_codec_cmds_c*> codecs;
481 bool operator<( const chapter_item_c & item ) const
483 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) );
490 class chapter_edition_c : public chapter_item_c
497 void RefreshChapters( );
498 mtime_t Duration() const;
499 void PublishChapters( input_title_t & title );
506 class matroska_segment_c
509 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
512 ,i_timescale(MKVD_TIMECODESCALE)
516 ,i_chapters_position(-1)
523 ,psz_muxing_application(NULL)
524 ,psz_writing_application(NULL)
525 ,psz_segment_filename(NULL)
528 ,i_default_edition(0)
533 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
536 virtual ~matroska_segment_c()
538 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
540 #define tk tracks[i_track]
541 if( tk->fmt.psz_description )
543 free( tk->fmt.psz_description );
547 free( tk->psz_codec );
549 if( tk->fmt.psz_language )
551 free( tk->fmt.psz_language );
557 if( psz_writing_application )
559 free( psz_writing_application );
561 if( psz_muxing_application )
563 free( psz_muxing_application );
565 if( psz_segment_filename )
567 free( psz_segment_filename );
575 free( psz_date_utc );
582 std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
583 while ( index != stored_editions.end() )
594 uint64_t i_timescale;
596 /* duration of the segment */
598 mtime_t i_start_time;
601 std::vector<mkv_track_t*> tracks;
604 int64_t i_cues_position;
605 int64_t i_chapters_position;
606 int64_t i_tags_position;
610 KaxSegmentUID segment_uid;
611 KaxPrevUID prev_segment_uid;
612 KaxNextUID next_segment_uid;
620 char *psz_muxing_application;
621 char *psz_writing_application;
622 char *psz_segment_filename;
626 std::vector<chapter_edition_c*> stored_editions;
627 int i_default_edition;
629 std::vector<chapter_translation_c> translations;
630 std::vector<KaxSegmentFamily> families;
637 bool PreloadFamily( const matroska_segment_c & segment );
638 void ParseInfo( KaxInfo *info );
639 void ParseChapters( KaxChapters *chapters );
640 void ParseSeekHead( KaxSeekHead *seekhead );
641 void ParseTracks( KaxTracks *tracks );
642 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
643 void ParseTrackEntry( KaxTrackEntry *m );
644 void ParseCluster( );
645 void IndexAppendCluster( KaxCluster *cluster );
648 void InformationCreate( );
649 void Seek( mtime_t i_date, mtime_t i_time_offset );
650 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
651 bool Select( mtime_t i_start_time );
653 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
656 // class holding hard-linked segment together in the playback order
657 class virtual_segment_c
660 virtual_segment_c( matroska_segment_c *p_segment )
661 :i_current_segment(0)
663 ,i_current_edition(-1)
664 ,psz_current_chapter(NULL)
666 linked_segments.push_back( p_segment );
668 AppendUID( p_segment->segment_uid );
669 AppendUID( p_segment->prev_segment_uid );
670 AppendUID( p_segment->next_segment_uid );
674 size_t AddSegment( matroska_segment_c *p_segment );
675 void PreloadLinked( );
676 mtime_t Duration( ) const;
678 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
680 inline chapter_edition_c *Edition()
682 if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
683 return (*p_editions)[i_current_edition];
687 inline bool EditionIsOrdered() const
689 return (p_editions->size() != 0 && i_current_edition >= 0 && (*p_editions)[i_current_edition]->b_ordered);
692 matroska_segment_c * Segment() const
694 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
696 return linked_segments[i_current_segment];
699 inline const chapter_item_c *CurrentChapter() const {
700 return psz_current_chapter;
705 if ( i_current_segment < linked_segments.size()-1 )
713 /* TODO handle/merge chapters here */
714 void UpdateCurrentToChapter( demux_t & demux );
715 bool Select( input_title_t & title );
718 std::vector<matroska_segment_c*> linked_segments;
719 std::vector<KaxSegmentUID> linked_uids;
720 size_t i_current_segment;
722 std::vector<chapter_edition_c*> *p_editions;
723 int i_current_edition;
724 chapter_item_c *psz_current_chapter;
726 void AppendUID( const EbmlBinary & UID );
729 class matroska_stream_c
732 matroska_stream_c( demux_sys_t & demuxer )
738 virtual ~matroska_stream_c()
747 std::vector<matroska_segment_c*> segments;
755 demux_sys_t( demux_t & demux )
762 ,p_current_segment(NULL)
766 virtual ~demux_sys_t()
768 for (size_t i=0; i<streams.size(); i++)
770 for ( size_t i=0; i<opened_segments.size(); i++ )
771 delete opened_segments[i];
779 mtime_t i_chapter_time;
783 input_title_t *title;
785 std::vector<matroska_stream_c*> streams;
786 std::vector<matroska_segment_c*> opened_segments;
787 virtual_segment_c *p_current_segment;
789 /* duration of the stream */
792 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
793 void PreloadFamily( const matroska_segment_c & of_segment );
794 void PreloadLinked( matroska_segment_c *p_segment );
795 bool PreparePlayback( );
796 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
799 static int Demux ( demux_t * );
800 static int Control( demux_t *, int, va_list );
801 static void Seek ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
803 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
805 static char *UTF8ToStr ( const UTFstring &u );
807 /*****************************************************************************
808 * Open: initializes matroska demux structures
809 *****************************************************************************/
810 static int Open( vlc_object_t * p_this )
812 demux_t *p_demux = (demux_t*)p_this;
814 matroska_stream_c *p_stream;
815 matroska_segment_c *p_segment;
817 std::string s_path, s_filename;
818 vlc_stream_io_callback *p_io_callback;
819 EbmlStream *p_io_stream;
821 /* peek the begining */
822 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
824 /* is a valid file */
825 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
826 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
828 /* Set the demux function */
829 p_demux->pf_demux = Demux;
830 p_demux->pf_control = Control;
831 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
833 p_io_callback = new vlc_stream_io_callback( p_demux->s );
834 p_io_stream = new EbmlStream( *p_io_callback );
836 if( p_io_stream == NULL )
838 msg_Err( p_demux, "failed to create EbmlStream" );
839 delete p_io_callback;
844 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
845 if( p_stream == NULL )
847 msg_Err( p_demux, "cannot find KaxSegment" );
850 p_sys->streams.push_back( p_stream );
852 p_stream->p_in = p_io_callback;
853 p_stream->p_es = p_io_stream;
855 for (size_t i=0; i<p_stream->segments.size(); i++)
857 p_stream->segments[i]->Preload();
860 p_segment = p_stream->segments[0];
861 if( p_segment->cluster != NULL )
863 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
865 // reset the stream reading to the first cluster of the segment used
866 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
869 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
870 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
872 // assume it's a regular file
873 // get the directory path
874 s_path = p_demux->psz_path;
875 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
877 s_path = s_path.substr(0,s_path.length()-1);
881 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
883 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
887 struct dirent *p_file_item;
888 DIR *p_src_dir = opendir(s_path.c_str());
890 if (p_src_dir != NULL)
892 while ((p_file_item = (dirent *) readdir(p_src_dir)))
894 if (strlen(p_file_item->d_name) > 4)
896 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
898 if (!s_filename.compare(p_demux->psz_path))
899 continue; // don't reuse the original opened file
901 #if defined(__GNUC__) && (__GNUC__ < 3)
902 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
903 !s_filename.compare("mka", s_filename.length() - 3, 3))
905 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
906 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
909 // test wether this file belongs to the our family
910 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
911 EbmlStream *p_estream = new EbmlStream(*p_file_io);
913 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
914 if ( p_stream == NULL )
916 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
922 p_stream->p_in = p_file_io;
923 p_stream->p_es = p_estream;
924 p_sys->streams.push_back( p_stream );
929 closedir( p_src_dir );
933 p_sys->PreloadFamily( *p_segment );
934 p_sys->PreloadLinked( p_segment );
935 if ( !p_sys->PreparePlayback( ) )
937 msg_Err( p_demux, "cannot use the segment" );
948 /*****************************************************************************
949 * Close: frees unused data
950 *****************************************************************************/
951 static void Close( vlc_object_t *p_this )
953 demux_t *p_demux = (demux_t*)p_this;
954 demux_sys_t *p_sys = p_demux->p_sys;
959 /*****************************************************************************
961 *****************************************************************************/
962 static int Control( demux_t *p_demux, int i_query, va_list args )
964 demux_sys_t *p_sys = p_demux->p_sys;
969 vlc_meta_t **pp_meta;
974 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
975 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
978 case DEMUX_GET_LENGTH:
979 pi64 = (int64_t*)va_arg( args, int64_t * );
980 if( p_sys->f_duration > 0.0 )
982 *pi64 = (int64_t)(p_sys->f_duration * 1000);
987 case DEMUX_GET_POSITION:
988 pf = (double*)va_arg( args, double * );
989 if ( p_sys->f_duration > 0.0 )
990 *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);
993 case DEMUX_SET_POSITION:
994 f = (double)va_arg( args, double );
995 Seek( p_demux, -1, f, NULL );
999 pi64 = (int64_t*)va_arg( args, int64_t * );
1000 *pi64 = p_sys->i_pts;
1003 case DEMUX_GET_TITLE_INFO:
1004 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1006 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1007 int *pi_int = (int*)va_arg( args, int* );
1010 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1012 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1016 return VLC_EGENERIC;
1018 case DEMUX_SET_TITLE:
1019 /* TODO handle editions as titles & DVD titles as well */
1020 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1024 return VLC_EGENERIC;
1026 case DEMUX_SET_SEEKPOINT:
1027 /* FIXME do a better implementation */
1028 i_skp = (int)va_arg( args, int );
1030 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1032 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1033 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1034 p_demux->info.i_seekpoint = i_skp;
1037 return VLC_EGENERIC;
1039 case DEMUX_SET_TIME:
1042 return VLC_EGENERIC;
1046 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1058 i_level = ep->GetLevel();
1060 if( el == NULL && *pp_block != NULL )
1062 /* update the index */
1063 #define idx index[i_index - 1]
1064 if( i_index > 0 && idx.i_time == -1 )
1066 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1067 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1075 if( ep->GetLevel() > 1 )
1080 msg_Warn( &sys.demuxer, "EOF" );
1081 return VLC_EGENERIC;
1087 if( MKV_IS_ID( el, KaxCluster ) )
1089 cluster = (KaxCluster*)el;
1091 /* add it to the index */
1093 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1095 IndexAppendCluster( cluster );
1098 // reset silent tracks
1099 for (size_t i=0; i<tracks.size(); i++)
1101 tracks[i]->b_silent = VLC_FALSE;
1106 else if( MKV_IS_ID( el, KaxCues ) )
1108 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1109 return VLC_EGENERIC;
1113 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1116 else if( i_level == 2 )
1118 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1120 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1122 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1123 cluster->InitTimecode( uint64( ctc ), i_timescale );
1125 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1129 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1134 else if( i_level == 3 )
1136 if( MKV_IS_ID( el, KaxBlock ) )
1138 *pp_block = (KaxBlock*)el;
1140 (*pp_block)->ReadData( es.I_O() );
1141 (*pp_block)->SetParent( *cluster );
1145 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1147 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1149 dur.ReadData( es.I_O() );
1150 *pi_duration = uint64( dur );
1152 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1154 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1156 ref.ReadData( es.I_O() );
1157 if( *pi_ref1 == -1 )
1159 *pi_ref1 = int64( ref );
1163 *pi_ref2 = int64( ref );
1166 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1168 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1169 track_num.ReadData( es.I_O() );
1171 for (size_t i=0; i<tracks.size(); i++)
1173 if ( tracks[i]->i_number == uint32(track_num))
1175 tracks[i]->b_silent = VLC_TRUE;
1183 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1184 return VLC_EGENERIC;
1189 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1192 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1193 memcpy( p_block->p_buffer, p_mem, i_mem );
1194 //p_block->i_rate = p_input->stream.control.i_rate;
1198 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1199 mtime_t i_duration )
1201 demux_sys_t *p_sys = p_demux->p_sys;
1202 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1208 #define tk p_segment->tracks[i_track]
1209 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1211 if( tk->i_number == block->TrackNum() )
1217 if( i_track >= p_segment->tracks.size() )
1219 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1222 if( tk->p_es == NULL )
1224 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1227 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1229 return; /* discard audio packets that shouldn't be rendered */
1232 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1235 tk->b_inited = VLC_FALSE;
1239 /* First send init data */
1240 if( !tk->b_inited && tk->i_data_init > 0 )
1244 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1245 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1246 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1248 tk->b_inited = VLC_TRUE;
1251 for( i = 0; i < block->NumberFrames(); i++ )
1254 DataBuffer &data = block->GetBuffer(i);
1256 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1258 if( p_block == NULL )
1263 #if defined(HAVE_ZLIB_H)
1264 if( tk->i_compression_type )
1266 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1270 // TODO implement correct timestamping when B frames are used
1271 if( tk->fmt.i_cat != VIDEO_ES )
1273 p_block->i_dts = p_block->i_pts = i_pts;
1277 p_block->i_dts = i_pts;
1281 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1283 p_block->i_length = i_duration * 1000;
1286 es_out_Send( p_demux->out, tk->p_es, p_block );
1288 /* use time stamp only for first block */
1295 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1297 int i_upper_lvl = 0;
1299 EbmlElement *p_l0, *p_l1, *p_l2;
1300 bool b_keep_stream = false, b_keep_segment;
1302 // verify the EBML Header
1303 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1308 p_l0->SkipData(*p_estream, EbmlHead_Context);
1311 // find all segments in this file
1312 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1318 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1322 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1325 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1326 b_keep_segment = false;
1328 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1329 p_segment1->ep = ep;
1330 p_segment1->segment = (KaxSegment*)p_l0;
1332 while ((p_l1 = ep->Get()))
1334 if (MKV_IS_ID(p_l1, KaxInfo))
1336 // find the families of this segment
1337 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1339 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1340 for( i = 0; i < p_info->ListSize(); i++ )
1342 EbmlElement *l = (*p_info)[i];
1344 if( MKV_IS_ID( l, KaxSegmentUID ) )
1346 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1347 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1348 if ( !b_keep_segment )
1349 break; // this segment is already known
1350 opened_segments.push_back( p_segment1 );
1351 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1353 else if( MKV_IS_ID( l, KaxPrevUID ) )
1355 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1357 else if( MKV_IS_ID( l, KaxNextUID ) )
1359 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1361 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1363 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1364 p_segment1->families.push_back( *p_fam );
1370 if ( b_keep_segment )
1372 b_keep_stream = true;
1373 p_stream1->segments.push_back( p_segment1 );
1379 p_l0->SkipData(*p_estream, EbmlHead_Context);
1380 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1383 if ( !b_keep_stream )
1392 bool matroska_segment_c::Select( mtime_t i_start_time )
1397 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1398 for( i_track = 0; i_track < tracks.size(); i_track++ )
1400 #define tk tracks[i_track]
1401 if( tk->fmt.i_cat == UNKNOWN_ES )
1403 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1408 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1410 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1412 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1413 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1417 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1419 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1420 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1421 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1423 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1424 if( tk->fmt.i_extra > 0 )
1426 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1427 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1431 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1432 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1434 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1436 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1438 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1440 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1442 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1444 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1445 tk->fmt.b_packetized = VLC_FALSE;
1446 tk->fmt.i_extra = tk->i_extra_data;
1447 tk->fmt.p_extra = malloc( tk->i_extra_data );
1448 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1452 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1455 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1457 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1459 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1463 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1468 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1469 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1470 tk->fmt.i_codec = p_box->i_type;
1471 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1472 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1473 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1474 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1475 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1476 MP4_FreeBox_sample_vide( p_box );
1478 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1480 stream_Delete( p_mp4_stream );
1483 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1485 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1487 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1488 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1492 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1494 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1496 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1497 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1498 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1499 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1500 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1502 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1503 if( tk->fmt.i_extra > 0 )
1505 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1506 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1510 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1511 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1512 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1514 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1516 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1518 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1520 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1522 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1524 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1526 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1527 tk->fmt.i_extra = tk->i_extra_data;
1528 tk->fmt.p_extra = malloc( tk->i_extra_data );
1529 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1531 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1533 int i, i_offset = 1, i_size[3], i_extra;
1536 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1538 /* Split the 3 headers */
1539 if( tk->p_extra_data[0] != 0x02 )
1540 msg_Err( &sys.demuxer, "invalid vorbis header" );
1542 for( i = 0; i < 2; i++ )
1545 while( i_offset < tk->i_extra_data )
1547 i_size[i] += tk->p_extra_data[i_offset];
1548 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1552 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1553 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1554 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1556 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1557 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1558 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1559 for( i = 0; i < 3; i++ )
1561 *(p_extra++) = i_size[i] >> 8;
1562 *(p_extra++) = i_size[i] & 0xFF;
1563 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1565 p_extra += i_size[i];
1566 i_extra += i_size[i];
1569 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1570 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1572 int i_profile, i_srate;
1573 static unsigned int i_sample_rates[] =
1575 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1576 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1579 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1580 /* create data for faad (MP4DecSpecificDescrTag)*/
1582 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1586 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1590 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1599 for( i_srate = 0; i_srate < 13; i_srate++ )
1601 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1606 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1608 tk->fmt.i_extra = 2;
1609 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1610 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1611 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1613 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1614 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1615 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1617 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1619 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1623 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1625 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1627 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1629 /* FIXME: support this codec */
1630 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1631 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1633 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1635 /* FIXME: support this codec */
1636 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1637 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1639 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1641 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1642 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1644 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1645 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1646 !strcmp( tk->psz_codec, "S_SSA" ) ||
1647 !strcmp( tk->psz_codec, "S_ASS" ))
1649 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1650 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1652 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1654 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1655 if( tk->i_extra_data )
1658 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1659 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1660 p_buf[tk->i_extra_data] = '\0';
1662 p_start = strstr( p_buf, "size:" );
1663 if( sscanf( p_start, "size: %dx%d",
1664 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1666 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 );
1670 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1675 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1677 /* FIXME: support this codec */
1678 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1679 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1683 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1684 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1688 tk->fmt.i_priority = 1000;
1691 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1693 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1697 sys.i_start_pts = i_start_time;
1698 // reset the stream reading to the first cluster of the segment used
1699 es.I_O().setFilePointer( i_start_pos );
1702 ep = new EbmlParser( &es, segment, &sys.demuxer );
1707 void matroska_segment_c::UnSelect( )
1711 for( i_track = 0; i_track < tracks.size(); i_track++ )
1713 #define tk tracks[i_track]
1714 if ( tk->p_es != NULL )
1716 es_out_Del( sys.demuxer.out, tk->p_es );
1725 bool virtual_segment_c::Select( input_title_t & title )
1727 if ( linked_segments.size() == 0 )
1730 // !!! should be called only once !!!
1731 matroska_segment_c *p_segment;
1734 // copy editions from the first segment
1735 p_segment = linked_segments[0];
1736 p_editions = &p_segment->stored_editions;
1738 for ( i=1 ; i<linked_segments.size(); i++ )
1740 p_segment = linked_segments[i];
1741 // FIXME assume we have the same editions in all segments
1742 for (j=0; j<p_segment->stored_editions.size(); j++)
1743 (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
1746 if ( Edition() != NULL )
1747 Edition()->PublishChapters( title );
1752 void chapter_edition_c::PublishChapters( input_title_t & title )
1754 title.i_seekpoint = 0;
1755 if ( title.seekpoint != NULL )
1756 free( title.seekpoint );
1757 chapter_item_c::PublishChapters( title, 0 );
1760 void chapter_item_c::PublishChapters( input_title_t & title, int i_level )
1762 if (b_display_seekpoint)
1764 seekpoint_t *sk = vlc_seekpoint_New();
1766 sk->i_level = i_level;
1767 sk->i_time_offset = i_start_time;
1768 sk->psz_name = strdup( psz_name.c_str() );
1770 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1771 title.i_seekpoint++;
1772 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1773 title.seekpoint[title.i_seekpoint-1] = sk;
1775 i_seekpoint_num = title.i_seekpoint;
1778 for ( size_t i=0; i<sub_chapters.size() ; i++)
1780 sub_chapters[i]->PublishChapters( title, i_level+1 );
1784 void virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1786 demux_sys_t & sys = *demux.p_sys;
1787 chapter_item_c *psz_curr_chapter;
1789 /* update current chapter/seekpoint */
1790 if ( p_editions->size() )
1792 /* 1st, we need to know in which chapter we are */
1793 psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
1795 /* we have moved to a new chapter */
1796 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1798 if ( psz_current_chapter != NULL )
1799 psz_current_chapter->Leave();
1801 if ( psz_curr_chapter->i_seekpoint_num > 0 )
1803 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1804 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1807 if ( (*p_editions)[i_current_edition]->b_ordered )
1809 psz_curr_chapter->Enter();
1811 // only seek if necessary
1812 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1813 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1816 psz_current_chapter = psz_curr_chapter;
1820 void chapter_item_c::Append( const chapter_item_c & chapter )
1822 // we are appending content for the same chapter UID
1824 chapter_item_c *p_chapter;
1826 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1828 p_chapter = FindChapter( *chapter.sub_chapters[i] );
1829 if ( p_chapter != NULL )
1831 p_chapter->Append( *chapter.sub_chapters[i] );
1835 sub_chapters.push_back( chapter.sub_chapters[i] );
1839 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1840 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1843 chapter_item_c * chapter_item_c::FindChapter( const chapter_item_c & chapter )
1846 for ( i=0; i<sub_chapters.size(); i++)
1848 if ( sub_chapters[i]->i_uid == chapter.i_uid )
1849 return sub_chapters[i];
1854 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
1856 demux_sys_t *p_sys = p_demux->p_sys;
1857 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1858 matroska_segment_c *p_segment = p_vsegment->Segment();
1859 mtime_t i_time_offset = 0;
1863 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1864 if( i_date < 0 && f_percent < 0 )
1866 msg_Warn( p_demux, "cannot seek nowhere !" );
1869 if( f_percent > 1.0 )
1871 msg_Warn( p_demux, "cannot seek so far !" );
1875 /* seek without index or without date */
1876 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1878 if (p_sys->f_duration >= 0)
1880 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1884 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1886 msg_Dbg( p_demux, "inacurate way of seeking" );
1887 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1889 if( p_segment->index[i_index].i_position >= i_pos)
1894 if( i_index == p_segment->i_index )
1899 i_date = p_segment->index[i_index].i_time;
1902 if( p_segment->index[i_index].i_position < i_pos )
1906 msg_Warn( p_demux, "searching for cluster, could take some time" );
1908 /* search a cluster */
1909 while( ( el = p_sys->ep->Get() ) != NULL )
1911 if( MKV_IS_ID( el, KaxCluster ) )
1913 KaxCluster *cluster = (KaxCluster*)el;
1915 /* add it to the index */
1916 p_segment->IndexAppendCluster( cluster );
1918 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1920 p_sys->cluster = cluster;
1931 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1934 /*****************************************************************************
1935 * Demux: reads and demuxes data packets
1936 *****************************************************************************
1937 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1938 *****************************************************************************/
1939 static int Demux( demux_t *p_demux)
1941 demux_sys_t *p_sys = p_demux->p_sys;
1942 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1943 matroska_segment_c *p_segmet = p_vsegment->Segment();
1944 if ( p_segmet == NULL ) return 0;
1945 int i_block_count = 0;
1948 int64_t i_block_duration;
1949 int64_t i_block_ref1;
1950 int64_t i_block_ref2;
1954 if ( p_sys->demuxer.b_die )
1957 if( p_sys->i_pts >= p_sys->i_start_pts )
1958 p_vsegment->UpdateCurrentToChapter( *p_demux );
1960 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1962 /* nothing left to read in this ordered edition */
1963 if ( !p_vsegment->SelectNext() )
1965 p_segmet->UnSelect( );
1967 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1969 /* switch to the next segment */
1970 p_segmet = p_vsegment->Segment();
1971 if ( !p_segmet->Select( 0 ) )
1973 msg_Err( p_demux, "Failed to select new segment" );
1980 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1982 if ( p_vsegment->EditionIsOrdered() )
1984 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
1985 // check if there are more chapters to read
1986 if ( p_chap != NULL )
1988 /* TODO handle successive chapters with the same user_start_time/user_end_time
1989 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
1990 p_vsegment->SelectNext();
1992 p_sys->i_pts = p_chap->i_user_end_time;
1993 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2000 msg_Warn( p_demux, "cannot get block EOF?" );
2001 p_segmet->UnSelect( );
2003 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2005 /* switch to the next segment */
2006 if ( !p_vsegment->SelectNext() )
2007 // no more segments in this stream
2009 p_segmet = p_vsegment->Segment();
2010 if ( !p_segmet->Select( 0 ) )
2012 msg_Err( p_demux, "Failed to select new segment" );
2019 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2021 if( p_sys->i_pts >= p_sys->i_start_pts )
2023 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2026 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2031 // TODO optimize when there is need to leave or when seeking has been called
2032 if( i_block_count > 5 )
2041 /*****************************************************************************
2043 *****************************************************************************/
2044 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2050 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2052 if( i_size <= 0 || mb_eof )
2057 return stream_Read( s, p_buffer, i_size );
2059 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2065 case seek_beginning:
2069 i_pos = stream_Size( s ) - i_offset;
2072 i_pos= stream_Tell( s ) + i_offset;
2076 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2083 if( stream_Seek( s, i_pos ) )
2089 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2093 uint64 vlc_stream_io_callback::getFilePointer( void )
2095 return stream_Tell( s );
2097 void vlc_stream_io_callback::close( void )
2103 /*****************************************************************************
2104 * Ebml Stream parser
2105 *****************************************************************************/
2106 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2113 mi_remain_size[0] = el_start->GetSize();
2115 for( i = 1; i < 6; i++ )
2121 mb_keep = VLC_FALSE;
2122 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2125 EbmlParser::~EbmlParser( void )
2129 for( i = 1; i < mi_level; i++ )
2135 mb_keep = VLC_FALSE;
2139 void EbmlParser::Up( void )
2141 if( mi_user_level == mi_level )
2143 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2149 void EbmlParser::Down( void )
2155 void EbmlParser::Keep( void )
2160 int EbmlParser::GetLevel( void )
2162 return mi_user_level;
2165 void EbmlParser::Reset( demux_t *p_demux )
2167 while ( mi_level > 0)
2169 delete m_el[mi_level];
2170 m_el[mi_level] = NULL;
2173 mi_user_level = mi_level = 1;
2174 #if LIBEBML_VERSION >= 0x000704
2175 // a little faster and cleaner
2176 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2178 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2180 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2183 EbmlElement *EbmlParser::Get( void )
2187 if( mi_user_level != mi_level )
2193 EbmlElement *ret = m_got;
2199 if( m_el[mi_level] )
2201 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2204 delete m_el[mi_level];
2206 mb_keep = VLC_FALSE;
2209 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2210 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2221 delete m_el[mi_level - 1];
2222 m_got = m_el[mi_level -1] = m_el[mi_level];
2223 m_el[mi_level] = NULL;
2230 else if( m_el[mi_level] == NULL )
2232 fprintf( stderr," m_el[mi_level] == NULL\n" );
2235 return m_el[mi_level];
2239 /*****************************************************************************
2241 * * LoadCues : load the cues element and update index
2243 * * LoadTags : load ... the tags element
2245 * * InformationCreate : create all information, load tags if present
2247 *****************************************************************************/
2248 void matroska_segment_c::LoadCues( )
2250 int64_t i_sav_position = es.I_O().getFilePointer();
2252 EbmlElement *el, *cues;
2254 /* *** Load the cue if found *** */
2255 if( i_cues_position < 0 )
2257 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2259 // IndexAppendCluster( cluster );
2262 vlc_bool_t b_seekable;
2264 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2268 msg_Dbg( &sys.demuxer, "loading cues" );
2269 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2270 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2274 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2275 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2279 ep = new EbmlParser( &es, cues, &sys.demuxer );
2280 while( ( el = ep->Get() ) != NULL )
2282 if( MKV_IS_ID( el, KaxCuePoint ) )
2284 #define idx index[i_index]
2287 idx.i_block_number= -1;
2288 idx.i_position = -1;
2290 idx.b_key = VLC_TRUE;
2293 while( ( el = ep->Get() ) != NULL )
2295 if( MKV_IS_ID( el, KaxCueTime ) )
2297 KaxCueTime &ctime = *(KaxCueTime*)el;
2299 ctime.ReadData( es.I_O() );
2301 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2303 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2306 while( ( el = ep->Get() ) != NULL )
2308 if( MKV_IS_ID( el, KaxCueTrack ) )
2310 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2312 ctrack.ReadData( es.I_O() );
2313 idx.i_track = uint16( ctrack );
2315 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2317 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2319 ccpos.ReadData( es.I_O() );
2320 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2322 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2324 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2326 cbnum.ReadData( es.I_O() );
2327 idx.i_block_number = uint32( cbnum );
2331 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2338 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2344 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2345 " track=%d bnum=%d", idx.i_time, idx.i_position,
2346 idx.i_track, idx.i_block_number );
2350 if( i_index >= i_index_max )
2352 i_index_max += 1024;
2353 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2359 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2367 msg_Dbg( &sys.demuxer, "loading cues done." );
2368 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2371 void matroska_segment_c::LoadTags( )
2373 int64_t i_sav_position = es.I_O().getFilePointer();
2375 EbmlElement *el, *tags;
2377 msg_Dbg( &sys.demuxer, "loading tags" );
2378 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2379 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2383 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2384 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2388 msg_Dbg( &sys.demuxer, "Tags" );
2389 ep = new EbmlParser( &es, tags, &sys.demuxer );
2390 while( ( el = ep->Get() ) != NULL )
2392 if( MKV_IS_ID( el, KaxTag ) )
2394 msg_Dbg( &sys.demuxer, "+ Tag" );
2396 while( ( el = ep->Get() ) != NULL )
2398 if( MKV_IS_ID( el, KaxTagTargets ) )
2400 msg_Dbg( &sys.demuxer, "| + Targets" );
2402 while( ( el = ep->Get() ) != NULL )
2404 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2408 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2410 msg_Dbg( &sys.demuxer, "| + General" );
2412 while( ( el = ep->Get() ) != NULL )
2414 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2418 else if( MKV_IS_ID( el, KaxTagGenres ) )
2420 msg_Dbg( &sys.demuxer, "| + Genres" );
2422 while( ( el = ep->Get() ) != NULL )
2424 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2428 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2430 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2432 while( ( el = ep->Get() ) != NULL )
2434 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2438 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2440 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2442 while( ( el = ep->Get() ) != NULL )
2444 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2448 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2450 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2452 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2454 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2456 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2458 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2460 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2462 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2464 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2466 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2468 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2470 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2472 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2474 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2478 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2485 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2491 msg_Dbg( &sys.demuxer, "loading tags done." );
2492 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2495 /*****************************************************************************
2497 *****************************************************************************/
2498 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2502 int i_upper_level = 0;
2504 msg_Dbg( &sys.demuxer, "| + Seek head" );
2506 /* Master elements */
2507 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2509 for( i = 0; i < seekhead->ListSize(); i++ )
2511 EbmlElement *l = (*seekhead)[i];
2513 if( MKV_IS_ID( l, KaxSeek ) )
2515 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2516 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2519 for( j = 0; j < sk->ListSize(); j++ )
2521 EbmlElement *l = (*sk)[j];
2523 if( MKV_IS_ID( l, KaxSeekID ) )
2525 KaxSeekID &sid = *(KaxSeekID*)l;
2526 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2528 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2530 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2531 i_pos = uint64( spos );
2535 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2541 if( id == KaxCues::ClassInfos.GlobalId )
2543 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2544 i_cues_position = segment->GetGlobalPosition( i_pos );
2546 else if( id == KaxChapters::ClassInfos.GlobalId )
2548 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2549 i_chapters_position = segment->GetGlobalPosition( i_pos );
2551 else if( id == KaxTags::ClassInfos.GlobalId )
2553 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2554 i_tags_position = segment->GetGlobalPosition( i_pos );
2560 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2565 /*****************************************************************************
2567 *****************************************************************************/
2568 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2574 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2576 tk = new mkv_track_t();
2577 tracks.push_back( tk );
2579 /* Init the track */
2580 memset( tk, 0, sizeof( mkv_track_t ) );
2582 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2583 tk->fmt.psz_language = strdup("English");
2584 tk->fmt.psz_description = NULL;
2586 tk->b_default = VLC_TRUE;
2587 tk->b_enabled = VLC_TRUE;
2588 tk->b_silent = VLC_FALSE;
2589 tk->i_number = tracks.size() - 1;
2590 tk->i_extra_data = 0;
2591 tk->p_extra_data = NULL;
2592 tk->psz_codec = NULL;
2593 tk->i_default_duration = 0;
2594 tk->f_timecodescale = 1.0;
2596 tk->b_inited = VLC_FALSE;
2597 tk->i_data_init = 0;
2598 tk->p_data_init = NULL;
2600 tk->psz_codec_name = NULL;
2601 tk->psz_codec_settings = NULL;
2602 tk->psz_codec_info_url = NULL;
2603 tk->psz_codec_download_url = NULL;
2605 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2607 for( i = 0; i < m->ListSize(); i++ )
2609 EbmlElement *l = (*m)[i];
2611 if( MKV_IS_ID( l, KaxTrackNumber ) )
2613 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2615 tk->i_number = uint32( tnum );
2616 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2618 else if( MKV_IS_ID( l, KaxTrackUID ) )
2620 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2622 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2624 else if( MKV_IS_ID( l, KaxTrackType ) )
2627 KaxTrackType &ttype = *(KaxTrackType*)l;
2629 switch( uint8(ttype) )
2633 tk->fmt.i_cat = AUDIO_ES;
2637 tk->fmt.i_cat = VIDEO_ES;
2639 case track_subtitle:
2640 psz_type = "subtitle";
2641 tk->fmt.i_cat = SPU_ES;
2644 psz_type = "unknown";
2645 tk->fmt.i_cat = UNKNOWN_ES;
2649 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2651 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2653 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2655 // tk->b_enabled = uint32( fenb );
2656 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2657 // uint32( fenb ) );
2659 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2661 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2663 tk->b_default = uint32( fdef );
2664 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2666 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2668 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2670 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2672 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2674 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2676 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2678 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2680 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2682 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2684 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2686 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2688 tk->i_default_duration = uint64(defd);
2689 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2691 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2693 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2695 tk->f_timecodescale = float( ttcs );
2696 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2698 else if( MKV_IS_ID( l, KaxTrackName ) )
2700 KaxTrackName &tname = *(KaxTrackName*)l;
2702 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2703 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2705 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2707 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2709 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2710 msg_Dbg( &sys.demuxer,
2711 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2713 else if( MKV_IS_ID( l, KaxCodecID ) )
2715 KaxCodecID &codecid = *(KaxCodecID*)l;
2717 tk->psz_codec = strdup( string( codecid ).c_str() );
2718 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2720 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2722 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2724 tk->i_extra_data = cpriv.GetSize();
2725 if( tk->i_extra_data > 0 )
2727 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2728 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2730 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2732 else if( MKV_IS_ID( l, KaxCodecName ) )
2734 KaxCodecName &cname = *(KaxCodecName*)l;
2736 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2737 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2739 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2741 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2742 MkvTree( sys.demuxer, 3, "Content Encodings" );
2743 for( j = 0; j < cencs->ListSize(); j++ )
2745 EbmlElement *l2 = (*cencs)[j];
2746 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2748 MkvTree( sys.demuxer, 4, "Content Encoding" );
2749 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2750 for( k = 0; k < cenc->ListSize(); k++ )
2752 EbmlElement *l3 = (*cenc)[k];
2753 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2755 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2756 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2758 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2760 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2761 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2763 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2765 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2766 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2768 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2770 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2771 MkvTree( sys.demuxer, 5, "Content Compression" );
2772 for( n = 0; n < compr->ListSize(); n++ )
2774 EbmlElement *l4 = (*compr)[n];
2775 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2777 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2778 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2779 if( uint32( compalg ) == 0 )
2781 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2786 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2793 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2800 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2805 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2807 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2809 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2810 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2812 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2814 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2816 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2817 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2819 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2821 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2823 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2824 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2826 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2828 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2830 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2832 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2834 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2836 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2838 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2840 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2843 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2846 for( j = 0; j < tkv->ListSize(); j++ )
2848 EbmlElement *l = (*tkv)[j];
2849 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2851 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2853 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2855 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2857 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2859 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2862 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2864 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2866 tk->fmt.video.i_width = uint16( vwidth );
2867 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2869 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2871 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2873 tk->fmt.video.i_height = uint16( vheight );
2874 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2876 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2878 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2880 tk->fmt.video.i_visible_width = uint16( vwidth );
2881 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2883 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2885 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2887 tk->fmt.video.i_visible_height = uint16( vheight );
2888 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2890 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2892 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2894 tk->f_fps = float( vfps );
2895 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2897 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2899 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2901 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2902 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2904 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2906 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2908 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2910 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2912 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2914 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2918 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2921 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2922 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2924 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2926 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2929 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2931 for( j = 0; j < tka->ListSize(); j++ )
2933 EbmlElement *l = (*tka)[j];
2935 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2937 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2939 tk->fmt.audio.i_rate = (int)float( afreq );
2940 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2942 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2944 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2946 tk->fmt.audio.i_channels = uint8( achan );
2947 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2949 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2951 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2953 tk->fmt.audio.i_bitspersample = uint8( abits );
2954 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2958 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2964 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2965 typeid(*l).name() );
2970 /*****************************************************************************
2972 *****************************************************************************/
2973 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
2977 int i_upper_level = 0;
2979 msg_Dbg( &sys.demuxer, "| + Tracks" );
2981 /* Master elements */
2982 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2984 for( i = 0; i < tracks->ListSize(); i++ )
2986 EbmlElement *l = (*tracks)[i];
2988 if( MKV_IS_ID( l, KaxTrackEntry ) )
2990 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
2994 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2999 /*****************************************************************************
3001 *****************************************************************************/
3002 void matroska_segment_c::ParseInfo( KaxInfo *info )
3007 int i_upper_level = 0;
3009 msg_Dbg( &sys.demuxer, "| + Information" );
3011 /* Master elements */
3012 m = static_cast<EbmlMaster *>(info);
3013 m->Read( es, info->Generic().Context, i_upper_level, el, true );
3015 for( i = 0; i < m->ListSize(); i++ )
3017 EbmlElement *l = (*m)[i];
3019 if( MKV_IS_ID( l, KaxSegmentUID ) )
3021 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3023 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3025 else if( MKV_IS_ID( l, KaxPrevUID ) )
3027 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3029 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3031 else if( MKV_IS_ID( l, KaxNextUID ) )
3033 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3035 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3037 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3039 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3041 i_timescale = uint64(tcs);
3043 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3046 else if( MKV_IS_ID( l, KaxDuration ) )
3048 KaxDuration &dur = *(KaxDuration*)l;
3050 i_duration = mtime_t( double( dur ) );
3052 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3055 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3057 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3059 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3061 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3062 psz_muxing_application );
3064 else if( MKV_IS_ID( l, KaxWritingApp ) )
3066 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3068 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3070 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3071 psz_writing_application );
3073 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3075 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3077 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3079 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3080 psz_segment_filename );
3082 else if( MKV_IS_ID( l, KaxTitle ) )
3084 KaxTitle &title = *(KaxTitle*)l;
3086 psz_title = UTF8ToStr( UTFstring( title ) );
3088 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3090 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3092 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3094 families.push_back(*uid);
3096 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3098 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3099 else if( MKV_IS_ID( l, KaxDateUTC ) )
3101 KaxDateUTC &date = *(KaxDateUTC*)l;
3106 i_date = date.GetEpochDate();
3107 memset( buffer, 0, 256 );
3108 if( gmtime_r( &i_date, &tmres ) &&
3109 asctime_r( &tmres, buffer ) )
3111 buffer[strlen( buffer)-1]= '\0';
3112 psz_date_utc = strdup( buffer );
3113 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3117 #if LIBMATROSKA_VERSION >= 0x000704
3118 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3120 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3121 chapter_translation_c translated;
3123 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3124 for( j = 0; j < p_trans->ListSize(); j++ )
3126 EbmlElement *l = (*p_trans)[j];
3128 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3130 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3132 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3134 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3136 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3138 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3142 translations.push_back( translated );
3147 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3151 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3152 i_duration = mtime_t(f_dur);
3156 /*****************************************************************************
3158 *****************************************************************************/
3159 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3163 if( sys.title == NULL )
3165 sys.title = vlc_input_title_New();
3168 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3169 for( i = 0; i < ca->ListSize(); i++ )
3171 EbmlElement *l = (*ca)[i];
3173 if( MKV_IS_ID( l, KaxChapterUID ) )
3175 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3176 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3178 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3180 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3181 chapters.b_display_seekpoint = uint8( flag ) == 0;
3183 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3185 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3187 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3188 chapters.i_start_time = uint64( start ) / I64C(1000);
3190 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3192 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3194 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3195 chapters.i_end_time = uint64( end ) / I64C(1000);
3197 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3199 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3201 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3203 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3204 for( j = 0; j < cd->ListSize(); j++ )
3206 EbmlElement *l= (*cd)[j];
3208 if( MKV_IS_ID( l, KaxChapterString ) )
3212 KaxChapterString &name =*(KaxChapterString*)l;
3213 for (k = 0; k < i_level; k++)
3214 chapters.psz_name += '+';
3215 chapters.psz_name += ' ';
3216 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3218 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3220 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3222 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3223 const char *psz = string( lang ).c_str();
3225 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3227 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3229 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3230 const char *psz = string( ct ).c_str();
3232 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3236 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3238 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3240 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3241 chapter_codec_cmds_c *p_ccodec = NULL;
3243 for( j = 0; j < cp->ListSize(); j++ )
3245 EbmlElement *k= (*cp)[j];
3247 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3249 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3250 if ( uint32(*p_codec_id) == 0 )
3251 p_ccodec = new matroska_script_codec_c();
3252 else if ( uint32(*p_codec_id) == 1 )
3253 p_ccodec = new dvd_chapter_codec_c();
3258 if ( p_ccodec != NULL )
3260 for( j = 0; j < cp->ListSize(); j++ )
3262 EbmlElement *k= (*cp)[j];
3264 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3266 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3267 p_ccodec->SetPrivate( *p_private );
3269 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3271 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3274 chapters.codecs.push_back( p_ccodec );
3277 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3279 chapter_item_c *new_sub_chapter = new chapter_item_c();
3280 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3281 new_sub_chapter->psz_parent = &chapters;
3282 chapters.sub_chapters.push_back( new_sub_chapter );
3287 /*****************************************************************************
3289 *****************************************************************************/
3290 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3294 int i_upper_level = 0;
3297 /* Master elements */
3298 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3300 for( i = 0; i < chapters->ListSize(); i++ )
3302 EbmlElement *l = (*chapters)[i];
3304 if( MKV_IS_ID( l, KaxEditionEntry ) )
3306 chapter_edition_c *p_edition = new chapter_edition_c();
3308 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3310 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3311 for( j = 0; j < E->ListSize(); j++ )
3313 EbmlElement *l = (*E)[j];
3315 if( MKV_IS_ID( l, KaxChapterAtom ) )
3317 chapter_item_c *new_sub_chapter = new chapter_item_c();
3318 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3319 p_edition->sub_chapters.push_back( new_sub_chapter );
3321 else if( MKV_IS_ID( l, KaxEditionUID ) )
3323 p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3325 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3327 p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3329 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3331 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3332 i_default_edition = stored_editions.size();
3336 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3339 stored_editions.push_back( p_edition );
3343 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3347 for( i = 0; i < stored_editions.size(); i++ )
3349 stored_editions[i]->RefreshChapters( );
3352 if ( stored_editions[i_default_edition]->b_ordered )
3354 /* update the duration of the segment according to the sum of all sub chapters */
3355 i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3361 void matroska_segment_c::ParseCluster( )
3366 int i_upper_level = 0;
3368 /* Master elements */
3369 m = static_cast<EbmlMaster *>( cluster );
3370 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3372 for( i = 0; i < m->ListSize(); i++ )
3374 EbmlElement *l = (*m)[i];
3376 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3378 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3380 cluster->InitTimecode( uint64( ctc ), i_timescale );
3385 i_start_time = cluster->GlobalTimecode() / 1000;
3388 /*****************************************************************************
3389 * InformationCreate:
3390 *****************************************************************************/
3391 void matroska_segment_c::InformationCreate( )
3395 sys.meta = vlc_meta_New();
3399 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3403 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3405 if( psz_segment_filename )
3407 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3409 if( psz_muxing_application )
3411 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3413 if( psz_writing_application )
3415 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3418 for( i_track = 0; i_track < tracks.size(); i_track++ )
3420 mkv_track_t *tk = tracks[i_track];
3421 vlc_meta_t *mtk = vlc_meta_New();
3423 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3424 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3425 sys.meta->track[sys.meta->i_track++] = mtk;
3427 if( tk->fmt.psz_description )
3429 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3431 if( tk->psz_codec_name )
3433 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3435 if( tk->psz_codec_settings )
3437 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3439 if( tk->psz_codec_info_url )
3441 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3443 if( tk->psz_codec_download_url )
3445 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3449 if( i_tags_position >= 0 )
3451 vlc_bool_t b_seekable;
3453 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3462 /*****************************************************************************
3464 *****************************************************************************/
3466 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3468 #define idx index[i_index]
3470 idx.i_block_number= -1;
3471 idx.i_position = cluster->GetElementPosition();
3473 idx.b_key = VLC_TRUE;
3476 if( i_index >= i_index_max )
3478 i_index_max += 1024;
3479 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3484 static char * UTF8ToStr( const UTFstring &u )
3493 p = dst = (char*)malloc( i_src + 1);
3512 void chapter_edition_c::RefreshChapters( )
3514 chapter_item_c::RefreshChapters( b_ordered, -1 );
3515 b_display_seekpoint = false;
3518 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3520 int64_t i_user_time = i_prev_user_time;
3522 // first the sub-chapters, and then ourself
3523 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3524 while ( index != sub_chapters.end() )
3526 i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3532 // the ordered chapters always start at zero
3533 if ( i_prev_user_time == -1 )
3535 if ( i_user_time == -1 )
3537 i_prev_user_time = 0;
3540 i_user_start_time = i_prev_user_time;
3541 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3543 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3547 i_user_end_time = i_user_time;
3552 std::sort( sub_chapters.begin(), sub_chapters.end() );
3553 i_user_start_time = i_start_time;
3554 if ( i_end_time != -1 )
3555 i_user_end_time = i_end_time;
3556 else if ( i_user_time != -1 )
3557 i_user_end_time = i_user_time;
3559 i_user_end_time = i_user_start_time;
3562 return i_user_end_time;
3565 mtime_t chapter_edition_c::Duration() const
3567 mtime_t i_result = 0;
3569 if ( sub_chapters.size() )
3571 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3573 i_result = (*index)->i_user_end_time;
3579 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3581 chapter_item_c *psz_result = NULL;
3583 if ( i_user_timecode >= i_user_start_time &&
3584 ( i_user_timecode < i_user_end_time ||
3585 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3587 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3588 while ( index != sub_chapters.end() && psz_result == NULL )
3590 psz_result = (*index)->FindTimecode( i_user_timecode );
3594 if ( psz_result == NULL )
3601 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3603 for (size_t i=0; i<opened_segments.size(); i++)
3605 opened_segments[i]->PreloadFamily( of_segment );
3608 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3613 for (size_t i=0; i<families.size(); i++)
3615 for (size_t j=0; j<of_segment.families.size(); j++)
3617 if ( families[i] == of_segment.families[j] )
3625 // preload all the linked segments for all preloaded segments
3626 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3628 size_t i_preloaded, i;
3630 delete p_current_segment;
3631 p_current_segment = new virtual_segment_c( p_segment );
3633 // fill our current virtual segment with all hard linked segments
3636 for ( i=0; i< opened_segments.size(); i++ )
3638 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3640 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3642 p_current_segment->Sort( );
3644 p_current_segment->PreloadLinked( );
3647 bool demux_sys_t::PreparePlayback( )
3649 p_current_segment->LoadCues();
3650 f_duration = p_current_segment->Duration();
3652 /* add information */
3653 p_current_segment->Segment()->InformationCreate( );
3655 p_current_segment->Segment()->Select( 0 );
3657 return p_current_segment->Select( *title );
3660 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
3662 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3663 if ( *p_itema == p_item_b->prev_segment_uid )
3666 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3667 if ( *p_itema == p_item_b->segment_uid )
3670 if ( *p_itema == p_item_b->prev_segment_uid )
3676 bool matroska_segment_c::Preload( )
3681 EbmlElement *el = NULL;
3683 ep->Reset( &sys.demuxer );
3685 while( ( el = ep->Get() ) != NULL )
3687 if( MKV_IS_ID( el, KaxInfo ) )
3689 ParseInfo( static_cast<KaxInfo*>( el ) );
3691 else if( MKV_IS_ID( el, KaxTracks ) )
3693 ParseTracks( static_cast<KaxTracks*>( el ) );
3695 else if( MKV_IS_ID( el, KaxSeekHead ) )
3697 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3699 else if( MKV_IS_ID( el, KaxCues ) )
3701 msg_Dbg( &sys.demuxer, "| + Cues" );
3703 else if( MKV_IS_ID( el, KaxCluster ) )
3705 msg_Dbg( &sys.demuxer, "| + Cluster" );
3707 cluster = (KaxCluster*)el;
3709 i_start_pos = cluster->GetElementPosition();
3713 /* stop parsing the stream */
3716 else if( MKV_IS_ID( el, KaxAttachments ) )
3718 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3720 else if( MKV_IS_ID( el, KaxChapters ) )
3722 msg_Dbg( &sys.demuxer, "| + Chapters" );
3723 ParseChapters( static_cast<KaxChapters*>( el ) );
3725 else if( MKV_IS_ID( el, KaxTag ) )
3727 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3731 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3740 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3742 for (size_t i=0; i<opened_segments.size(); i++)
3744 if ( opened_segments[i]->segment_uid == uid )
3745 return opened_segments[i];
3750 void virtual_segment_c::Sort()
3752 // keep the current segment index
3753 matroska_segment_c *p_segment = linked_segments[i_current_segment];
3755 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
3757 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3758 if ( linked_segments[i_current_segment] == p_segment )
3762 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
3765 // check if it's not already in here
3766 for ( i=0; i<linked_segments.size(); i++ )
3768 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3772 // find possible mates
3773 for ( i=0; i<linked_uids.size(); i++ )
3775 if ( p_segment->segment_uid == linked_uids[i]
3776 || p_segment->prev_segment_uid == linked_uids[i]
3777 || p_segment->next_segment_uid == linked_uids[i] )
3779 linked_segments.push_back( p_segment );
3781 AppendUID( p_segment->prev_segment_uid );
3782 AppendUID( p_segment->next_segment_uid );
3790 void virtual_segment_c::PreloadLinked( )
3792 for ( size_t i=0; i<linked_segments.size(); i++ )
3794 linked_segments[i]->Preload( );
3796 i_current_edition = linked_segments[0]->i_default_edition;
3799 mtime_t virtual_segment_c::Duration() const
3802 if ( linked_segments.size() == 0 )
3805 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
3806 // p_last_segment->ParseCluster( );
3808 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3813 void virtual_segment_c::LoadCues( )
3815 for ( size_t i=0; i<linked_segments.size(); i++ )
3817 linked_segments[i]->LoadCues();
3821 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
3823 if ( UID.GetBuffer() == NULL )
3826 for (size_t i=0; i<linked_uids.size(); i++)
3828 if ( UID == linked_uids[i] )
3831 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3834 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
3837 int i_track_skipping;
3838 int64_t i_block_duration;
3839 int64_t i_block_ref1;
3840 int64_t i_block_ref2;
3842 int64_t i_seek_position = i_start_pos;
3843 int64_t i_seek_time = i_start_time;
3849 for( ; i_idx < i_index; i_idx++ )
3851 if( index[i_idx].i_time + i_time_offset > i_date )
3862 i_seek_position = index[i_idx].i_position;
3863 i_seek_time = index[i_idx].i_time;
3866 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3867 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3869 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3872 ep = new EbmlParser( &es, segment, &sys.demuxer );
3875 sys.i_start_pts = i_date;
3877 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3879 /* now parse until key frame */
3880 #define tk tracks[i_track]
3881 i_track_skipping = 0;
3882 for( i_track = 0; i_track < tracks.size(); i_track++ )
3884 if( tk->fmt.i_cat == VIDEO_ES )
3886 tk->b_search_keyframe = VLC_TRUE;
3889 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3893 while( i_track_skipping > 0 )
3895 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3897 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3902 for( i_track = 0; i_track < tracks.size(); i_track++ )
3904 if( tk->i_number == block->TrackNum() )
3910 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3912 if( i_track < tracks.size() )
3914 if( sys.i_pts >= sys.i_start_pts )
3916 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3917 i_track_skipping = 0;
3919 else if( tk->fmt.i_cat == VIDEO_ES )
3921 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3923 tk->b_search_keyframe = VLC_FALSE;
3926 if( !tk->b_search_keyframe )
3928 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3938 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
3940 demux_sys_t *p_sys = demuxer.p_sys;
3943 // find the actual time for an ordered edition
3944 if ( psz_chapter == NULL )
3946 if ( EditionIsOrdered() )
3948 /* 1st, we need to know in which chapter we are */
3949 psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
3953 if ( psz_chapter != NULL )
3955 psz_current_chapter = psz_chapter;
3956 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3957 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3958 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3961 // find the best matching segment
3962 for ( i=0; i<linked_segments.size(); i++ )
3964 if ( i_date < linked_segments[i]->i_start_time )
3971 if ( i_current_segment != i )
3973 linked_segments[i_current_segment]->UnSelect();
3974 linked_segments[i]->Select( i_date );
3975 i_current_segment = i;
3978 linked_segments[i]->Seek( i_date, i_time_offset );
3981 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
3985 uint32 codec_time = uint32(-1);
3986 for( i = 0; i < command.ListSize(); i++ )
3988 const EbmlElement *k = command[i];
3990 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
3992 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
3997 for( i = 0; i < command.ListSize(); i++ )
3999 const EbmlElement *k = command[i];
4001 if( MKV_IS_ID( k, KaxChapterProcessData ) )
4003 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4004 switch ( codec_time )
4007 during_cmds.push_back( *p_data );
4010 enter_cmds.push_back( *p_data );
4013 leave_cmds.push_back( *p_data );
4022 bool chapter_item_c::Enter()
4024 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4025 while ( index != codecs.end() )
4033 bool chapter_item_c::Leave()
4035 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4036 while ( index != codecs.end() )
4044 bool dvd_chapter_codec_c::Enter()
4046 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4047 while ( index != enter_cmds.end() )
4049 if ( (*index).GetSize() )
4051 binary *p_data = (*index).GetBuffer();
4052 size_t i_size = *p_data++;
4053 // avoid reading too much from the buffer
4054 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4055 for ( ; i_size > 0; i_size--, p_data += 8 )
4057 interpretor.Interpret( p_data );
4065 bool dvd_chapter_codec_c::Leave()
4067 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4068 while ( index != leave_cmds.end() )
4070 if ( (*index).GetSize() )
4072 binary *p_data = (*index).GetBuffer();
4073 size_t i_size = *p_data++;
4074 // avoid reading too much from the buffer
4075 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4076 for ( ; i_size > 0; i_size--, p_data += 8 )
4078 interpretor.Interpret( p_data );
4086 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )