1 /*****************************************************************************
2 * mkv.cpp : matroska demuxer
3 *****************************************************************************
4 * Copyright (C) 2003-2004 VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Steve Lhomme <steve.lhomme@free.fr>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
28 #include <stdlib.h> /* malloc(), free() */
33 # include <time.h> /* time() */
36 #include <vlc/input.h>
38 #include <codecs.h> /* BITMAPINFOHEADER, WAVEFORMATEX */
53 /* libebml and matroska */
54 #include "ebml/EbmlHead.h"
55 #include "ebml/EbmlSubHead.h"
56 #include "ebml/EbmlStream.h"
57 #include "ebml/EbmlContexts.h"
58 #include "ebml/EbmlVoid.h"
59 #include "ebml/EbmlVersion.h"
60 #include "ebml/StdIOCallback.h"
62 #include "matroska/KaxAttachments.h"
63 #include "matroska/KaxBlock.h"
64 #include "matroska/KaxBlockData.h"
65 #include "matroska/KaxChapters.h"
66 #include "matroska/KaxCluster.h"
67 #include "matroska/KaxClusterData.h"
68 #include "matroska/KaxContexts.h"
69 #include "matroska/KaxCues.h"
70 #include "matroska/KaxCuesData.h"
71 #include "matroska/KaxInfo.h"
72 #include "matroska/KaxInfoData.h"
73 #include "matroska/KaxSeekHead.h"
74 #include "matroska/KaxSegment.h"
75 #include "matroska/KaxTag.h"
76 #include "matroska/KaxTags.h"
77 #include "matroska/KaxTagMulti.h"
78 #include "matroska/KaxTracks.h"
79 #include "matroska/KaxTrackAudio.h"
80 #include "matroska/KaxTrackVideo.h"
81 #include "matroska/KaxTrackEntryData.h"
82 #include "matroska/KaxContentEncoding.h"
83 #include "matroska/KaxVersion.h"
85 #include "ebml/StdIOCallback.h"
88 #include "mp4/libmp4.h"
94 #define MATROSKA_COMPRESSION_NONE 0
95 #define MATROSKA_COMPRESSION_ZLIB 1
97 #define MKVD_TIMECODESCALE 1000000
100 * What's between a directory and a filename?
103 #define DIRECTORY_SEPARATOR '\\'
105 #define DIRECTORY_SEPARATOR '/'
108 using namespace LIBMATROSKA_NAMESPACE;
111 /*****************************************************************************
113 *****************************************************************************/
114 static int Open ( vlc_object_t * );
115 static void Close( vlc_object_t * );
118 set_shortname( _("Matroska") );
119 set_description( _("Matroska stream demuxer" ) );
120 set_capability( "demux2", 50 );
121 set_callbacks( Open, Close );
122 set_category( CAT_INPUT );
123 set_subcategory( SUBCAT_INPUT_DEMUX );
125 add_bool( "mkv-use-ordered-chapters", 1, NULL,
126 N_("Ordered chapters"),
127 N_("Play ordered chapters as specified in the segment"), VLC_TRUE );
129 add_bool( "mkv-use-chapter-codec", 1, NULL,
130 N_("Chapter codecs"),
131 N_("Use chapter codecs found in the segment"), VLC_TRUE );
133 add_bool( "mkv-seek-percent", 0, NULL,
134 N_("Seek based on percent not time"),
135 N_("Seek based on percent not time"), VLC_TRUE );
137 add_bool( "mkv-use-dummy", 0, NULL,
138 N_("Dummy Elements"),
139 N_("Read and discard unknown EBML elements (not good for broken files)"), VLC_TRUE );
141 add_shortcut( "mka" );
142 add_shortcut( "mkv" );
145 /*****************************************************************************
147 *****************************************************************************/
149 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
150 int result, dstsize, n;
155 d_stream.zalloc = (alloc_func)0;
156 d_stream.zfree = (free_func)0;
157 d_stream.opaque = (voidpf)0;
158 result = inflateInit(&d_stream);
161 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
165 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
166 d_stream.avail_in = p_in_block->i_buffer;
168 p_block = block_New( p_this, 0 );
173 p_block = block_Realloc( p_block, 0, n * 1000 );
174 dst = (unsigned char *)p_block->p_buffer;
175 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
176 d_stream.avail_out = 1000;
177 result = inflate(&d_stream, Z_NO_FLUSH);
178 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
180 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
184 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
185 ( result != Z_STREAM_END ) );
187 dstsize = d_stream.total_out;
188 inflateEnd( &d_stream );
190 p_block = block_Realloc( p_block, 0, dstsize );
191 p_block->i_buffer = dstsize;
192 block_Release( p_in_block );
199 * Helper function to print the mkv parse tree
201 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
206 msg_Err( &demuxer, "too deep tree" );
209 va_start( args, psz_format );
210 static char *psz_foo = "| | | | | | | | | |";
211 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
212 strncpy( psz_foo2, psz_foo, 4 * i_level );
213 psz_foo2[ 4 * i_level ] = '+';
214 psz_foo2[ 4 * i_level + 1 ] = ' ';
215 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
216 __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
221 /*****************************************************************************
223 *****************************************************************************/
224 class vlc_stream_io_callback: public IOCallback
231 vlc_stream_io_callback( stream_t * );
233 virtual uint32 read ( void *p_buffer, size_t i_size);
234 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
235 virtual size_t write ( const void *p_buffer, size_t i_size);
236 virtual uint64 getFilePointer ( void );
237 virtual void close ( void );
240 /*****************************************************************************
242 *****************************************************************************/
246 EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
247 virtual ~EbmlParser( void );
251 void Reset( demux_t *p_demux );
252 EbmlElement *Get( void );
255 int GetLevel( void );
260 EbmlElement *m_el[10];
261 int64_t mi_remain_size[10];
271 /*****************************************************************************
272 * Some functions to manipulate memory
273 *****************************************************************************/
274 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
275 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
277 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
280 /*****************************************************************************
281 * definitions of structures and functions used by this plugins
282 *****************************************************************************/
285 vlc_bool_t b_default;
286 vlc_bool_t b_enabled;
287 unsigned int i_number;
290 uint8_t *p_extra_data;
294 uint64_t i_default_duration;
295 float f_timecodescale;
303 /* data to be send first */
305 uint8_t *p_data_init;
307 /* hack : it's for seek */
308 vlc_bool_t b_search_keyframe;
312 char *psz_codec_name;
313 char *psz_codec_settings;
314 char *psz_codec_info_url;
315 char *psz_codec_download_url;
317 /* encryption/compression */
318 int i_compression_type;
333 class chapter_codec_cmds_c
336 void SetPrivate( const KaxChapterProcessPrivate & private_data )
338 m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
341 void AddCommand( const KaxChapterProcessCommand & command );
344 KaxChapterProcessPrivate m_private_data;
346 std::vector<KaxChapterProcessData> enter_cmds;
347 std::vector<KaxChapterProcessData> during_cmds;
348 std::vector<KaxChapterProcessData> leave_cmds;
351 class dvd_command_interpretor_c
355 class dvd_chapter_codec_c : public chapter_codec_cmds_c
358 static dvd_command_interpretor_c interpreter;
361 class matroska_script_codec_c : public chapter_codec_cmds_c
365 class chapter_translation_c
368 KaxChapterTranslateID translated;
369 unsigned int codec_id;
370 std::vector<uint64_t> editions;
379 ,i_user_start_time(-1)
382 ,b_display_seekpoint(true)
386 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
387 void PublishChapters( input_title_t & title, int i_level );
388 const chapter_item_c * FindTimecode( mtime_t i_timecode ) const;
389 void Append( const chapter_item_c & edition );
390 chapter_item_c * FindChapter( const chapter_item_c & chapter );
392 int64_t i_start_time, i_end_time;
393 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
394 std::vector<chapter_item_c> sub_chapters;
397 bool b_display_seekpoint;
398 std::string psz_name;
399 chapter_item_c *psz_parent;
401 std::vector<chapter_codec_cmds_c> codecs;
403 bool operator<( const chapter_item_c & item ) const
405 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) );
412 class chapter_edition_c : public chapter_item_c
419 void RefreshChapters( );
420 mtime_t Duration() const;
421 void PublishChapters( input_title_t & title );
428 class matroska_segment_c
431 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
434 ,i_timescale(MKVD_TIMECODESCALE)
438 ,i_chapters_position(-1)
445 ,psz_muxing_application(NULL)
446 ,psz_writing_application(NULL)
447 ,psz_segment_filename(NULL)
450 ,i_default_edition(0)
455 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
458 virtual ~matroska_segment_c()
460 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
462 #define tk tracks[i_track]
463 if( tk->fmt.psz_description )
465 free( tk->fmt.psz_description );
469 free( tk->psz_codec );
471 if( tk->fmt.psz_language )
473 free( tk->fmt.psz_language );
479 if( psz_writing_application )
481 free( psz_writing_application );
483 if( psz_muxing_application )
485 free( psz_muxing_application );
487 if( psz_segment_filename )
489 free( psz_segment_filename );
497 free( psz_date_utc );
509 uint64_t i_timescale;
511 /* duration of the segment */
513 mtime_t i_start_time;
516 std::vector<mkv_track_t*> tracks;
519 int64_t i_cues_position;
520 int64_t i_chapters_position;
521 int64_t i_tags_position;
525 KaxSegmentUID segment_uid;
526 KaxPrevUID prev_segment_uid;
527 KaxNextUID next_segment_uid;
535 char *psz_muxing_application;
536 char *psz_writing_application;
537 char *psz_segment_filename;
541 std::vector<chapter_edition_c> stored_editions;
542 int i_default_edition;
544 std::vector<chapter_translation_c> translations;
545 std::vector<KaxSegmentFamily> families;
552 bool PreloadFamily( const matroska_segment_c & segment );
553 void ParseInfo( KaxInfo *info );
554 void ParseChapters( KaxChapters *chapters );
555 void ParseSeekHead( KaxSeekHead *seekhead );
556 void ParseTracks( KaxTracks *tracks );
557 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
558 void ParseTrackEntry( KaxTrackEntry *m );
559 void ParseCluster( );
560 void IndexAppendCluster( KaxCluster *cluster );
563 void InformationCreate( );
564 void Seek( mtime_t i_date, mtime_t i_time_offset );
565 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
566 bool Select( mtime_t i_start_time );
568 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
571 // class holding hard-linked segment together in the playback order
572 class virtual_segment_c
575 virtual_segment_c( matroska_segment_c *p_segment )
576 :i_current_segment(0)
577 ,i_current_edition(-1)
578 ,psz_current_chapter(NULL)
580 linked_segments.push_back( p_segment );
582 AppendUID( p_segment->segment_uid );
583 AppendUID( p_segment->prev_segment_uid );
584 AppendUID( p_segment->next_segment_uid );
588 size_t AddSegment( matroska_segment_c *p_segment );
589 void PreloadLinked( );
590 mtime_t Duration( ) const;
592 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_c *psz_chapter );
594 inline chapter_edition_c *Edition()
596 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
597 return &editions[i_current_edition];
601 inline bool EditionIsOrdered() const
603 return (editions.size() != 0 && i_current_edition >= 0 && editions[i_current_edition].b_ordered);
606 matroska_segment_c * Segment() const
608 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
610 return linked_segments[i_current_segment];
613 inline const chapter_item_c *CurrentChapter() const {
614 return psz_current_chapter;
619 if ( i_current_segment < linked_segments.size()-1 )
627 /* TODO handle/merge chapters here */
628 void UpdateCurrentToChapter( demux_t & demux );
629 bool Select( input_title_t & title );
632 std::vector<matroska_segment_c*> linked_segments;
633 std::vector<KaxSegmentUID> linked_uids;
634 size_t i_current_segment;
636 std::vector<chapter_edition_c> editions;
637 int i_current_edition;
638 const chapter_item_c *psz_current_chapter;
640 void AppendUID( const EbmlBinary & UID );
643 class matroska_stream_c
646 matroska_stream_c( demux_sys_t & demuxer )
652 virtual ~matroska_stream_c()
661 std::vector<matroska_segment_c*> segments;
669 demux_sys_t( demux_t & demux )
676 ,p_current_segment(NULL)
680 virtual ~demux_sys_t()
682 for (size_t i=0; i<streams.size(); i++)
684 for ( size_t i=0; i<opened_segments.size(); i++ )
685 delete opened_segments[i];
693 mtime_t i_chapter_time;
697 input_title_t *title;
699 std::vector<matroska_stream_c*> streams;
700 std::vector<matroska_segment_c*> opened_segments;
701 virtual_segment_c *p_current_segment;
703 /* duration of the stream */
706 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
707 void PreloadFamily( const matroska_segment_c & of_segment );
708 void PreloadLinked( matroska_segment_c *p_segment );
709 bool PreparePlayback( );
710 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
713 static int Demux ( demux_t * );
714 static int Control( demux_t *, int, va_list );
715 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_c *psz_chapter );
717 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
719 static char *UTF8ToStr ( const UTFstring &u );
721 /*****************************************************************************
722 * Open: initializes matroska demux structures
723 *****************************************************************************/
724 static int Open( vlc_object_t * p_this )
726 demux_t *p_demux = (demux_t*)p_this;
728 matroska_stream_c *p_stream;
729 matroska_segment_c *p_segment;
731 std::string s_path, s_filename;
732 vlc_stream_io_callback *p_io_callback;
733 EbmlStream *p_io_stream;
735 /* peek the begining */
736 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
738 /* is a valid file */
739 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
740 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
742 /* Set the demux function */
743 p_demux->pf_demux = Demux;
744 p_demux->pf_control = Control;
745 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
747 p_io_callback = new vlc_stream_io_callback( p_demux->s );
748 p_io_stream = new EbmlStream( *p_io_callback );
750 if( p_io_stream == NULL )
752 msg_Err( p_demux, "failed to create EbmlStream" );
753 delete p_io_callback;
758 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
759 if( p_stream == NULL )
761 msg_Err( p_demux, "cannot find KaxSegment" );
764 p_sys->streams.push_back( p_stream );
766 p_stream->p_in = p_io_callback;
767 p_stream->p_es = p_io_stream;
769 for (size_t i=0; i<p_stream->segments.size(); i++)
771 p_stream->segments[i]->Preload();
774 p_segment = p_stream->segments[0];
775 if( p_segment->cluster != NULL )
777 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
779 // reset the stream reading to the first cluster of the segment used
780 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
783 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
784 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
786 // assume it's a regular file
787 // get the directory path
788 s_path = p_demux->psz_path;
789 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
791 s_path = s_path.substr(0,s_path.length()-1);
795 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
797 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
801 struct dirent *p_file_item;
802 DIR *p_src_dir = opendir(s_path.c_str());
804 if (p_src_dir != NULL)
806 while ((p_file_item = (dirent *) readdir(p_src_dir)))
808 if (strlen(p_file_item->d_name) > 4)
810 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
812 if (!s_filename.compare(p_demux->psz_path))
813 continue; // don't reuse the original opened file
815 #if defined(__GNUC__) && (__GNUC__ < 3)
816 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
817 !s_filename.compare("mka", s_filename.length() - 3, 3))
819 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
820 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
823 // test wether this file belongs to the our family
824 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
825 EbmlStream *p_estream = new EbmlStream(*p_file_io);
827 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
828 if ( p_stream == NULL )
830 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
836 p_stream->p_in = p_file_io;
837 p_stream->p_es = p_estream;
838 p_sys->streams.push_back( p_stream );
843 closedir( p_src_dir );
847 p_sys->PreloadFamily( *p_segment );
848 p_sys->PreloadLinked( p_segment );
849 if ( !p_sys->PreparePlayback( ) )
851 msg_Err( p_demux, "cannot use the segment" );
862 /*****************************************************************************
863 * Close: frees unused data
864 *****************************************************************************/
865 static void Close( vlc_object_t *p_this )
867 demux_t *p_demux = (demux_t*)p_this;
868 demux_sys_t *p_sys = p_demux->p_sys;
873 /*****************************************************************************
875 *****************************************************************************/
876 static int Control( demux_t *p_demux, int i_query, va_list args )
878 demux_sys_t *p_sys = p_demux->p_sys;
883 vlc_meta_t **pp_meta;
888 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
889 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
892 case DEMUX_GET_LENGTH:
893 pi64 = (int64_t*)va_arg( args, int64_t * );
894 if( p_sys->f_duration > 0.0 )
896 *pi64 = (int64_t)(p_sys->f_duration * 1000);
901 case DEMUX_GET_POSITION:
902 pf = (double*)va_arg( args, double * );
903 if ( p_sys->f_duration > 0.0 )
904 *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);
907 case DEMUX_SET_POSITION:
908 f = (double)va_arg( args, double );
909 Seek( p_demux, -1, f, NULL );
913 pi64 = (int64_t*)va_arg( args, int64_t * );
914 *pi64 = p_sys->i_pts;
917 case DEMUX_GET_TITLE_INFO:
918 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
920 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
921 int *pi_int = (int*)va_arg( args, int* );
924 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
926 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
932 case DEMUX_SET_TITLE:
933 /* TODO handle editions as titles & DVD titles as well */
934 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
940 case DEMUX_SET_SEEKPOINT:
941 /* FIXME do a better implementation */
942 i_skp = (int)va_arg( args, int );
944 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
946 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
947 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
948 p_demux->info.i_seekpoint = i_skp;
960 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
972 i_level = ep->GetLevel();
974 if( el == NULL && *pp_block != NULL )
976 /* update the index */
977 #define idx index[i_index - 1]
978 if( i_index > 0 && idx.i_time == -1 )
980 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
981 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
989 if( ep->GetLevel() > 1 )
994 msg_Warn( &sys.demuxer, "EOF" );
1001 if( MKV_IS_ID( el, KaxCluster ) )
1003 cluster = (KaxCluster*)el;
1005 /* add it to the index */
1007 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1009 IndexAppendCluster( cluster );
1012 // reset silent tracks
1013 for (size_t i=0; i<tracks.size(); i++)
1015 tracks[i]->b_silent = VLC_FALSE;
1020 else if( MKV_IS_ID( el, KaxCues ) )
1022 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1023 return VLC_EGENERIC;
1027 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1030 else if( i_level == 2 )
1032 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1034 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1036 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1037 cluster->InitTimecode( uint64( ctc ), i_timescale );
1039 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1043 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1048 else if( i_level == 3 )
1050 if( MKV_IS_ID( el, KaxBlock ) )
1052 *pp_block = (KaxBlock*)el;
1054 (*pp_block)->ReadData( es.I_O() );
1055 (*pp_block)->SetParent( *cluster );
1059 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1061 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1063 dur.ReadData( es.I_O() );
1064 *pi_duration = uint64( dur );
1066 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1068 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1070 ref.ReadData( es.I_O() );
1071 if( *pi_ref1 == -1 )
1073 *pi_ref1 = int64( ref );
1077 *pi_ref2 = int64( ref );
1080 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1082 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1083 track_num.ReadData( es.I_O() );
1085 for (size_t i=0; i<tracks.size(); i++)
1087 if ( tracks[i]->i_number == uint32(track_num))
1089 tracks[i]->b_silent = VLC_TRUE;
1097 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1098 return VLC_EGENERIC;
1103 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1106 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1107 memcpy( p_block->p_buffer, p_mem, i_mem );
1108 //p_block->i_rate = p_input->stream.control.i_rate;
1112 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1113 mtime_t i_duration )
1115 demux_sys_t *p_sys = p_demux->p_sys;
1116 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1122 #define tk p_segment->tracks[i_track]
1123 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1125 if( tk->i_number == block->TrackNum() )
1131 if( i_track >= p_segment->tracks.size() )
1133 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1136 if( tk->p_es == NULL )
1138 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1141 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1143 return; /* discard audio packets that shouldn't be rendered */
1146 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1149 tk->b_inited = VLC_FALSE;
1153 /* First send init data */
1154 if( !tk->b_inited && tk->i_data_init > 0 )
1158 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1159 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1160 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1162 tk->b_inited = VLC_TRUE;
1165 for( i = 0; i < block->NumberFrames(); i++ )
1168 DataBuffer &data = block->GetBuffer(i);
1170 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1172 if( p_block == NULL )
1177 #if defined(HAVE_ZLIB_H)
1178 if( tk->i_compression_type )
1180 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1184 // TODO implement correct timestamping when B frames are used
1185 if( tk->fmt.i_cat != VIDEO_ES )
1187 p_block->i_dts = p_block->i_pts = i_pts;
1191 p_block->i_dts = i_pts;
1195 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1197 p_block->i_length = i_duration * 1000;
1200 es_out_Send( p_demux->out, tk->p_es, p_block );
1202 /* use time stamp only for first block */
1209 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1211 int i_upper_lvl = 0;
1213 EbmlElement *p_l0, *p_l1, *p_l2;
1214 bool b_keep_stream = false, b_keep_segment;
1216 // verify the EBML Header
1217 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1222 p_l0->SkipData(*p_estream, EbmlHead_Context);
1225 // find all segments in this file
1226 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1232 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1236 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1239 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1240 b_keep_segment = false;
1242 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1243 p_segment1->ep = ep;
1244 p_segment1->segment = (KaxSegment*)p_l0;
1246 while ((p_l1 = ep->Get()))
1248 if (MKV_IS_ID(p_l1, KaxInfo))
1250 // find the families of this segment
1251 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1253 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1254 for( i = 0; i < p_info->ListSize(); i++ )
1256 EbmlElement *l = (*p_info)[i];
1258 if( MKV_IS_ID( l, KaxSegmentUID ) )
1260 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1261 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1262 if ( !b_keep_segment )
1263 break; // this segment is already known
1264 opened_segments.push_back( p_segment1 );
1265 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1267 else if( MKV_IS_ID( l, KaxPrevUID ) )
1269 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1271 else if( MKV_IS_ID( l, KaxNextUID ) )
1273 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1275 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1277 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1278 p_segment1->families.push_back( *p_fam );
1284 if ( b_keep_segment )
1286 b_keep_stream = true;
1287 p_stream1->segments.push_back( p_segment1 );
1293 p_l0->SkipData(*p_estream, EbmlHead_Context);
1294 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1297 if ( !b_keep_stream )
1306 bool matroska_segment_c::Select( mtime_t i_start_time )
1311 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1312 for( i_track = 0; i_track < tracks.size(); i_track++ )
1314 #define tk tracks[i_track]
1315 if( tk->fmt.i_cat == UNKNOWN_ES )
1317 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1322 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1324 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1326 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1327 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1331 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1333 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1334 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1335 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1337 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1338 if( tk->fmt.i_extra > 0 )
1340 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1341 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1345 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1346 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1348 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1350 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1352 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1354 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1356 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1358 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1359 tk->fmt.b_packetized = VLC_FALSE;
1360 tk->fmt.i_extra = tk->i_extra_data;
1361 tk->fmt.p_extra = malloc( tk->i_extra_data );
1362 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1366 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1369 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1371 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1373 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1377 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1382 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1383 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1384 tk->fmt.i_codec = p_box->i_type;
1385 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1386 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1387 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1388 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1389 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1390 MP4_FreeBox_sample_vide( p_box );
1392 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1394 stream_Delete( p_mp4_stream );
1397 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1399 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1401 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1402 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1406 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1408 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1410 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1411 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1412 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1413 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1414 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1416 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1417 if( tk->fmt.i_extra > 0 )
1419 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1420 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1424 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1425 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1426 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1428 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1430 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1432 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1434 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1436 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1438 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1440 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1441 tk->fmt.i_extra = tk->i_extra_data;
1442 tk->fmt.p_extra = malloc( tk->i_extra_data );
1443 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1445 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1447 int i, i_offset = 1, i_size[3], i_extra;
1450 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1452 /* Split the 3 headers */
1453 if( tk->p_extra_data[0] != 0x02 )
1454 msg_Err( &sys.demuxer, "invalid vorbis header" );
1456 for( i = 0; i < 2; i++ )
1459 while( i_offset < tk->i_extra_data )
1461 i_size[i] += tk->p_extra_data[i_offset];
1462 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1466 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1467 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1468 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1470 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1471 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1472 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1473 for( i = 0; i < 3; i++ )
1475 *(p_extra++) = i_size[i] >> 8;
1476 *(p_extra++) = i_size[i] & 0xFF;
1477 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1479 p_extra += i_size[i];
1480 i_extra += i_size[i];
1483 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1484 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1486 int i_profile, i_srate;
1487 static unsigned int i_sample_rates[] =
1489 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1490 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1493 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1494 /* create data for faad (MP4DecSpecificDescrTag)*/
1496 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1500 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1504 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1513 for( i_srate = 0; i_srate < 13; i_srate++ )
1515 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1520 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1522 tk->fmt.i_extra = 2;
1523 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1524 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1525 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1527 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1528 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1529 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1531 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1533 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1537 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1539 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1541 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1543 /* FIXME: support this codec */
1544 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1545 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1547 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1549 /* FIXME: support this codec */
1550 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1551 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1553 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1555 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1556 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1558 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1559 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1560 !strcmp( tk->psz_codec, "S_SSA" ) ||
1561 !strcmp( tk->psz_codec, "S_ASS" ))
1563 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1564 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1566 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1568 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1569 if( tk->i_extra_data )
1572 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1573 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1574 p_buf[tk->i_extra_data] = '\0';
1576 p_start = strstr( p_buf, "size:" );
1577 if( sscanf( p_start, "size: %dx%d",
1578 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1580 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 );
1584 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1589 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1591 /* FIXME: support this codec */
1592 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1593 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1597 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1598 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1602 tk->fmt.i_priority = 1000;
1605 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1607 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1611 sys.i_start_pts = i_start_time;
1612 // reset the stream reading to the first cluster of the segment used
1613 es.I_O().setFilePointer( i_start_pos );
1616 ep = new EbmlParser( &es, segment, &sys.demuxer );
1621 void matroska_segment_c::UnSelect( )
1625 for( i_track = 0; i_track < tracks.size(); i_track++ )
1627 #define tk tracks[i_track]
1628 if ( tk->p_es != NULL )
1630 es_out_Del( sys.demuxer.out, tk->p_es );
1639 bool virtual_segment_c::Select( input_title_t & title )
1641 if ( linked_segments.size() == 0 )
1644 // !!! should be called only once !!!
1645 matroska_segment_c *p_segment;
1648 // copy editions from the first segment
1649 p_segment = linked_segments[0];
1650 editions = p_segment->stored_editions;
1652 for ( i=1 ; i<linked_segments.size(); i++ )
1654 p_segment = linked_segments[i];
1655 // FIXME assume we have the same editions in all segments
1656 for (j=0; j<p_segment->stored_editions.size(); j++)
1657 editions[j].Append( p_segment->stored_editions[j] );
1660 if ( Edition() != NULL )
1661 Edition()->PublishChapters( title );
1666 void chapter_edition_c::PublishChapters( input_title_t & title )
1668 title.i_seekpoint = 0;
1669 if ( title.seekpoint != NULL )
1670 free( title.seekpoint );
1671 chapter_item_c::PublishChapters( title, 0 );
1674 void chapter_item_c::PublishChapters( input_title_t & title, int i_level )
1676 if (b_display_seekpoint)
1678 seekpoint_t *sk = vlc_seekpoint_New();
1680 sk->i_level = i_level;
1681 sk->i_time_offset = i_start_time;
1682 sk->psz_name = strdup( psz_name.c_str() );
1684 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1685 title.i_seekpoint++;
1686 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1687 title.seekpoint[title.i_seekpoint-1] = sk;
1689 i_seekpoint_num = title.i_seekpoint;
1692 for ( size_t i=0; i<sub_chapters.size() ; i++)
1694 sub_chapters[i].PublishChapters( title, i_level+1 );
1698 void virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1700 demux_sys_t & sys = *demux.p_sys;
1701 const chapter_item_c *psz_curr_chapter;
1703 /* update current chapter/seekpoint */
1704 if ( editions.size() )
1706 /* 1st, we need to know in which chapter we are */
1707 psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1709 /* we have moved to a new chapter */
1710 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1712 if ( psz_current_chapter != NULL )
1713 psz_current_chapter->Leave();
1715 if ( psz_curr_chapter->i_seekpoint_num > 0 )
1717 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1718 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1721 if ( editions[i_current_edition].b_ordered )
1723 psz_curr_chapter->Enter();
1725 // only seek if necessary
1726 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1727 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1730 psz_current_chapter = psz_curr_chapter;
1734 void chapter_item_c::Append( const chapter_item_c & chapter )
1736 // we are appending content for the same chapter UID
1738 chapter_item_c *p_chapter;
1740 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1742 p_chapter = FindChapter( chapter.sub_chapters[i] );
1743 if ( p_chapter != NULL )
1745 p_chapter->Append( chapter.sub_chapters[i] );
1749 sub_chapters.push_back( chapter.sub_chapters[i] );
1753 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1754 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1757 chapter_item_c * chapter_item_c::FindChapter( const chapter_item_c & chapter )
1760 for ( i=0; i<sub_chapters.size(); i++)
1762 if ( sub_chapters[i].i_uid == chapter.i_uid )
1763 return &sub_chapters[i];
1768 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_c *psz_chapter )
1770 demux_sys_t *p_sys = p_demux->p_sys;
1771 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1772 matroska_segment_c *p_segment = p_vsegment->Segment();
1773 mtime_t i_time_offset = 0;
1777 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1778 if( i_date < 0 && f_percent < 0 )
1780 msg_Warn( p_demux, "cannot seek nowhere !" );
1783 if( f_percent > 1.0 )
1785 msg_Warn( p_demux, "cannot seek so far !" );
1789 /* seek without index or without date */
1790 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1792 if (p_sys->f_duration >= 0)
1794 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1798 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1800 msg_Dbg( p_demux, "inacurate way of seeking" );
1801 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1803 if( p_segment->index[i_index].i_position >= i_pos)
1808 if( i_index == p_segment->i_index )
1813 i_date = p_segment->index[i_index].i_time;
1816 if( p_segment->index[i_index].i_position < i_pos )
1820 msg_Warn( p_demux, "searching for cluster, could take some time" );
1822 /* search a cluster */
1823 while( ( el = p_sys->ep->Get() ) != NULL )
1825 if( MKV_IS_ID( el, KaxCluster ) )
1827 KaxCluster *cluster = (KaxCluster*)el;
1829 /* add it to the index */
1830 p_segment->IndexAppendCluster( cluster );
1832 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1834 p_sys->cluster = cluster;
1845 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1848 /*****************************************************************************
1849 * Demux: reads and demuxes data packets
1850 *****************************************************************************
1851 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1852 *****************************************************************************/
1853 static int Demux( demux_t *p_demux)
1855 demux_sys_t *p_sys = p_demux->p_sys;
1856 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1857 matroska_segment_c *p_segmet = p_vsegment->Segment();
1858 if ( p_segmet == NULL ) return 0;
1859 int i_block_count = 0;
1862 int64_t i_block_duration;
1863 int64_t i_block_ref1;
1864 int64_t i_block_ref2;
1868 if ( p_sys->demuxer.b_die )
1871 if( p_sys->i_pts >= p_sys->i_start_pts )
1872 p_vsegment->UpdateCurrentToChapter( *p_demux );
1874 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1876 /* nothing left to read in this ordered edition */
1877 if ( !p_vsegment->SelectNext() )
1879 p_segmet->UnSelect( );
1881 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1883 /* switch to the next segment */
1884 p_segmet = p_vsegment->Segment();
1885 if ( !p_segmet->Select( 0 ) )
1887 msg_Err( p_demux, "Failed to select new segment" );
1894 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1896 if ( p_vsegment->EditionIsOrdered() )
1898 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
1899 // check if there are more chapters to read
1900 if ( p_chap != NULL )
1902 /* TODO handle successive chapters with the same user_start_time/user_end_time
1903 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
1904 p_vsegment->SelectNext();
1906 p_sys->i_pts = p_chap->i_user_end_time;
1907 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
1914 msg_Warn( p_demux, "cannot get block EOF?" );
1915 p_segmet->UnSelect( );
1917 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1919 /* switch to the next segment */
1920 if ( !p_vsegment->SelectNext() )
1921 // no more segments in this stream
1923 p_segmet = p_vsegment->Segment();
1924 if ( !p_segmet->Select( 0 ) )
1926 msg_Err( p_demux, "Failed to select new segment" );
1933 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1935 if( p_sys->i_pts >= p_sys->i_start_pts )
1937 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1940 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1945 // TODO optimize when there is need to leave or when seeking has been called
1946 if( i_block_count > 5 )
1955 /*****************************************************************************
1957 *****************************************************************************/
1958 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1964 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1966 if( i_size <= 0 || mb_eof )
1971 return stream_Read( s, p_buffer, i_size );
1973 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1979 case seek_beginning:
1983 i_pos = stream_Size( s ) - i_offset;
1986 i_pos= stream_Tell( s ) + i_offset;
1990 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1997 if( stream_Seek( s, i_pos ) )
2003 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2007 uint64 vlc_stream_io_callback::getFilePointer( void )
2009 return stream_Tell( s );
2011 void vlc_stream_io_callback::close( void )
2017 /*****************************************************************************
2018 * Ebml Stream parser
2019 *****************************************************************************/
2020 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2027 mi_remain_size[0] = el_start->GetSize();
2029 for( i = 1; i < 6; i++ )
2035 mb_keep = VLC_FALSE;
2036 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2039 EbmlParser::~EbmlParser( void )
2043 for( i = 1; i < mi_level; i++ )
2049 mb_keep = VLC_FALSE;
2053 void EbmlParser::Up( void )
2055 if( mi_user_level == mi_level )
2057 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2063 void EbmlParser::Down( void )
2069 void EbmlParser::Keep( void )
2074 int EbmlParser::GetLevel( void )
2076 return mi_user_level;
2079 void EbmlParser::Reset( demux_t *p_demux )
2081 while ( mi_level > 0)
2083 delete m_el[mi_level];
2084 m_el[mi_level] = NULL;
2087 mi_user_level = mi_level = 1;
2088 #if LIBEBML_VERSION >= 0x000704
2089 // a little faster and cleaner
2090 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2092 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2094 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2097 EbmlElement *EbmlParser::Get( void )
2101 if( mi_user_level != mi_level )
2107 EbmlElement *ret = m_got;
2113 if( m_el[mi_level] )
2115 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2118 delete m_el[mi_level];
2120 mb_keep = VLC_FALSE;
2123 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2124 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2135 delete m_el[mi_level - 1];
2136 m_got = m_el[mi_level -1] = m_el[mi_level];
2137 m_el[mi_level] = NULL;
2144 else if( m_el[mi_level] == NULL )
2146 fprintf( stderr," m_el[mi_level] == NULL\n" );
2149 return m_el[mi_level];
2153 /*****************************************************************************
2155 * * LoadCues : load the cues element and update index
2157 * * LoadTags : load ... the tags element
2159 * * InformationCreate : create all information, load tags if present
2161 *****************************************************************************/
2162 void matroska_segment_c::LoadCues( )
2164 int64_t i_sav_position = es.I_O().getFilePointer();
2166 EbmlElement *el, *cues;
2168 /* *** Load the cue if found *** */
2169 if( i_cues_position < 0 )
2171 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2173 // IndexAppendCluster( cluster );
2176 vlc_bool_t b_seekable;
2178 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2182 msg_Dbg( &sys.demuxer, "loading cues" );
2183 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2184 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2188 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2189 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2193 ep = new EbmlParser( &es, cues, &sys.demuxer );
2194 while( ( el = ep->Get() ) != NULL )
2196 if( MKV_IS_ID( el, KaxCuePoint ) )
2198 #define idx index[i_index]
2201 idx.i_block_number= -1;
2202 idx.i_position = -1;
2204 idx.b_key = VLC_TRUE;
2207 while( ( el = ep->Get() ) != NULL )
2209 if( MKV_IS_ID( el, KaxCueTime ) )
2211 KaxCueTime &ctime = *(KaxCueTime*)el;
2213 ctime.ReadData( es.I_O() );
2215 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2217 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2220 while( ( el = ep->Get() ) != NULL )
2222 if( MKV_IS_ID( el, KaxCueTrack ) )
2224 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2226 ctrack.ReadData( es.I_O() );
2227 idx.i_track = uint16( ctrack );
2229 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2231 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2233 ccpos.ReadData( es.I_O() );
2234 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2236 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2238 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2240 cbnum.ReadData( es.I_O() );
2241 idx.i_block_number = uint32( cbnum );
2245 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2252 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2258 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2259 " track=%d bnum=%d", idx.i_time, idx.i_position,
2260 idx.i_track, idx.i_block_number );
2264 if( i_index >= i_index_max )
2266 i_index_max += 1024;
2267 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2273 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2281 msg_Dbg( &sys.demuxer, "loading cues done." );
2282 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2285 void matroska_segment_c::LoadTags( )
2287 int64_t i_sav_position = es.I_O().getFilePointer();
2289 EbmlElement *el, *tags;
2291 msg_Dbg( &sys.demuxer, "loading tags" );
2292 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2293 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2297 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2298 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2302 msg_Dbg( &sys.demuxer, "Tags" );
2303 ep = new EbmlParser( &es, tags, &sys.demuxer );
2304 while( ( el = ep->Get() ) != NULL )
2306 if( MKV_IS_ID( el, KaxTag ) )
2308 msg_Dbg( &sys.demuxer, "+ Tag" );
2310 while( ( el = ep->Get() ) != NULL )
2312 if( MKV_IS_ID( el, KaxTagTargets ) )
2314 msg_Dbg( &sys.demuxer, "| + Targets" );
2316 while( ( el = ep->Get() ) != NULL )
2318 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2322 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2324 msg_Dbg( &sys.demuxer, "| + General" );
2326 while( ( el = ep->Get() ) != NULL )
2328 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2332 else if( MKV_IS_ID( el, KaxTagGenres ) )
2334 msg_Dbg( &sys.demuxer, "| + Genres" );
2336 while( ( el = ep->Get() ) != NULL )
2338 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2342 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2344 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2346 while( ( el = ep->Get() ) != NULL )
2348 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2352 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2354 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2356 while( ( el = ep->Get() ) != NULL )
2358 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2362 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2364 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2366 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2368 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2370 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2372 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2374 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2376 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2378 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2380 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2382 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2384 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2386 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2388 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2392 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2399 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2405 msg_Dbg( &sys.demuxer, "loading tags done." );
2406 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2409 /*****************************************************************************
2411 *****************************************************************************/
2412 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2416 int i_upper_level = 0;
2418 msg_Dbg( &sys.demuxer, "| + Seek head" );
2420 /* Master elements */
2421 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2423 for( i = 0; i < seekhead->ListSize(); i++ )
2425 EbmlElement *l = (*seekhead)[i];
2427 if( MKV_IS_ID( l, KaxSeek ) )
2429 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2430 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2433 for( j = 0; j < sk->ListSize(); j++ )
2435 EbmlElement *l = (*sk)[j];
2437 if( MKV_IS_ID( l, KaxSeekID ) )
2439 KaxSeekID &sid = *(KaxSeekID*)l;
2440 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2442 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2444 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2445 i_pos = uint64( spos );
2449 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2455 if( id == KaxCues::ClassInfos.GlobalId )
2457 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2458 i_cues_position = segment->GetGlobalPosition( i_pos );
2460 else if( id == KaxChapters::ClassInfos.GlobalId )
2462 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2463 i_chapters_position = segment->GetGlobalPosition( i_pos );
2465 else if( id == KaxTags::ClassInfos.GlobalId )
2467 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2468 i_tags_position = segment->GetGlobalPosition( i_pos );
2474 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2479 /*****************************************************************************
2481 *****************************************************************************/
2482 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2488 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2490 tk = new mkv_track_t();
2491 tracks.push_back( tk );
2493 /* Init the track */
2494 memset( tk, 0, sizeof( mkv_track_t ) );
2496 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2497 tk->fmt.psz_language = strdup("English");
2498 tk->fmt.psz_description = NULL;
2500 tk->b_default = VLC_TRUE;
2501 tk->b_enabled = VLC_TRUE;
2502 tk->b_silent = VLC_FALSE;
2503 tk->i_number = tracks.size() - 1;
2504 tk->i_extra_data = 0;
2505 tk->p_extra_data = NULL;
2506 tk->psz_codec = NULL;
2507 tk->i_default_duration = 0;
2508 tk->f_timecodescale = 1.0;
2510 tk->b_inited = VLC_FALSE;
2511 tk->i_data_init = 0;
2512 tk->p_data_init = NULL;
2514 tk->psz_codec_name = NULL;
2515 tk->psz_codec_settings = NULL;
2516 tk->psz_codec_info_url = NULL;
2517 tk->psz_codec_download_url = NULL;
2519 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2521 for( i = 0; i < m->ListSize(); i++ )
2523 EbmlElement *l = (*m)[i];
2525 if( MKV_IS_ID( l, KaxTrackNumber ) )
2527 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2529 tk->i_number = uint32( tnum );
2530 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2532 else if( MKV_IS_ID( l, KaxTrackUID ) )
2534 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2536 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2538 else if( MKV_IS_ID( l, KaxTrackType ) )
2541 KaxTrackType &ttype = *(KaxTrackType*)l;
2543 switch( uint8(ttype) )
2547 tk->fmt.i_cat = AUDIO_ES;
2551 tk->fmt.i_cat = VIDEO_ES;
2553 case track_subtitle:
2554 psz_type = "subtitle";
2555 tk->fmt.i_cat = SPU_ES;
2558 psz_type = "unknown";
2559 tk->fmt.i_cat = UNKNOWN_ES;
2563 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2565 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2567 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2569 // tk->b_enabled = uint32( fenb );
2570 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2571 // uint32( fenb ) );
2573 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2575 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2577 tk->b_default = uint32( fdef );
2578 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2580 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2582 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2584 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2586 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2588 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2590 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2592 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2594 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2596 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2598 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2600 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2602 tk->i_default_duration = uint64(defd);
2603 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2605 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2607 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2609 tk->f_timecodescale = float( ttcs );
2610 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2612 else if( MKV_IS_ID( l, KaxTrackName ) )
2614 KaxTrackName &tname = *(KaxTrackName*)l;
2616 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2617 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2619 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2621 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2623 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2624 msg_Dbg( &sys.demuxer,
2625 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2627 else if( MKV_IS_ID( l, KaxCodecID ) )
2629 KaxCodecID &codecid = *(KaxCodecID*)l;
2631 tk->psz_codec = strdup( string( codecid ).c_str() );
2632 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2634 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2636 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2638 tk->i_extra_data = cpriv.GetSize();
2639 if( tk->i_extra_data > 0 )
2641 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2642 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2644 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2646 else if( MKV_IS_ID( l, KaxCodecName ) )
2648 KaxCodecName &cname = *(KaxCodecName*)l;
2650 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2651 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2653 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2655 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2656 MkvTree( sys.demuxer, 3, "Content Encodings" );
2657 for( j = 0; j < cencs->ListSize(); j++ )
2659 EbmlElement *l2 = (*cencs)[j];
2660 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2662 MkvTree( sys.demuxer, 4, "Content Encoding" );
2663 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2664 for( k = 0; k < cenc->ListSize(); k++ )
2666 EbmlElement *l3 = (*cenc)[k];
2667 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2669 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2670 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2672 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2674 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2675 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2677 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2679 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2680 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2682 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2684 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2685 MkvTree( sys.demuxer, 5, "Content Compression" );
2686 for( n = 0; n < compr->ListSize(); n++ )
2688 EbmlElement *l4 = (*compr)[n];
2689 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2691 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2692 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2693 if( uint32( compalg ) == 0 )
2695 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2700 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2707 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2714 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2719 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2721 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2723 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2724 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2726 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2728 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2730 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2731 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2733 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2735 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2737 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2738 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2740 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2742 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2744 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2746 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2748 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2750 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2752 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2754 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2757 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2760 for( j = 0; j < tkv->ListSize(); j++ )
2762 EbmlElement *l = (*tkv)[j];
2763 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2765 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2767 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2769 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2771 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2773 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2776 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2778 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2780 tk->fmt.video.i_width = uint16( vwidth );
2781 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2783 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2785 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2787 tk->fmt.video.i_height = uint16( vheight );
2788 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2790 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2792 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2794 tk->fmt.video.i_visible_width = uint16( vwidth );
2795 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2797 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2799 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2801 tk->fmt.video.i_visible_height = uint16( vheight );
2802 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2804 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2806 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2808 tk->f_fps = float( vfps );
2809 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2811 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2813 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2815 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2816 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2818 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2820 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2822 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2824 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2826 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2828 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2832 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2835 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2836 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2838 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2840 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2843 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2845 for( j = 0; j < tka->ListSize(); j++ )
2847 EbmlElement *l = (*tka)[j];
2849 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2851 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2853 tk->fmt.audio.i_rate = (int)float( afreq );
2854 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2856 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2858 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2860 tk->fmt.audio.i_channels = uint8( achan );
2861 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2863 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2865 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2867 tk->fmt.audio.i_bitspersample = uint8( abits );
2868 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2872 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2878 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2879 typeid(*l).name() );
2884 /*****************************************************************************
2886 *****************************************************************************/
2887 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
2891 int i_upper_level = 0;
2893 msg_Dbg( &sys.demuxer, "| + Tracks" );
2895 /* Master elements */
2896 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2898 for( i = 0; i < tracks->ListSize(); i++ )
2900 EbmlElement *l = (*tracks)[i];
2902 if( MKV_IS_ID( l, KaxTrackEntry ) )
2904 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
2908 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2913 /*****************************************************************************
2915 *****************************************************************************/
2916 void matroska_segment_c::ParseInfo( KaxInfo *info )
2921 int i_upper_level = 0;
2923 msg_Dbg( &sys.demuxer, "| + Information" );
2925 /* Master elements */
2926 m = static_cast<EbmlMaster *>(info);
2927 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2929 for( i = 0; i < m->ListSize(); i++ )
2931 EbmlElement *l = (*m)[i];
2933 if( MKV_IS_ID( l, KaxSegmentUID ) )
2935 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2937 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2939 else if( MKV_IS_ID( l, KaxPrevUID ) )
2941 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2943 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2945 else if( MKV_IS_ID( l, KaxNextUID ) )
2947 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2949 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2951 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2953 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2955 i_timescale = uint64(tcs);
2957 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2960 else if( MKV_IS_ID( l, KaxDuration ) )
2962 KaxDuration &dur = *(KaxDuration*)l;
2964 i_duration = mtime_t( double( dur ) );
2966 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
2969 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2971 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2973 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2975 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2976 psz_muxing_application );
2978 else if( MKV_IS_ID( l, KaxWritingApp ) )
2980 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2982 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2984 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2985 psz_writing_application );
2987 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2989 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2991 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2993 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2994 psz_segment_filename );
2996 else if( MKV_IS_ID( l, KaxTitle ) )
2998 KaxTitle &title = *(KaxTitle*)l;
3000 psz_title = UTF8ToStr( UTFstring( title ) );
3002 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3004 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3006 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3008 families.push_back(*uid);
3010 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3012 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3013 else if( MKV_IS_ID( l, KaxDateUTC ) )
3015 KaxDateUTC &date = *(KaxDateUTC*)l;
3020 i_date = date.GetEpochDate();
3021 memset( buffer, 0, 256 );
3022 if( gmtime_r( &i_date, &tmres ) &&
3023 asctime_r( &tmres, buffer ) )
3025 buffer[strlen( buffer)-1]= '\0';
3026 psz_date_utc = strdup( buffer );
3027 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3031 #if LIBMATROSKA_VERSION >= 0x000704
3032 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3034 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3035 chapter_translation_c translated;
3037 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3038 for( j = 0; j < p_trans->ListSize(); j++ )
3040 EbmlElement *l = (*p_trans)[j];
3042 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3044 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3046 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3048 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3050 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3052 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3056 translations.push_back( translated );
3061 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3065 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3066 i_duration = mtime_t(f_dur);
3070 /*****************************************************************************
3072 *****************************************************************************/
3073 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3077 if( sys.title == NULL )
3079 sys.title = vlc_input_title_New();
3082 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3083 for( i = 0; i < ca->ListSize(); i++ )
3085 EbmlElement *l = (*ca)[i];
3087 if( MKV_IS_ID( l, KaxChapterUID ) )
3089 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3090 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3092 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3094 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3095 chapters.b_display_seekpoint = uint8( flag ) == 0;
3097 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3099 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3101 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3102 chapters.i_start_time = uint64( start ) / I64C(1000);
3104 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3106 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3108 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3109 chapters.i_end_time = uint64( end ) / I64C(1000);
3111 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3113 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3115 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3117 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3118 for( j = 0; j < cd->ListSize(); j++ )
3120 EbmlElement *l= (*cd)[j];
3122 if( MKV_IS_ID( l, KaxChapterString ) )
3126 KaxChapterString &name =*(KaxChapterString*)l;
3127 for (k = 0; k < i_level; k++)
3128 chapters.psz_name += '+';
3129 chapters.psz_name += ' ';
3130 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3132 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3134 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3136 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3137 const char *psz = string( lang ).c_str();
3139 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3141 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3143 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3144 const char *psz = string( ct ).c_str();
3146 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3150 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3152 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3154 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3155 chapter_codec_cmds_c *p_ccodec = NULL;
3157 for( j = 0; j < cp->ListSize(); j++ )
3159 EbmlElement *k= (*cp)[j];
3161 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3163 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3164 if ( uint32(*p_codec_id) == 0 )
3165 p_ccodec = new matroska_script_codec_c();
3166 else if ( uint32(*p_codec_id) == 1 )
3167 p_ccodec = new dvd_chapter_codec_c();
3172 if ( p_ccodec != NULL )
3173 for( j = 0; j < cp->ListSize(); j++ )
3175 EbmlElement *k= (*cp)[j];
3177 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3179 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3180 p_ccodec->SetPrivate( *p_private );
3182 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3184 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3187 chapters.codecs.push_back( *p_ccodec );
3189 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3191 chapter_item_c new_sub_chapter;
3192 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), new_sub_chapter );
3193 new_sub_chapter.psz_parent = &chapters;
3194 chapters.sub_chapters.push_back( new_sub_chapter );
3199 /*****************************************************************************
3201 *****************************************************************************/
3202 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3206 int i_upper_level = 0;
3209 /* Master elements */
3210 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3212 for( i = 0; i < chapters->ListSize(); i++ )
3214 EbmlElement *l = (*chapters)[i];
3216 if( MKV_IS_ID( l, KaxEditionEntry ) )
3218 chapter_edition_c edition;
3220 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3222 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3223 for( j = 0; j < E->ListSize(); j++ )
3225 EbmlElement *l = (*E)[j];
3227 if( MKV_IS_ID( l, KaxChapterAtom ) )
3229 chapter_item_c new_sub_chapter;
3230 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), new_sub_chapter );
3231 edition.sub_chapters.push_back( new_sub_chapter );
3233 else if( MKV_IS_ID( l, KaxEditionUID ) )
3235 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3237 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3239 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3241 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3243 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3244 i_default_edition = stored_editions.size();
3248 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3251 stored_editions.push_back( edition );
3255 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3259 for( i = 0; i < stored_editions.size(); i++ )
3261 stored_editions[i].RefreshChapters( );
3264 if ( stored_editions[i_default_edition].b_ordered )
3266 /* update the duration of the segment according to the sum of all sub chapters */
3267 i_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3273 void matroska_segment_c::ParseCluster( )
3278 int i_upper_level = 0;
3280 /* Master elements */
3281 m = static_cast<EbmlMaster *>( cluster );
3282 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3284 for( i = 0; i < m->ListSize(); i++ )
3286 EbmlElement *l = (*m)[i];
3288 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3290 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3292 cluster->InitTimecode( uint64( ctc ), i_timescale );
3297 i_start_time = cluster->GlobalTimecode() / 1000;
3300 /*****************************************************************************
3301 * InformationCreate:
3302 *****************************************************************************/
3303 void matroska_segment_c::InformationCreate( )
3307 sys.meta = vlc_meta_New();
3311 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3315 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3317 if( psz_segment_filename )
3319 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3321 if( psz_muxing_application )
3323 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3325 if( psz_writing_application )
3327 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3330 for( i_track = 0; i_track < tracks.size(); i_track++ )
3332 mkv_track_t *tk = tracks[i_track];
3333 vlc_meta_t *mtk = vlc_meta_New();
3335 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3336 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3337 sys.meta->track[sys.meta->i_track++] = mtk;
3339 if( tk->fmt.psz_description )
3341 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3343 if( tk->psz_codec_name )
3345 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3347 if( tk->psz_codec_settings )
3349 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3351 if( tk->psz_codec_info_url )
3353 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3355 if( tk->psz_codec_download_url )
3357 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3361 if( i_tags_position >= 0 )
3363 vlc_bool_t b_seekable;
3365 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3374 /*****************************************************************************
3376 *****************************************************************************/
3378 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3380 #define idx index[i_index]
3382 idx.i_block_number= -1;
3383 idx.i_position = cluster->GetElementPosition();
3385 idx.b_key = VLC_TRUE;
3388 if( i_index >= i_index_max )
3390 i_index_max += 1024;
3391 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3396 static char * UTF8ToStr( const UTFstring &u )
3405 p = dst = (char*)malloc( i_src + 1);
3424 void chapter_edition_c::RefreshChapters( )
3426 chapter_item_c::RefreshChapters( b_ordered, -1 );
3427 b_display_seekpoint = false;
3430 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3432 int64_t i_user_time = i_prev_user_time;
3434 // first the sub-chapters, and then ourself
3435 std::vector<chapter_item_c>::iterator index = sub_chapters.begin();
3436 while ( index != sub_chapters.end() )
3438 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time );
3444 // the ordered chapters always start at zero
3445 if ( i_prev_user_time == -1 )
3447 if ( i_user_time == -1 )
3449 i_prev_user_time = 0;
3452 i_user_start_time = i_prev_user_time;
3453 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3455 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3459 i_user_end_time = i_user_time;
3464 std::sort( sub_chapters.begin(), sub_chapters.end() );
3465 i_user_start_time = i_start_time;
3466 if ( i_end_time != -1 )
3467 i_user_end_time = i_end_time;
3468 else if ( i_user_time != -1 )
3469 i_user_end_time = i_user_time;
3471 i_user_end_time = i_user_start_time;
3474 return i_user_end_time;
3477 mtime_t chapter_edition_c::Duration() const
3479 mtime_t i_result = 0;
3481 if ( sub_chapters.size() )
3483 std::vector<chapter_item_c>::const_iterator index = sub_chapters.end();
3485 i_result = (*index).i_user_end_time;
3491 const chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode ) const
3493 const chapter_item_c *psz_result = NULL;
3495 if ( i_user_timecode >= i_user_start_time &&
3496 ( i_user_timecode < i_user_end_time ||
3497 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3499 std::vector<chapter_item_c>::const_iterator index = sub_chapters.begin();
3500 while ( index != sub_chapters.end() && psz_result == NULL )
3502 psz_result = (*index).FindTimecode( i_user_timecode );
3506 if ( psz_result == NULL )
3513 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3515 for (size_t i=0; i<opened_segments.size(); i++)
3517 opened_segments[i]->PreloadFamily( of_segment );
3520 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3525 for (size_t i=0; i<families.size(); i++)
3527 for (size_t j=0; j<of_segment.families.size(); j++)
3529 if ( families[i] == of_segment.families[j] )
3537 // preload all the linked segments for all preloaded segments
3538 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3540 size_t i_preloaded, i;
3542 delete p_current_segment;
3543 p_current_segment = new virtual_segment_c( p_segment );
3545 // fill our current virtual segment with all hard linked segments
3548 for ( i=0; i< opened_segments.size(); i++ )
3550 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3552 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3554 p_current_segment->Sort( );
3556 p_current_segment->PreloadLinked( );
3559 bool demux_sys_t::PreparePlayback( )
3561 p_current_segment->LoadCues();
3562 f_duration = p_current_segment->Duration();
3564 /* add information */
3565 p_current_segment->Segment()->InformationCreate( );
3567 p_current_segment->Segment()->Select( 0 );
3569 return p_current_segment->Select( *title );
3572 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
3574 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3575 if ( *p_itema == p_item_b->prev_segment_uid )
3578 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3579 if ( *p_itema == p_item_b->segment_uid )
3582 if ( *p_itema == p_item_b->prev_segment_uid )
3588 bool matroska_segment_c::Preload( )
3593 EbmlElement *el = NULL;
3595 ep->Reset( &sys.demuxer );
3597 while( ( el = ep->Get() ) != NULL )
3599 if( MKV_IS_ID( el, KaxInfo ) )
3601 ParseInfo( static_cast<KaxInfo*>( el ) );
3603 else if( MKV_IS_ID( el, KaxTracks ) )
3605 ParseTracks( static_cast<KaxTracks*>( el ) );
3607 else if( MKV_IS_ID( el, KaxSeekHead ) )
3609 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3611 else if( MKV_IS_ID( el, KaxCues ) )
3613 msg_Dbg( &sys.demuxer, "| + Cues" );
3615 else if( MKV_IS_ID( el, KaxCluster ) )
3617 msg_Dbg( &sys.demuxer, "| + Cluster" );
3619 cluster = (KaxCluster*)el;
3621 i_start_pos = cluster->GetElementPosition();
3625 /* stop parsing the stream */
3628 else if( MKV_IS_ID( el, KaxAttachments ) )
3630 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3632 else if( MKV_IS_ID( el, KaxChapters ) )
3634 msg_Dbg( &sys.demuxer, "| + Chapters" );
3635 ParseChapters( static_cast<KaxChapters*>( el ) );
3637 else if( MKV_IS_ID( el, KaxTag ) )
3639 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3643 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3652 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3654 for (size_t i=0; i<opened_segments.size(); i++)
3656 if ( opened_segments[i]->segment_uid == uid )
3657 return opened_segments[i];
3662 void virtual_segment_c::Sort()
3664 // keep the current segment index
3665 matroska_segment_c *p_segment = linked_segments[i_current_segment];
3667 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
3669 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3670 if ( linked_segments[i_current_segment] == p_segment )
3674 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
3677 // check if it's not already in here
3678 for ( i=0; i<linked_segments.size(); i++ )
3680 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3684 // find possible mates
3685 for ( i=0; i<linked_uids.size(); i++ )
3687 if ( p_segment->segment_uid == linked_uids[i]
3688 || p_segment->prev_segment_uid == linked_uids[i]
3689 || p_segment->next_segment_uid == linked_uids[i] )
3691 linked_segments.push_back( p_segment );
3693 AppendUID( p_segment->prev_segment_uid );
3694 AppendUID( p_segment->next_segment_uid );
3702 void virtual_segment_c::PreloadLinked( )
3704 for ( size_t i=0; i<linked_segments.size(); i++ )
3706 linked_segments[i]->Preload( );
3708 i_current_edition = linked_segments[0]->i_default_edition;
3711 mtime_t virtual_segment_c::Duration() const
3714 if ( linked_segments.size() == 0 )
3717 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
3718 // p_last_segment->ParseCluster( );
3720 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3725 void virtual_segment_c::LoadCues( )
3727 for ( size_t i=0; i<linked_segments.size(); i++ )
3729 linked_segments[i]->LoadCues();
3733 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
3735 if ( UID.GetBuffer() == NULL )
3738 for (size_t i=0; i<linked_uids.size(); i++)
3740 if ( UID == linked_uids[i] )
3743 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3746 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
3749 int i_track_skipping;
3750 int64_t i_block_duration;
3751 int64_t i_block_ref1;
3752 int64_t i_block_ref2;
3754 int64_t i_seek_position = i_start_pos;
3755 int64_t i_seek_time = i_start_time;
3761 for( ; i_idx < i_index; i_idx++ )
3763 if( index[i_idx].i_time + i_time_offset > i_date )
3774 i_seek_position = index[i_idx].i_position;
3775 i_seek_time = index[i_idx].i_time;
3778 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3779 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3781 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3784 ep = new EbmlParser( &es, segment, &sys.demuxer );
3787 sys.i_start_pts = i_date;
3789 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3791 /* now parse until key frame */
3792 #define tk tracks[i_track]
3793 i_track_skipping = 0;
3794 for( i_track = 0; i_track < tracks.size(); i_track++ )
3796 if( tk->fmt.i_cat == VIDEO_ES )
3798 tk->b_search_keyframe = VLC_TRUE;
3801 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3805 while( i_track_skipping > 0 )
3807 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3809 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3814 for( i_track = 0; i_track < tracks.size(); i_track++ )
3816 if( tk->i_number == block->TrackNum() )
3822 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3824 if( i_track < tracks.size() )
3826 if( sys.i_pts >= sys.i_start_pts )
3828 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3829 i_track_skipping = 0;
3831 else if( tk->fmt.i_cat == VIDEO_ES )
3833 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3835 tk->b_search_keyframe = VLC_FALSE;
3838 if( !tk->b_search_keyframe )
3840 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3850 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_c *psz_chapter )
3852 demux_sys_t *p_sys = demuxer.p_sys;
3855 // find the actual time for an ordered edition
3856 if ( psz_chapter == NULL )
3858 if ( EditionIsOrdered() )
3860 /* 1st, we need to know in which chapter we are */
3861 psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3865 if ( psz_chapter != NULL )
3867 psz_current_chapter = psz_chapter;
3868 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3869 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3870 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3873 // find the best matching segment
3874 for ( i=0; i<linked_segments.size(); i++ )
3876 if ( i_date < linked_segments[i]->i_start_time )
3883 if ( i_current_segment != i )
3885 linked_segments[i_current_segment]->UnSelect();
3886 linked_segments[i]->Select( i_date );
3887 i_current_segment = i;
3890 linked_segments[i]->Seek( i_date, i_time_offset );
3893 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
3897 uint32 codec_time = uint32(-1);
3898 for( i = 0; i < command.ListSize(); i++ )
3900 const EbmlElement *k = command[i];
3902 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
3904 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
3909 for( i = 0; i < command.ListSize(); i++ )
3911 const EbmlElement *k = command[i];
3913 if( MKV_IS_ID( k, KaxChapterProcessData ) )
3915 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
3916 switch ( codec_time )
3919 during_cmds.push_back( *p_data );
3922 enter_cmds.push_back( *p_data );
3925 leave_cmds.push_back( *p_data );
3934 bool chapter_item_c::Enter() const
3939 bool chapter_item_c::Leave() const