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 virtual ~chapter_codec_cmds_c() {}
338 void SetPrivate( const KaxChapterProcessPrivate & private_data )
340 m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
343 void AddCommand( const KaxChapterProcessCommand & command );
345 virtual bool Enter() { return true; }
346 virtual bool Leave() { return true; }
349 KaxChapterProcessPrivate m_private_data;
351 std::vector<KaxChapterProcessData> enter_cmds;
352 std::vector<KaxChapterProcessData> during_cmds;
353 std::vector<KaxChapterProcessData> leave_cmds;
356 class dvd_command_interpretor_c
359 dvd_command_interpretor_c()
361 memset( p_GPRM, 0, sizeof(p_GPRM) );
362 memset( p_SPRM, 0, sizeof(p_SPRM) );
369 p_SPRM[ 16 ] = 0xFFFFu;
370 p_SPRM[ 18 ] = 0xFFFFu;
373 bool Interpret( const binary * p_command, size_t i_size = 8 );
376 uint16 GetGPRM( size_t index ) const
378 if ( index >= 0 && index < 16 )
379 return p_GPRM[ index ];
383 uint16 GetSPRM( size_t index ) const
385 // 21,22,23 reserved for future use
386 if ( index >= 0 && index < 21 )
387 return p_SPRM[ index ];
391 bool SetGPRM( size_t index, uint16 value )
393 if ( index >= 0 && index < 16 )
395 p_GPRM[ index ] = value;
401 bool SetSPRM( size_t index, uint16 value )
403 if ( index > 0 && index <= 13 && index != 12 )
405 p_SPRM[ index ] = value;
414 static const uint16 CMD_JUMP_TT = 0x3002;
417 class dvd_chapter_codec_c : public chapter_codec_cmds_c
424 dvd_command_interpretor_c interpretor;
427 class matroska_script_codec_c : public chapter_codec_cmds_c
431 class chapter_translation_c
434 KaxChapterTranslateID translated;
435 unsigned int codec_id;
436 std::vector<uint64_t> editions;
445 ,i_user_start_time(-1)
448 ,b_display_seekpoint(true)
454 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
455 while ( index != codecs.end() )
460 std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
461 while ( index_ != sub_chapters.end() )
468 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
469 void PublishChapters( input_title_t & title, int i_level );
470 chapter_item_c * FindTimecode( mtime_t i_timecode );
471 void Append( const chapter_item_c & edition );
472 chapter_item_c * FindChapter( const chapter_item_c & chapter );
474 int64_t i_start_time, i_end_time;
475 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
476 std::vector<chapter_item_c*> sub_chapters;
479 bool b_display_seekpoint;
480 std::string psz_name;
481 chapter_item_c *psz_parent;
483 std::vector<chapter_codec_cmds_c*> codecs;
485 bool operator<( const chapter_item_c & item ) const
487 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) );
494 class chapter_edition_c : public chapter_item_c
501 void RefreshChapters( );
502 mtime_t Duration() const;
503 void PublishChapters( input_title_t & title );
510 class matroska_segment_c
513 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
516 ,i_timescale(MKVD_TIMECODESCALE)
520 ,i_chapters_position(-1)
527 ,psz_muxing_application(NULL)
528 ,psz_writing_application(NULL)
529 ,psz_segment_filename(NULL)
532 ,i_default_edition(0)
537 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
540 virtual ~matroska_segment_c()
542 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
544 #define tk tracks[i_track]
545 if( tk->fmt.psz_description )
547 free( tk->fmt.psz_description );
551 free( tk->psz_codec );
553 if( tk->fmt.psz_language )
555 free( tk->fmt.psz_language );
561 if( psz_writing_application )
563 free( psz_writing_application );
565 if( psz_muxing_application )
567 free( psz_muxing_application );
569 if( psz_segment_filename )
571 free( psz_segment_filename );
579 free( psz_date_utc );
586 std::vector<chapter_edition_c*>::iterator index = stored_editions.begin();
587 while ( index != stored_editions.end() )
598 uint64_t i_timescale;
600 /* duration of the segment */
602 mtime_t i_start_time;
605 std::vector<mkv_track_t*> tracks;
608 int64_t i_cues_position;
609 int64_t i_chapters_position;
610 int64_t i_tags_position;
614 KaxSegmentUID segment_uid;
615 KaxPrevUID prev_segment_uid;
616 KaxNextUID next_segment_uid;
624 char *psz_muxing_application;
625 char *psz_writing_application;
626 char *psz_segment_filename;
630 std::vector<chapter_edition_c*> stored_editions;
631 int i_default_edition;
633 std::vector<chapter_translation_c> translations;
634 std::vector<KaxSegmentFamily> families;
641 bool PreloadFamily( const matroska_segment_c & segment );
642 void ParseInfo( KaxInfo *info );
643 void ParseChapters( KaxChapters *chapters );
644 void ParseSeekHead( KaxSeekHead *seekhead );
645 void ParseTracks( KaxTracks *tracks );
646 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
647 void ParseTrackEntry( KaxTrackEntry *m );
648 void ParseCluster( );
649 void IndexAppendCluster( KaxCluster *cluster );
652 void InformationCreate( );
653 void Seek( mtime_t i_date, mtime_t i_time_offset );
654 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
655 bool Select( mtime_t i_start_time );
657 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
660 // class holding hard-linked segment together in the playback order
661 class virtual_segment_c
664 virtual_segment_c( matroska_segment_c *p_segment )
665 :i_current_segment(0)
667 ,i_current_edition(-1)
668 ,psz_current_chapter(NULL)
670 linked_segments.push_back( p_segment );
672 AppendUID( p_segment->segment_uid );
673 AppendUID( p_segment->prev_segment_uid );
674 AppendUID( p_segment->next_segment_uid );
678 size_t AddSegment( matroska_segment_c *p_segment );
679 void PreloadLinked( );
680 mtime_t Duration( ) const;
682 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter );
684 inline chapter_edition_c *Edition()
686 if ( i_current_edition >= 0 && size_t(i_current_edition) < p_editions->size() )
687 return (*p_editions)[i_current_edition];
691 inline bool EditionIsOrdered() const
693 return (p_editions->size() != 0 && i_current_edition >= 0 && (*p_editions)[i_current_edition]->b_ordered);
696 matroska_segment_c * Segment() const
698 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
700 return linked_segments[i_current_segment];
703 inline const chapter_item_c *CurrentChapter() const {
704 return psz_current_chapter;
709 if ( i_current_segment < linked_segments.size()-1 )
717 /* TODO handle/merge chapters here */
718 void UpdateCurrentToChapter( demux_t & demux );
719 bool Select( input_title_t & title );
722 std::vector<matroska_segment_c*> linked_segments;
723 std::vector<KaxSegmentUID> linked_uids;
724 size_t i_current_segment;
726 std::vector<chapter_edition_c*> *p_editions;
727 int i_current_edition;
728 chapter_item_c *psz_current_chapter;
730 void AppendUID( const EbmlBinary & UID );
733 class matroska_stream_c
736 matroska_stream_c( demux_sys_t & demuxer )
742 virtual ~matroska_stream_c()
751 std::vector<matroska_segment_c*> segments;
759 demux_sys_t( demux_t & demux )
766 ,p_current_segment(NULL)
770 virtual ~demux_sys_t()
772 for (size_t i=0; i<streams.size(); i++)
774 for ( size_t i=0; i<opened_segments.size(); i++ )
775 delete opened_segments[i];
783 mtime_t i_chapter_time;
787 input_title_t *title;
789 std::vector<matroska_stream_c*> streams;
790 std::vector<matroska_segment_c*> opened_segments;
791 virtual_segment_c *p_current_segment;
793 /* duration of the stream */
796 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
797 void PreloadFamily( const matroska_segment_c & of_segment );
798 void PreloadLinked( matroska_segment_c *p_segment );
799 bool PreparePlayback( );
800 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
803 static int Demux ( demux_t * );
804 static int Control( demux_t *, int, va_list );
805 static void Seek ( demux_t *, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter );
807 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
809 static char *UTF8ToStr ( const UTFstring &u );
811 /*****************************************************************************
812 * Open: initializes matroska demux structures
813 *****************************************************************************/
814 static int Open( vlc_object_t * p_this )
816 demux_t *p_demux = (demux_t*)p_this;
818 matroska_stream_c *p_stream;
819 matroska_segment_c *p_segment;
821 std::string s_path, s_filename;
822 vlc_stream_io_callback *p_io_callback;
823 EbmlStream *p_io_stream;
825 /* peek the begining */
826 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
828 /* is a valid file */
829 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
830 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
832 /* Set the demux function */
833 p_demux->pf_demux = Demux;
834 p_demux->pf_control = Control;
835 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
837 p_io_callback = new vlc_stream_io_callback( p_demux->s );
838 p_io_stream = new EbmlStream( *p_io_callback );
840 if( p_io_stream == NULL )
842 msg_Err( p_demux, "failed to create EbmlStream" );
843 delete p_io_callback;
848 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
849 if( p_stream == NULL )
851 msg_Err( p_demux, "cannot find KaxSegment" );
854 p_sys->streams.push_back( p_stream );
856 p_stream->p_in = p_io_callback;
857 p_stream->p_es = p_io_stream;
859 for (size_t i=0; i<p_stream->segments.size(); i++)
861 p_stream->segments[i]->Preload();
864 p_segment = p_stream->segments[0];
865 if( p_segment->cluster != NULL )
867 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
869 // reset the stream reading to the first cluster of the segment used
870 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
873 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
874 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
876 // assume it's a regular file
877 // get the directory path
878 s_path = p_demux->psz_path;
879 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
881 s_path = s_path.substr(0,s_path.length()-1);
885 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
887 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
891 struct dirent *p_file_item;
892 DIR *p_src_dir = opendir(s_path.c_str());
894 if (p_src_dir != NULL)
896 while ((p_file_item = (dirent *) readdir(p_src_dir)))
898 if (strlen(p_file_item->d_name) > 4)
900 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
902 if (!s_filename.compare(p_demux->psz_path))
903 continue; // don't reuse the original opened file
905 #if defined(__GNUC__) && (__GNUC__ < 3)
906 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
907 !s_filename.compare("mka", s_filename.length() - 3, 3))
909 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
910 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
913 // test wether this file belongs to the our family
914 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
915 EbmlStream *p_estream = new EbmlStream(*p_file_io);
917 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
918 if ( p_stream == NULL )
920 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
926 p_stream->p_in = p_file_io;
927 p_stream->p_es = p_estream;
928 p_sys->streams.push_back( p_stream );
933 closedir( p_src_dir );
937 p_sys->PreloadFamily( *p_segment );
938 p_sys->PreloadLinked( p_segment );
939 if ( !p_sys->PreparePlayback( ) )
941 msg_Err( p_demux, "cannot use the segment" );
952 /*****************************************************************************
953 * Close: frees unused data
954 *****************************************************************************/
955 static void Close( vlc_object_t *p_this )
957 demux_t *p_demux = (demux_t*)p_this;
958 demux_sys_t *p_sys = p_demux->p_sys;
963 /*****************************************************************************
965 *****************************************************************************/
966 static int Control( demux_t *p_demux, int i_query, va_list args )
968 demux_sys_t *p_sys = p_demux->p_sys;
973 vlc_meta_t **pp_meta;
978 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
979 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
982 case DEMUX_GET_LENGTH:
983 pi64 = (int64_t*)va_arg( args, int64_t * );
984 if( p_sys->f_duration > 0.0 )
986 *pi64 = (int64_t)(p_sys->f_duration * 1000);
991 case DEMUX_GET_POSITION:
992 pf = (double*)va_arg( args, double * );
993 if ( p_sys->f_duration > 0.0 )
994 *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);
997 case DEMUX_SET_POSITION:
998 f = (double)va_arg( args, double );
999 Seek( p_demux, -1, f, NULL );
1002 case DEMUX_GET_TIME:
1003 pi64 = (int64_t*)va_arg( args, int64_t * );
1004 *pi64 = p_sys->i_pts;
1007 case DEMUX_GET_TITLE_INFO:
1008 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1010 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1011 int *pi_int = (int*)va_arg( args, int* );
1014 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1016 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1020 return VLC_EGENERIC;
1022 case DEMUX_SET_TITLE:
1023 /* TODO handle editions as titles & DVD titles as well */
1024 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1028 return VLC_EGENERIC;
1030 case DEMUX_SET_SEEKPOINT:
1031 /* FIXME do a better implementation */
1032 i_skp = (int)va_arg( args, int );
1034 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1036 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1037 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1038 p_demux->info.i_seekpoint = i_skp;
1041 return VLC_EGENERIC;
1043 case DEMUX_SET_TIME:
1046 return VLC_EGENERIC;
1050 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1062 i_level = ep->GetLevel();
1064 if( el == NULL && *pp_block != NULL )
1066 /* update the index */
1067 #define idx index[i_index - 1]
1068 if( i_index > 0 && idx.i_time == -1 )
1070 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1071 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1079 if( ep->GetLevel() > 1 )
1084 msg_Warn( &sys.demuxer, "EOF" );
1085 return VLC_EGENERIC;
1091 if( MKV_IS_ID( el, KaxCluster ) )
1093 cluster = (KaxCluster*)el;
1095 /* add it to the index */
1097 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1099 IndexAppendCluster( cluster );
1102 // reset silent tracks
1103 for (size_t i=0; i<tracks.size(); i++)
1105 tracks[i]->b_silent = VLC_FALSE;
1110 else if( MKV_IS_ID( el, KaxCues ) )
1112 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1113 return VLC_EGENERIC;
1117 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1120 else if( i_level == 2 )
1122 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1124 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1126 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1127 cluster->InitTimecode( uint64( ctc ), i_timescale );
1129 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1133 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1138 else if( i_level == 3 )
1140 if( MKV_IS_ID( el, KaxBlock ) )
1142 *pp_block = (KaxBlock*)el;
1144 (*pp_block)->ReadData( es.I_O() );
1145 (*pp_block)->SetParent( *cluster );
1149 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1151 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1153 dur.ReadData( es.I_O() );
1154 *pi_duration = uint64( dur );
1156 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1158 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1160 ref.ReadData( es.I_O() );
1161 if( *pi_ref1 == -1 )
1163 *pi_ref1 = int64( ref );
1167 *pi_ref2 = int64( ref );
1170 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1172 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1173 track_num.ReadData( es.I_O() );
1175 for (size_t i=0; i<tracks.size(); i++)
1177 if ( tracks[i]->i_number == uint32(track_num))
1179 tracks[i]->b_silent = VLC_TRUE;
1187 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1188 return VLC_EGENERIC;
1193 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1196 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1197 memcpy( p_block->p_buffer, p_mem, i_mem );
1198 //p_block->i_rate = p_input->stream.control.i_rate;
1202 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1203 mtime_t i_duration )
1205 demux_sys_t *p_sys = p_demux->p_sys;
1206 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1212 #define tk p_segment->tracks[i_track]
1213 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1215 if( tk->i_number == block->TrackNum() )
1221 if( i_track >= p_segment->tracks.size() )
1223 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1226 if( tk->p_es == NULL )
1228 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1231 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1233 return; /* discard audio packets that shouldn't be rendered */
1236 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1239 tk->b_inited = VLC_FALSE;
1243 /* First send init data */
1244 if( !tk->b_inited && tk->i_data_init > 0 )
1248 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1249 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1250 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1252 tk->b_inited = VLC_TRUE;
1255 for( i = 0; i < block->NumberFrames(); i++ )
1258 DataBuffer &data = block->GetBuffer(i);
1260 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1262 if( p_block == NULL )
1267 #if defined(HAVE_ZLIB_H)
1268 if( tk->i_compression_type )
1270 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1274 // TODO implement correct timestamping when B frames are used
1275 if( tk->fmt.i_cat != VIDEO_ES )
1277 p_block->i_dts = p_block->i_pts = i_pts;
1281 p_block->i_dts = i_pts;
1285 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1287 p_block->i_length = i_duration * 1000;
1290 es_out_Send( p_demux->out, tk->p_es, p_block );
1292 /* use time stamp only for first block */
1299 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1301 int i_upper_lvl = 0;
1303 EbmlElement *p_l0, *p_l1, *p_l2;
1304 bool b_keep_stream = false, b_keep_segment;
1306 // verify the EBML Header
1307 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1312 p_l0->SkipData(*p_estream, EbmlHead_Context);
1315 // find all segments in this file
1316 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1322 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1326 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1329 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1330 b_keep_segment = false;
1332 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1333 p_segment1->ep = ep;
1334 p_segment1->segment = (KaxSegment*)p_l0;
1336 while ((p_l1 = ep->Get()))
1338 if (MKV_IS_ID(p_l1, KaxInfo))
1340 // find the families of this segment
1341 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1343 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1344 for( i = 0; i < p_info->ListSize(); i++ )
1346 EbmlElement *l = (*p_info)[i];
1348 if( MKV_IS_ID( l, KaxSegmentUID ) )
1350 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1351 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1352 if ( !b_keep_segment )
1353 break; // this segment is already known
1354 opened_segments.push_back( p_segment1 );
1355 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1357 else if( MKV_IS_ID( l, KaxPrevUID ) )
1359 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1361 else if( MKV_IS_ID( l, KaxNextUID ) )
1363 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1365 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1367 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1368 p_segment1->families.push_back( *p_fam );
1374 if ( b_keep_segment )
1376 b_keep_stream = true;
1377 p_stream1->segments.push_back( p_segment1 );
1383 p_l0->SkipData(*p_estream, EbmlHead_Context);
1384 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1387 if ( !b_keep_stream )
1396 bool matroska_segment_c::Select( mtime_t i_start_time )
1401 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1402 for( i_track = 0; i_track < tracks.size(); i_track++ )
1404 #define tk tracks[i_track]
1405 if( tk->fmt.i_cat == UNKNOWN_ES )
1407 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1412 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1414 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1416 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1417 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1421 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1423 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1424 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1425 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1427 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1428 if( tk->fmt.i_extra > 0 )
1430 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1431 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1435 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1436 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1438 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1440 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1442 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1444 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1446 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1448 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1449 tk->fmt.b_packetized = VLC_FALSE;
1450 tk->fmt.i_extra = tk->i_extra_data;
1451 tk->fmt.p_extra = malloc( tk->i_extra_data );
1452 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1456 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1459 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1461 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1463 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1467 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1472 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1473 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1474 tk->fmt.i_codec = p_box->i_type;
1475 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1476 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1477 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1478 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1479 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1480 MP4_FreeBox_sample_vide( p_box );
1482 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1484 stream_Delete( p_mp4_stream );
1487 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1489 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1491 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1492 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1496 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1498 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1500 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1501 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1502 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1503 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1504 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1506 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1507 if( tk->fmt.i_extra > 0 )
1509 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1510 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1514 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1515 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1516 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1518 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1520 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1522 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1524 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1526 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1528 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1530 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1531 tk->fmt.i_extra = tk->i_extra_data;
1532 tk->fmt.p_extra = malloc( tk->i_extra_data );
1533 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1535 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1537 int i, i_offset = 1, i_size[3], i_extra;
1540 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1542 /* Split the 3 headers */
1543 if( tk->p_extra_data[0] != 0x02 )
1544 msg_Err( &sys.demuxer, "invalid vorbis header" );
1546 for( i = 0; i < 2; i++ )
1549 while( i_offset < tk->i_extra_data )
1551 i_size[i] += tk->p_extra_data[i_offset];
1552 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1556 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1557 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1558 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1560 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1561 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1562 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1563 for( i = 0; i < 3; i++ )
1565 *(p_extra++) = i_size[i] >> 8;
1566 *(p_extra++) = i_size[i] & 0xFF;
1567 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1569 p_extra += i_size[i];
1570 i_extra += i_size[i];
1573 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1574 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1576 int i_profile, i_srate;
1577 static unsigned int i_sample_rates[] =
1579 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1580 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1583 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1584 /* create data for faad (MP4DecSpecificDescrTag)*/
1586 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1590 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1594 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1603 for( i_srate = 0; i_srate < 13; i_srate++ )
1605 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1610 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1612 tk->fmt.i_extra = 2;
1613 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1614 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1615 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1617 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1618 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1619 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1621 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1623 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1627 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1629 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1631 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1633 /* FIXME: support this codec */
1634 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1635 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1637 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1639 /* FIXME: support this codec */
1640 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1641 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1643 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1645 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1646 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1648 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1649 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1650 !strcmp( tk->psz_codec, "S_SSA" ) ||
1651 !strcmp( tk->psz_codec, "S_ASS" ))
1653 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1654 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1656 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1658 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1659 if( tk->i_extra_data )
1662 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1663 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1664 p_buf[tk->i_extra_data] = '\0';
1666 p_start = strstr( p_buf, "size:" );
1667 if( sscanf( p_start, "size: %dx%d",
1668 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1670 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 );
1674 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1679 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1681 /* FIXME: support this codec */
1682 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1683 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1687 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1688 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1692 tk->fmt.i_priority = 1000;
1695 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1697 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1701 sys.i_start_pts = i_start_time;
1702 // reset the stream reading to the first cluster of the segment used
1703 es.I_O().setFilePointer( i_start_pos );
1706 ep = new EbmlParser( &es, segment, &sys.demuxer );
1711 void matroska_segment_c::UnSelect( )
1715 for( i_track = 0; i_track < tracks.size(); i_track++ )
1717 #define tk tracks[i_track]
1718 if ( tk->p_es != NULL )
1720 es_out_Del( sys.demuxer.out, tk->p_es );
1729 bool virtual_segment_c::Select( input_title_t & title )
1731 if ( linked_segments.size() == 0 )
1734 // !!! should be called only once !!!
1735 matroska_segment_c *p_segment;
1738 // copy editions from the first segment
1739 p_segment = linked_segments[0];
1740 p_editions = &p_segment->stored_editions;
1742 for ( i=1 ; i<linked_segments.size(); i++ )
1744 p_segment = linked_segments[i];
1745 // FIXME assume we have the same editions in all segments
1746 for (j=0; j<p_segment->stored_editions.size(); j++)
1747 (*p_editions)[j]->Append( *p_segment->stored_editions[j] );
1750 if ( Edition() != NULL )
1751 Edition()->PublishChapters( title );
1756 void chapter_edition_c::PublishChapters( input_title_t & title )
1758 title.i_seekpoint = 0;
1759 if ( title.seekpoint != NULL )
1760 free( title.seekpoint );
1761 chapter_item_c::PublishChapters( title, 0 );
1764 void chapter_item_c::PublishChapters( input_title_t & title, int i_level )
1766 if (b_display_seekpoint)
1768 seekpoint_t *sk = vlc_seekpoint_New();
1770 sk->i_level = i_level;
1771 sk->i_time_offset = i_start_time;
1772 sk->psz_name = strdup( psz_name.c_str() );
1774 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1775 title.i_seekpoint++;
1776 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1777 title.seekpoint[title.i_seekpoint-1] = sk;
1779 i_seekpoint_num = title.i_seekpoint;
1782 for ( size_t i=0; i<sub_chapters.size() ; i++)
1784 sub_chapters[i]->PublishChapters( title, i_level+1 );
1788 void virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1790 demux_sys_t & sys = *demux.p_sys;
1791 chapter_item_c *psz_curr_chapter;
1793 /* update current chapter/seekpoint */
1794 if ( p_editions->size() )
1796 /* 1st, we need to know in which chapter we are */
1797 psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
1799 /* we have moved to a new chapter */
1800 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1802 if ( psz_current_chapter != NULL )
1803 psz_current_chapter->Leave();
1805 if ( psz_curr_chapter->i_seekpoint_num > 0 )
1807 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1808 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1811 if ( (*p_editions)[i_current_edition]->b_ordered )
1813 psz_curr_chapter->Enter();
1815 // only seek if necessary
1816 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1817 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1820 psz_current_chapter = psz_curr_chapter;
1824 void chapter_item_c::Append( const chapter_item_c & chapter )
1826 // we are appending content for the same chapter UID
1828 chapter_item_c *p_chapter;
1830 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1832 p_chapter = FindChapter( *chapter.sub_chapters[i] );
1833 if ( p_chapter != NULL )
1835 p_chapter->Append( *chapter.sub_chapters[i] );
1839 sub_chapters.push_back( chapter.sub_chapters[i] );
1843 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1844 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1847 chapter_item_c * chapter_item_c::FindChapter( const chapter_item_c & chapter )
1850 for ( i=0; i<sub_chapters.size(); i++)
1852 if ( sub_chapters[i]->i_uid == chapter.i_uid )
1853 return sub_chapters[i];
1858 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
1860 demux_sys_t *p_sys = p_demux->p_sys;
1861 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1862 matroska_segment_c *p_segment = p_vsegment->Segment();
1863 mtime_t i_time_offset = 0;
1867 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1868 if( i_date < 0 && f_percent < 0 )
1870 msg_Warn( p_demux, "cannot seek nowhere !" );
1873 if( f_percent > 1.0 )
1875 msg_Warn( p_demux, "cannot seek so far !" );
1879 /* seek without index or without date */
1880 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1882 if (p_sys->f_duration >= 0)
1884 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1888 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1890 msg_Dbg( p_demux, "inacurate way of seeking" );
1891 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1893 if( p_segment->index[i_index].i_position >= i_pos)
1898 if( i_index == p_segment->i_index )
1903 i_date = p_segment->index[i_index].i_time;
1906 if( p_segment->index[i_index].i_position < i_pos )
1910 msg_Warn( p_demux, "searching for cluster, could take some time" );
1912 /* search a cluster */
1913 while( ( el = p_sys->ep->Get() ) != NULL )
1915 if( MKV_IS_ID( el, KaxCluster ) )
1917 KaxCluster *cluster = (KaxCluster*)el;
1919 /* add it to the index */
1920 p_segment->IndexAppendCluster( cluster );
1922 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1924 p_sys->cluster = cluster;
1935 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1938 /*****************************************************************************
1939 * Demux: reads and demuxes data packets
1940 *****************************************************************************
1941 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1942 *****************************************************************************/
1943 static int Demux( demux_t *p_demux)
1945 demux_sys_t *p_sys = p_demux->p_sys;
1946 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1947 matroska_segment_c *p_segmet = p_vsegment->Segment();
1948 if ( p_segmet == NULL ) return 0;
1949 int i_block_count = 0;
1952 int64_t i_block_duration;
1953 int64_t i_block_ref1;
1954 int64_t i_block_ref2;
1958 if ( p_sys->demuxer.b_die )
1961 if( p_sys->i_pts >= p_sys->i_start_pts )
1962 p_vsegment->UpdateCurrentToChapter( *p_demux );
1964 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1966 /* nothing left to read in this ordered edition */
1967 if ( !p_vsegment->SelectNext() )
1969 p_segmet->UnSelect( );
1971 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1973 /* switch to the next segment */
1974 p_segmet = p_vsegment->Segment();
1975 if ( !p_segmet->Select( 0 ) )
1977 msg_Err( p_demux, "Failed to select new segment" );
1984 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1986 if ( p_vsegment->EditionIsOrdered() )
1988 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
1989 // check if there are more chapters to read
1990 if ( p_chap != NULL )
1992 /* TODO handle successive chapters with the same user_start_time/user_end_time
1993 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
1994 p_vsegment->SelectNext();
1996 p_sys->i_pts = p_chap->i_user_end_time;
1997 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2004 msg_Warn( p_demux, "cannot get block EOF?" );
2005 p_segmet->UnSelect( );
2007 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2009 /* switch to the next segment */
2010 if ( !p_vsegment->SelectNext() )
2011 // no more segments in this stream
2013 p_segmet = p_vsegment->Segment();
2014 if ( !p_segmet->Select( 0 ) )
2016 msg_Err( p_demux, "Failed to select new segment" );
2023 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2025 if( p_sys->i_pts >= p_sys->i_start_pts )
2027 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2030 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2035 // TODO optimize when there is need to leave or when seeking has been called
2036 if( i_block_count > 5 )
2045 /*****************************************************************************
2047 *****************************************************************************/
2048 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2054 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2056 if( i_size <= 0 || mb_eof )
2061 return stream_Read( s, p_buffer, i_size );
2063 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2069 case seek_beginning:
2073 i_pos = stream_Size( s ) - i_offset;
2076 i_pos= stream_Tell( s ) + i_offset;
2080 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2087 if( stream_Seek( s, i_pos ) )
2093 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2097 uint64 vlc_stream_io_callback::getFilePointer( void )
2099 return stream_Tell( s );
2101 void vlc_stream_io_callback::close( void )
2107 /*****************************************************************************
2108 * Ebml Stream parser
2109 *****************************************************************************/
2110 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2117 mi_remain_size[0] = el_start->GetSize();
2119 for( i = 1; i < 6; i++ )
2125 mb_keep = VLC_FALSE;
2126 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2129 EbmlParser::~EbmlParser( void )
2133 for( i = 1; i < mi_level; i++ )
2139 mb_keep = VLC_FALSE;
2143 void EbmlParser::Up( void )
2145 if( mi_user_level == mi_level )
2147 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2153 void EbmlParser::Down( void )
2159 void EbmlParser::Keep( void )
2164 int EbmlParser::GetLevel( void )
2166 return mi_user_level;
2169 void EbmlParser::Reset( demux_t *p_demux )
2171 while ( mi_level > 0)
2173 delete m_el[mi_level];
2174 m_el[mi_level] = NULL;
2177 mi_user_level = mi_level = 1;
2178 #if LIBEBML_VERSION >= 0x000704
2179 // a little faster and cleaner
2180 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2182 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2184 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2187 EbmlElement *EbmlParser::Get( void )
2191 if( mi_user_level != mi_level )
2197 EbmlElement *ret = m_got;
2203 if( m_el[mi_level] )
2205 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2208 delete m_el[mi_level];
2210 mb_keep = VLC_FALSE;
2213 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2214 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2225 delete m_el[mi_level - 1];
2226 m_got = m_el[mi_level -1] = m_el[mi_level];
2227 m_el[mi_level] = NULL;
2234 else if( m_el[mi_level] == NULL )
2236 fprintf( stderr," m_el[mi_level] == NULL\n" );
2239 return m_el[mi_level];
2243 /*****************************************************************************
2245 * * LoadCues : load the cues element and update index
2247 * * LoadTags : load ... the tags element
2249 * * InformationCreate : create all information, load tags if present
2251 *****************************************************************************/
2252 void matroska_segment_c::LoadCues( )
2254 int64_t i_sav_position = es.I_O().getFilePointer();
2256 EbmlElement *el, *cues;
2258 /* *** Load the cue if found *** */
2259 if( i_cues_position < 0 )
2261 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2263 // IndexAppendCluster( cluster );
2266 vlc_bool_t b_seekable;
2268 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2272 msg_Dbg( &sys.demuxer, "loading cues" );
2273 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2274 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2278 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2279 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2283 ep = new EbmlParser( &es, cues, &sys.demuxer );
2284 while( ( el = ep->Get() ) != NULL )
2286 if( MKV_IS_ID( el, KaxCuePoint ) )
2288 #define idx index[i_index]
2291 idx.i_block_number= -1;
2292 idx.i_position = -1;
2294 idx.b_key = VLC_TRUE;
2297 while( ( el = ep->Get() ) != NULL )
2299 if( MKV_IS_ID( el, KaxCueTime ) )
2301 KaxCueTime &ctime = *(KaxCueTime*)el;
2303 ctime.ReadData( es.I_O() );
2305 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2307 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2310 while( ( el = ep->Get() ) != NULL )
2312 if( MKV_IS_ID( el, KaxCueTrack ) )
2314 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2316 ctrack.ReadData( es.I_O() );
2317 idx.i_track = uint16( ctrack );
2319 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2321 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2323 ccpos.ReadData( es.I_O() );
2324 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2326 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2328 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2330 cbnum.ReadData( es.I_O() );
2331 idx.i_block_number = uint32( cbnum );
2335 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2342 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2348 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2349 " track=%d bnum=%d", idx.i_time, idx.i_position,
2350 idx.i_track, idx.i_block_number );
2354 if( i_index >= i_index_max )
2356 i_index_max += 1024;
2357 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2363 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2371 msg_Dbg( &sys.demuxer, "loading cues done." );
2372 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2375 void matroska_segment_c::LoadTags( )
2377 int64_t i_sav_position = es.I_O().getFilePointer();
2379 EbmlElement *el, *tags;
2381 msg_Dbg( &sys.demuxer, "loading tags" );
2382 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2383 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2387 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2388 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2392 msg_Dbg( &sys.demuxer, "Tags" );
2393 ep = new EbmlParser( &es, tags, &sys.demuxer );
2394 while( ( el = ep->Get() ) != NULL )
2396 if( MKV_IS_ID( el, KaxTag ) )
2398 msg_Dbg( &sys.demuxer, "+ Tag" );
2400 while( ( el = ep->Get() ) != NULL )
2402 if( MKV_IS_ID( el, KaxTagTargets ) )
2404 msg_Dbg( &sys.demuxer, "| + Targets" );
2406 while( ( el = ep->Get() ) != NULL )
2408 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2412 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2414 msg_Dbg( &sys.demuxer, "| + General" );
2416 while( ( el = ep->Get() ) != NULL )
2418 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2422 else if( MKV_IS_ID( el, KaxTagGenres ) )
2424 msg_Dbg( &sys.demuxer, "| + Genres" );
2426 while( ( el = ep->Get() ) != NULL )
2428 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2432 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2434 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2436 while( ( el = ep->Get() ) != NULL )
2438 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2442 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2444 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2446 while( ( el = ep->Get() ) != NULL )
2448 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2452 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2454 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2456 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2458 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2460 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2462 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2464 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2466 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2468 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2470 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2472 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2474 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2476 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2478 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2482 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2489 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2495 msg_Dbg( &sys.demuxer, "loading tags done." );
2496 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2499 /*****************************************************************************
2501 *****************************************************************************/
2502 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2506 int i_upper_level = 0;
2508 msg_Dbg( &sys.demuxer, "| + Seek head" );
2510 /* Master elements */
2511 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2513 for( i = 0; i < seekhead->ListSize(); i++ )
2515 EbmlElement *l = (*seekhead)[i];
2517 if( MKV_IS_ID( l, KaxSeek ) )
2519 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2520 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2523 for( j = 0; j < sk->ListSize(); j++ )
2525 EbmlElement *l = (*sk)[j];
2527 if( MKV_IS_ID( l, KaxSeekID ) )
2529 KaxSeekID &sid = *(KaxSeekID*)l;
2530 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2532 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2534 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2535 i_pos = uint64( spos );
2539 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2545 if( id == KaxCues::ClassInfos.GlobalId )
2547 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2548 i_cues_position = segment->GetGlobalPosition( i_pos );
2550 else if( id == KaxChapters::ClassInfos.GlobalId )
2552 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2553 i_chapters_position = segment->GetGlobalPosition( i_pos );
2555 else if( id == KaxTags::ClassInfos.GlobalId )
2557 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2558 i_tags_position = segment->GetGlobalPosition( i_pos );
2564 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2569 /*****************************************************************************
2571 *****************************************************************************/
2572 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2578 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2580 tk = new mkv_track_t();
2581 tracks.push_back( tk );
2583 /* Init the track */
2584 memset( tk, 0, sizeof( mkv_track_t ) );
2586 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2587 tk->fmt.psz_language = strdup("English");
2588 tk->fmt.psz_description = NULL;
2590 tk->b_default = VLC_TRUE;
2591 tk->b_enabled = VLC_TRUE;
2592 tk->b_silent = VLC_FALSE;
2593 tk->i_number = tracks.size() - 1;
2594 tk->i_extra_data = 0;
2595 tk->p_extra_data = NULL;
2596 tk->psz_codec = NULL;
2597 tk->i_default_duration = 0;
2598 tk->f_timecodescale = 1.0;
2600 tk->b_inited = VLC_FALSE;
2601 tk->i_data_init = 0;
2602 tk->p_data_init = NULL;
2604 tk->psz_codec_name = NULL;
2605 tk->psz_codec_settings = NULL;
2606 tk->psz_codec_info_url = NULL;
2607 tk->psz_codec_download_url = NULL;
2609 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2611 for( i = 0; i < m->ListSize(); i++ )
2613 EbmlElement *l = (*m)[i];
2615 if( MKV_IS_ID( l, KaxTrackNumber ) )
2617 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2619 tk->i_number = uint32( tnum );
2620 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2622 else if( MKV_IS_ID( l, KaxTrackUID ) )
2624 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2626 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2628 else if( MKV_IS_ID( l, KaxTrackType ) )
2631 KaxTrackType &ttype = *(KaxTrackType*)l;
2633 switch( uint8(ttype) )
2637 tk->fmt.i_cat = AUDIO_ES;
2641 tk->fmt.i_cat = VIDEO_ES;
2643 case track_subtitle:
2644 psz_type = "subtitle";
2645 tk->fmt.i_cat = SPU_ES;
2648 psz_type = "unknown";
2649 tk->fmt.i_cat = UNKNOWN_ES;
2653 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2655 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2657 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2659 // tk->b_enabled = uint32( fenb );
2660 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2661 // uint32( fenb ) );
2663 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2665 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2667 tk->b_default = uint32( fdef );
2668 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2670 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2672 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2674 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2676 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2678 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2680 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2682 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2684 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2686 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2688 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2690 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2692 tk->i_default_duration = uint64(defd);
2693 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2695 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2697 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2699 tk->f_timecodescale = float( ttcs );
2700 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2702 else if( MKV_IS_ID( l, KaxTrackName ) )
2704 KaxTrackName &tname = *(KaxTrackName*)l;
2706 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2707 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2709 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2711 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2713 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2714 msg_Dbg( &sys.demuxer,
2715 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2717 else if( MKV_IS_ID( l, KaxCodecID ) )
2719 KaxCodecID &codecid = *(KaxCodecID*)l;
2721 tk->psz_codec = strdup( string( codecid ).c_str() );
2722 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2724 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2726 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2728 tk->i_extra_data = cpriv.GetSize();
2729 if( tk->i_extra_data > 0 )
2731 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2732 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2734 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2736 else if( MKV_IS_ID( l, KaxCodecName ) )
2738 KaxCodecName &cname = *(KaxCodecName*)l;
2740 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2741 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2743 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2745 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2746 MkvTree( sys.demuxer, 3, "Content Encodings" );
2747 for( j = 0; j < cencs->ListSize(); j++ )
2749 EbmlElement *l2 = (*cencs)[j];
2750 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2752 MkvTree( sys.demuxer, 4, "Content Encoding" );
2753 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2754 for( k = 0; k < cenc->ListSize(); k++ )
2756 EbmlElement *l3 = (*cenc)[k];
2757 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2759 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2760 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2762 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2764 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2765 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2767 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2769 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2770 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2772 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2774 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2775 MkvTree( sys.demuxer, 5, "Content Compression" );
2776 for( n = 0; n < compr->ListSize(); n++ )
2778 EbmlElement *l4 = (*compr)[n];
2779 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2781 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2782 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2783 if( uint32( compalg ) == 0 )
2785 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2790 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2797 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2804 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2809 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2811 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2813 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2814 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2816 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2818 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2820 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2821 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2823 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2825 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2827 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2828 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2830 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2832 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2834 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2836 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2838 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2840 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2842 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2844 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2847 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2850 for( j = 0; j < tkv->ListSize(); j++ )
2852 EbmlElement *l = (*tkv)[j];
2853 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2855 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2857 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2859 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2861 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2863 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2866 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2868 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2870 tk->fmt.video.i_width = uint16( vwidth );
2871 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2873 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2875 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2877 tk->fmt.video.i_height = uint16( vheight );
2878 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2880 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2882 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2884 tk->fmt.video.i_visible_width = uint16( vwidth );
2885 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2887 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2889 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2891 tk->fmt.video.i_visible_height = uint16( vheight );
2892 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2894 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2896 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2898 tk->f_fps = float( vfps );
2899 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2901 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2903 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2905 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2906 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2908 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2910 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2912 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2914 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2916 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2918 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2922 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2925 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2926 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2928 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2930 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2933 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2935 for( j = 0; j < tka->ListSize(); j++ )
2937 EbmlElement *l = (*tka)[j];
2939 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2941 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2943 tk->fmt.audio.i_rate = (int)float( afreq );
2944 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2946 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2948 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2950 tk->fmt.audio.i_channels = uint8( achan );
2951 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2953 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2955 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2957 tk->fmt.audio.i_bitspersample = uint8( abits );
2958 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2962 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2968 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2969 typeid(*l).name() );
2974 /*****************************************************************************
2976 *****************************************************************************/
2977 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
2981 int i_upper_level = 0;
2983 msg_Dbg( &sys.demuxer, "| + Tracks" );
2985 /* Master elements */
2986 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2988 for( i = 0; i < tracks->ListSize(); i++ )
2990 EbmlElement *l = (*tracks)[i];
2992 if( MKV_IS_ID( l, KaxTrackEntry ) )
2994 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
2998 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3003 /*****************************************************************************
3005 *****************************************************************************/
3006 void matroska_segment_c::ParseInfo( KaxInfo *info )
3011 int i_upper_level = 0;
3013 msg_Dbg( &sys.demuxer, "| + Information" );
3015 /* Master elements */
3016 m = static_cast<EbmlMaster *>(info);
3017 m->Read( es, info->Generic().Context, i_upper_level, el, true );
3019 for( i = 0; i < m->ListSize(); i++ )
3021 EbmlElement *l = (*m)[i];
3023 if( MKV_IS_ID( l, KaxSegmentUID ) )
3025 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3027 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3029 else if( MKV_IS_ID( l, KaxPrevUID ) )
3031 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3033 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3035 else if( MKV_IS_ID( l, KaxNextUID ) )
3037 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3039 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3041 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3043 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3045 i_timescale = uint64(tcs);
3047 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3050 else if( MKV_IS_ID( l, KaxDuration ) )
3052 KaxDuration &dur = *(KaxDuration*)l;
3054 i_duration = mtime_t( double( dur ) );
3056 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3059 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3061 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3063 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3065 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3066 psz_muxing_application );
3068 else if( MKV_IS_ID( l, KaxWritingApp ) )
3070 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3072 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3074 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3075 psz_writing_application );
3077 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3079 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3081 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3083 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3084 psz_segment_filename );
3086 else if( MKV_IS_ID( l, KaxTitle ) )
3088 KaxTitle &title = *(KaxTitle*)l;
3090 psz_title = UTF8ToStr( UTFstring( title ) );
3092 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3094 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3096 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3098 families.push_back(*uid);
3100 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3102 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3103 else if( MKV_IS_ID( l, KaxDateUTC ) )
3105 KaxDateUTC &date = *(KaxDateUTC*)l;
3110 i_date = date.GetEpochDate();
3111 memset( buffer, 0, 256 );
3112 if( gmtime_r( &i_date, &tmres ) &&
3113 asctime_r( &tmres, buffer ) )
3115 buffer[strlen( buffer)-1]= '\0';
3116 psz_date_utc = strdup( buffer );
3117 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3121 #if LIBMATROSKA_VERSION >= 0x000704
3122 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3124 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3125 chapter_translation_c translated;
3127 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3128 for( j = 0; j < p_trans->ListSize(); j++ )
3130 EbmlElement *l = (*p_trans)[j];
3132 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3134 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3136 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3138 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3140 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3142 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3146 translations.push_back( translated );
3151 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3155 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3156 i_duration = mtime_t(f_dur);
3160 /*****************************************************************************
3162 *****************************************************************************/
3163 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3167 if( sys.title == NULL )
3169 sys.title = vlc_input_title_New();
3172 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3173 for( i = 0; i < ca->ListSize(); i++ )
3175 EbmlElement *l = (*ca)[i];
3177 if( MKV_IS_ID( l, KaxChapterUID ) )
3179 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3180 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3182 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3184 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3185 chapters.b_display_seekpoint = uint8( flag ) == 0;
3187 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3189 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3191 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3192 chapters.i_start_time = uint64( start ) / I64C(1000);
3194 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3196 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3198 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3199 chapters.i_end_time = uint64( end ) / I64C(1000);
3201 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3203 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3205 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3207 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3208 for( j = 0; j < cd->ListSize(); j++ )
3210 EbmlElement *l= (*cd)[j];
3212 if( MKV_IS_ID( l, KaxChapterString ) )
3216 KaxChapterString &name =*(KaxChapterString*)l;
3217 for (k = 0; k < i_level; k++)
3218 chapters.psz_name += '+';
3219 chapters.psz_name += ' ';
3220 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3222 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3224 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3226 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3227 const char *psz = string( lang ).c_str();
3229 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3231 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3233 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3234 const char *psz = string( ct ).c_str();
3236 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3240 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3242 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3244 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3245 chapter_codec_cmds_c *p_ccodec = NULL;
3247 for( j = 0; j < cp->ListSize(); j++ )
3249 EbmlElement *k= (*cp)[j];
3251 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3253 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3254 if ( uint32(*p_codec_id) == 0 )
3255 p_ccodec = new matroska_script_codec_c();
3256 else if ( uint32(*p_codec_id) == 1 )
3257 p_ccodec = new dvd_chapter_codec_c();
3262 if ( p_ccodec != NULL )
3264 for( j = 0; j < cp->ListSize(); j++ )
3266 EbmlElement *k= (*cp)[j];
3268 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3270 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3271 p_ccodec->SetPrivate( *p_private );
3273 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3275 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3278 chapters.codecs.push_back( p_ccodec );
3281 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3283 chapter_item_c *new_sub_chapter = new chapter_item_c();
3284 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3285 new_sub_chapter->psz_parent = &chapters;
3286 chapters.sub_chapters.push_back( new_sub_chapter );
3291 /*****************************************************************************
3293 *****************************************************************************/
3294 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3298 int i_upper_level = 0;
3301 /* Master elements */
3302 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3304 for( i = 0; i < chapters->ListSize(); i++ )
3306 EbmlElement *l = (*chapters)[i];
3308 if( MKV_IS_ID( l, KaxEditionEntry ) )
3310 chapter_edition_c *p_edition = new chapter_edition_c();
3312 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3314 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3315 for( j = 0; j < E->ListSize(); j++ )
3317 EbmlElement *l = (*E)[j];
3319 if( MKV_IS_ID( l, KaxChapterAtom ) )
3321 chapter_item_c *new_sub_chapter = new chapter_item_c();
3322 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3323 p_edition->sub_chapters.push_back( new_sub_chapter );
3325 else if( MKV_IS_ID( l, KaxEditionUID ) )
3327 p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3329 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3331 p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3333 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3335 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3336 i_default_edition = stored_editions.size();
3340 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3343 stored_editions.push_back( p_edition );
3347 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3351 for( i = 0; i < stored_editions.size(); i++ )
3353 stored_editions[i]->RefreshChapters( );
3356 if ( stored_editions[i_default_edition]->b_ordered )
3358 /* update the duration of the segment according to the sum of all sub chapters */
3359 i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3365 void matroska_segment_c::ParseCluster( )
3370 int i_upper_level = 0;
3372 /* Master elements */
3373 m = static_cast<EbmlMaster *>( cluster );
3374 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3376 for( i = 0; i < m->ListSize(); i++ )
3378 EbmlElement *l = (*m)[i];
3380 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3382 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3384 cluster->InitTimecode( uint64( ctc ), i_timescale );
3389 i_start_time = cluster->GlobalTimecode() / 1000;
3392 /*****************************************************************************
3393 * InformationCreate:
3394 *****************************************************************************/
3395 void matroska_segment_c::InformationCreate( )
3399 sys.meta = vlc_meta_New();
3403 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3407 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3409 if( psz_segment_filename )
3411 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3413 if( psz_muxing_application )
3415 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3417 if( psz_writing_application )
3419 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3422 for( i_track = 0; i_track < tracks.size(); i_track++ )
3424 mkv_track_t *tk = tracks[i_track];
3425 vlc_meta_t *mtk = vlc_meta_New();
3427 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3428 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3429 sys.meta->track[sys.meta->i_track++] = mtk;
3431 if( tk->fmt.psz_description )
3433 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3435 if( tk->psz_codec_name )
3437 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3439 if( tk->psz_codec_settings )
3441 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3443 if( tk->psz_codec_info_url )
3445 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3447 if( tk->psz_codec_download_url )
3449 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3453 if( i_tags_position >= 0 )
3455 vlc_bool_t b_seekable;
3457 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3466 /*****************************************************************************
3468 *****************************************************************************/
3470 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3472 #define idx index[i_index]
3474 idx.i_block_number= -1;
3475 idx.i_position = cluster->GetElementPosition();
3477 idx.b_key = VLC_TRUE;
3480 if( i_index >= i_index_max )
3482 i_index_max += 1024;
3483 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3488 static char * UTF8ToStr( const UTFstring &u )
3497 p = dst = (char*)malloc( i_src + 1);
3516 void chapter_edition_c::RefreshChapters( )
3518 chapter_item_c::RefreshChapters( b_ordered, -1 );
3519 b_display_seekpoint = false;
3522 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3524 int64_t i_user_time = i_prev_user_time;
3526 // first the sub-chapters, and then ourself
3527 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3528 while ( index != sub_chapters.end() )
3530 i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3536 // the ordered chapters always start at zero
3537 if ( i_prev_user_time == -1 )
3539 if ( i_user_time == -1 )
3541 i_prev_user_time = 0;
3544 i_user_start_time = i_prev_user_time;
3545 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3547 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3551 i_user_end_time = i_user_time;
3556 std::sort( sub_chapters.begin(), sub_chapters.end() );
3557 i_user_start_time = i_start_time;
3558 if ( i_end_time != -1 )
3559 i_user_end_time = i_end_time;
3560 else if ( i_user_time != -1 )
3561 i_user_end_time = i_user_time;
3563 i_user_end_time = i_user_start_time;
3566 return i_user_end_time;
3569 mtime_t chapter_edition_c::Duration() const
3571 mtime_t i_result = 0;
3573 if ( sub_chapters.size() )
3575 std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3577 i_result = (*index)->i_user_end_time;
3583 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3585 chapter_item_c *psz_result = NULL;
3587 if ( i_user_timecode >= i_user_start_time &&
3588 ( i_user_timecode < i_user_end_time ||
3589 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3591 std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3592 while ( index != sub_chapters.end() && psz_result == NULL )
3594 psz_result = (*index)->FindTimecode( i_user_timecode );
3598 if ( psz_result == NULL )
3605 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3607 for (size_t i=0; i<opened_segments.size(); i++)
3609 opened_segments[i]->PreloadFamily( of_segment );
3612 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3617 for (size_t i=0; i<families.size(); i++)
3619 for (size_t j=0; j<of_segment.families.size(); j++)
3621 if ( families[i] == of_segment.families[j] )
3629 // preload all the linked segments for all preloaded segments
3630 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3632 size_t i_preloaded, i;
3634 delete p_current_segment;
3635 p_current_segment = new virtual_segment_c( p_segment );
3637 // fill our current virtual segment with all hard linked segments
3640 for ( i=0; i< opened_segments.size(); i++ )
3642 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3644 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3646 p_current_segment->Sort( );
3648 p_current_segment->PreloadLinked( );
3651 bool demux_sys_t::PreparePlayback( )
3653 p_current_segment->LoadCues();
3654 f_duration = p_current_segment->Duration();
3656 /* add information */
3657 p_current_segment->Segment()->InformationCreate( );
3659 p_current_segment->Segment()->Select( 0 );
3661 return p_current_segment->Select( *title );
3664 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
3666 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3667 if ( *p_itema == p_item_b->prev_segment_uid )
3670 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3671 if ( *p_itema == p_item_b->segment_uid )
3674 if ( *p_itema == p_item_b->prev_segment_uid )
3680 bool matroska_segment_c::Preload( )
3685 EbmlElement *el = NULL;
3687 ep->Reset( &sys.demuxer );
3689 while( ( el = ep->Get() ) != NULL )
3691 if( MKV_IS_ID( el, KaxInfo ) )
3693 ParseInfo( static_cast<KaxInfo*>( el ) );
3695 else if( MKV_IS_ID( el, KaxTracks ) )
3697 ParseTracks( static_cast<KaxTracks*>( el ) );
3699 else if( MKV_IS_ID( el, KaxSeekHead ) )
3701 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3703 else if( MKV_IS_ID( el, KaxCues ) )
3705 msg_Dbg( &sys.demuxer, "| + Cues" );
3707 else if( MKV_IS_ID( el, KaxCluster ) )
3709 msg_Dbg( &sys.demuxer, "| + Cluster" );
3711 cluster = (KaxCluster*)el;
3713 i_start_pos = cluster->GetElementPosition();
3717 /* stop parsing the stream */
3720 else if( MKV_IS_ID( el, KaxAttachments ) )
3722 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3724 else if( MKV_IS_ID( el, KaxChapters ) )
3726 msg_Dbg( &sys.demuxer, "| + Chapters" );
3727 ParseChapters( static_cast<KaxChapters*>( el ) );
3729 else if( MKV_IS_ID( el, KaxTag ) )
3731 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3735 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3744 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3746 for (size_t i=0; i<opened_segments.size(); i++)
3748 if ( opened_segments[i]->segment_uid == uid )
3749 return opened_segments[i];
3754 void virtual_segment_c::Sort()
3756 // keep the current segment index
3757 matroska_segment_c *p_segment = linked_segments[i_current_segment];
3759 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
3761 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3762 if ( linked_segments[i_current_segment] == p_segment )
3766 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
3769 // check if it's not already in here
3770 for ( i=0; i<linked_segments.size(); i++ )
3772 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3776 // find possible mates
3777 for ( i=0; i<linked_uids.size(); i++ )
3779 if ( p_segment->segment_uid == linked_uids[i]
3780 || p_segment->prev_segment_uid == linked_uids[i]
3781 || p_segment->next_segment_uid == linked_uids[i] )
3783 linked_segments.push_back( p_segment );
3785 AppendUID( p_segment->prev_segment_uid );
3786 AppendUID( p_segment->next_segment_uid );
3794 void virtual_segment_c::PreloadLinked( )
3796 for ( size_t i=0; i<linked_segments.size(); i++ )
3798 linked_segments[i]->Preload( );
3800 i_current_edition = linked_segments[0]->i_default_edition;
3803 mtime_t virtual_segment_c::Duration() const
3806 if ( linked_segments.size() == 0 )
3809 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
3810 // p_last_segment->ParseCluster( );
3812 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3817 void virtual_segment_c::LoadCues( )
3819 for ( size_t i=0; i<linked_segments.size(); i++ )
3821 linked_segments[i]->LoadCues();
3825 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
3827 if ( UID.GetBuffer() == NULL )
3830 for (size_t i=0; i<linked_uids.size(); i++)
3832 if ( UID == linked_uids[i] )
3835 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3838 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
3841 int i_track_skipping;
3842 int64_t i_block_duration;
3843 int64_t i_block_ref1;
3844 int64_t i_block_ref2;
3846 int64_t i_seek_position = i_start_pos;
3847 int64_t i_seek_time = i_start_time;
3853 for( ; i_idx < i_index; i_idx++ )
3855 if( index[i_idx].i_time + i_time_offset > i_date )
3866 i_seek_position = index[i_idx].i_position;
3867 i_seek_time = index[i_idx].i_time;
3870 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3871 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3873 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3876 ep = new EbmlParser( &es, segment, &sys.demuxer );
3879 sys.i_start_pts = i_date;
3881 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3883 /* now parse until key frame */
3884 #define tk tracks[i_track]
3885 i_track_skipping = 0;
3886 for( i_track = 0; i_track < tracks.size(); i_track++ )
3888 if( tk->fmt.i_cat == VIDEO_ES )
3890 tk->b_search_keyframe = VLC_TRUE;
3893 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3897 while( i_track_skipping > 0 )
3899 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3901 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3906 for( i_track = 0; i_track < tracks.size(); i_track++ )
3908 if( tk->i_number == block->TrackNum() )
3914 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3916 if( i_track < tracks.size() )
3918 if( sys.i_pts >= sys.i_start_pts )
3920 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3921 i_track_skipping = 0;
3923 else if( tk->fmt.i_cat == VIDEO_ES )
3925 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3927 tk->b_search_keyframe = VLC_FALSE;
3930 if( !tk->b_search_keyframe )
3932 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3942 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
3944 demux_sys_t *p_sys = demuxer.p_sys;
3947 // find the actual time for an ordered edition
3948 if ( psz_chapter == NULL )
3950 if ( EditionIsOrdered() )
3952 /* 1st, we need to know in which chapter we are */
3953 psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
3957 if ( psz_chapter != NULL )
3959 psz_current_chapter = psz_chapter;
3960 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3961 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3962 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3965 // find the best matching segment
3966 for ( i=0; i<linked_segments.size(); i++ )
3968 if ( i_date < linked_segments[i]->i_start_time )
3975 if ( i_current_segment != i )
3977 linked_segments[i_current_segment]->UnSelect();
3978 linked_segments[i]->Select( i_date );
3979 i_current_segment = i;
3982 linked_segments[i]->Seek( i_date, i_time_offset );
3985 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
3989 uint32 codec_time = uint32(-1);
3990 for( i = 0; i < command.ListSize(); i++ )
3992 const EbmlElement *k = command[i];
3994 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
3996 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
4001 for( i = 0; i < command.ListSize(); i++ )
4003 const EbmlElement *k = command[i];
4005 if( MKV_IS_ID( k, KaxChapterProcessData ) )
4007 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4008 switch ( codec_time )
4011 during_cmds.push_back( *p_data );
4014 enter_cmds.push_back( *p_data );
4017 leave_cmds.push_back( *p_data );
4026 bool chapter_item_c::Enter()
4028 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4029 while ( index != codecs.end() )
4037 bool chapter_item_c::Leave()
4039 std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4040 while ( index != codecs.end() )
4048 bool dvd_chapter_codec_c::Enter()
4050 std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4051 while ( index != enter_cmds.end() )
4053 if ( (*index).GetSize() )
4055 binary *p_data = (*index).GetBuffer();
4056 size_t i_size = *p_data++;
4057 // avoid reading too much from the buffer
4058 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4059 for ( ; i_size > 0; i_size--, p_data += 8 )
4061 interpretor.Interpret( p_data );
4069 bool dvd_chapter_codec_c::Leave()
4071 std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4072 while ( index != leave_cmds.end() )
4074 if ( (*index).GetSize() )
4076 binary *p_data = (*index).GetBuffer();
4077 size_t i_size = *p_data++;
4078 // avoid reading too much from the buffer
4079 i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4080 for ( ; i_size > 0; i_size--, p_data += 8 )
4082 interpretor.Interpret( p_data );
4090 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4095 uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4097 switch ( i_command )
4101 uint8 i_title = p_command[5];
4102 // TODO find in the ChapProcessPrivate matching this Title level