1 /*****************************************************************************
2 * mkv.cpp : matroska demuxer
3 *****************************************************************************
4 * Copyright (C) 2003-2004 VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Steve Lhomme <steve.lhomme@free.fr>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
28 #include <stdlib.h> /* malloc(), free() */
33 # include <time.h> /* time() */
36 #include <vlc/input.h>
38 #include <codecs.h> /* BITMAPINFOHEADER, WAVEFORMATEX */
53 /* libebml and matroska */
54 #include "ebml/EbmlHead.h"
55 #include "ebml/EbmlSubHead.h"
56 #include "ebml/EbmlStream.h"
57 #include "ebml/EbmlContexts.h"
58 #include "ebml/EbmlVoid.h"
59 #include "ebml/EbmlVersion.h"
60 #include "ebml/StdIOCallback.h"
62 #include "matroska/KaxAttachments.h"
63 #include "matroska/KaxBlock.h"
64 #include "matroska/KaxBlockData.h"
65 #include "matroska/KaxChapters.h"
66 #include "matroska/KaxCluster.h"
67 #include "matroska/KaxClusterData.h"
68 #include "matroska/KaxContexts.h"
69 #include "matroska/KaxCues.h"
70 #include "matroska/KaxCuesData.h"
71 #include "matroska/KaxInfo.h"
72 #include "matroska/KaxInfoData.h"
73 #include "matroska/KaxSeekHead.h"
74 #include "matroska/KaxSegment.h"
75 #include "matroska/KaxTag.h"
76 #include "matroska/KaxTags.h"
77 #include "matroska/KaxTagMulti.h"
78 #include "matroska/KaxTracks.h"
79 #include "matroska/KaxTrackAudio.h"
80 #include "matroska/KaxTrackVideo.h"
81 #include "matroska/KaxTrackEntryData.h"
82 #include "matroska/KaxContentEncoding.h"
83 #include "matroska/KaxVersion.h"
85 #include "ebml/StdIOCallback.h"
88 #include "mp4/libmp4.h"
94 #define MATROSKA_COMPRESSION_NONE 0
95 #define MATROSKA_COMPRESSION_ZLIB 1
97 #define MKVD_TIMECODESCALE 1000000
100 * What's between a directory and a filename?
103 #define DIRECTORY_SEPARATOR '\\'
105 #define DIRECTORY_SEPARATOR '/'
108 using namespace LIBMATROSKA_NAMESPACE;
111 /*****************************************************************************
113 *****************************************************************************/
114 static int Open ( vlc_object_t * );
115 static void Close( vlc_object_t * );
118 set_shortname( _("Matroska") );
119 set_description( _("Matroska stream demuxer" ) );
120 set_capability( "demux2", 50 );
121 set_callbacks( Open, Close );
122 set_category( CAT_INPUT );
123 set_subcategory( SUBCAT_INPUT_DEMUX );
125 add_bool( "mkv-use-ordered-chapters", 1, NULL,
126 N_("Ordered chapters"),
127 N_("Play ordered chapters as specified in the segment"), VLC_TRUE );
129 add_bool( "mkv-use-chapter-codec", 1, NULL,
130 N_("Chapter codecs"),
131 N_("Use chapter codecs found in the segment"), VLC_TRUE );
133 add_bool( "mkv-seek-percent", 0, NULL,
134 N_("Seek based on percent not time"),
135 N_("Seek based on percent not time"), VLC_TRUE );
137 add_bool( "mkv-use-dummy", 0, NULL,
138 N_("Dummy Elements"),
139 N_("Read and discard unknown EBML elements (not good for broken files)"), VLC_TRUE );
141 add_shortcut( "mka" );
142 add_shortcut( "mkv" );
145 /*****************************************************************************
147 *****************************************************************************/
149 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
150 int result, dstsize, n;
155 d_stream.zalloc = (alloc_func)0;
156 d_stream.zfree = (free_func)0;
157 d_stream.opaque = (voidpf)0;
158 result = inflateInit(&d_stream);
161 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
165 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
166 d_stream.avail_in = p_in_block->i_buffer;
168 p_block = block_New( p_this, 0 );
173 p_block = block_Realloc( p_block, 0, n * 1000 );
174 dst = (unsigned char *)p_block->p_buffer;
175 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
176 d_stream.avail_out = 1000;
177 result = inflate(&d_stream, Z_NO_FLUSH);
178 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
180 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
184 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
185 ( result != Z_STREAM_END ) );
187 dstsize = d_stream.total_out;
188 inflateEnd( &d_stream );
190 p_block = block_Realloc( p_block, 0, dstsize );
191 p_block->i_buffer = dstsize;
192 block_Release( p_in_block );
199 * Helper function to print the mkv parse tree
201 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
206 msg_Err( &demuxer, "too deep tree" );
209 va_start( args, psz_format );
210 static char *psz_foo = "| | | | | | | | | |";
211 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
212 strncpy( psz_foo2, psz_foo, 4 * i_level );
213 psz_foo2[ 4 * i_level ] = '+';
214 psz_foo2[ 4 * i_level + 1 ] = ' ';
215 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
216 __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
221 /*****************************************************************************
223 *****************************************************************************/
224 class vlc_stream_io_callback: public IOCallback
231 vlc_stream_io_callback( stream_t * );
233 virtual uint32 read ( void *p_buffer, size_t i_size);
234 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
235 virtual size_t write ( const void *p_buffer, size_t i_size);
236 virtual uint64 getFilePointer ( void );
237 virtual void close ( void );
240 /*****************************************************************************
242 *****************************************************************************/
246 EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
247 virtual ~EbmlParser( void );
251 void Reset( demux_t *p_demux );
252 EbmlElement *Get( void );
255 int GetLevel( void );
260 EbmlElement *m_el[10];
261 int64_t mi_remain_size[10];
271 /*****************************************************************************
272 * Some functions to manipulate memory
273 *****************************************************************************/
274 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
275 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
277 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
280 /*****************************************************************************
281 * definitions of structures and functions used by this plugins
282 *****************************************************************************/
285 vlc_bool_t b_default;
286 vlc_bool_t b_enabled;
287 unsigned int i_number;
290 uint8_t *p_extra_data;
294 uint64_t i_default_duration;
295 float f_timecodescale;
303 /* data to be send first */
305 uint8_t *p_data_init;
307 /* hack : it's for seek */
308 vlc_bool_t b_search_keyframe;
312 char *psz_codec_name;
313 char *psz_codec_settings;
314 char *psz_codec_info_url;
315 char *psz_codec_download_url;
317 /* encryption/compression */
318 int i_compression_type;
333 class chapter_codec_cmds_c
336 void SetPrivate( const KaxChapterProcessPrivate & private_data )
338 m_private_data = *( new KaxChapterProcessPrivate( private_data ) );
341 void AddCommand( const KaxChapterProcessCommand & command );
343 virtual bool Enter() const {}
344 virtual bool Leave() const {}
347 KaxChapterProcessPrivate m_private_data;
349 std::vector<KaxChapterProcessData> enter_cmds;
350 std::vector<KaxChapterProcessData> during_cmds;
351 std::vector<KaxChapterProcessData> leave_cmds;
354 class dvd_command_interpretor_c
356 dvd_command_interpretor_c()
358 memset( p_GPRM, 0, sizeof(p_GPRM) * 2 );
359 memset( p_SPRM, 0, sizeof(p_SPRM) * 2 );
366 p_SPRM[ 16 ] = 0xFFFFu;
367 p_SPRM[ 18 ] = 0xFFFFu;
370 bool Interpret( const binary * p_command, size_t i_size = 8 );
373 uint16 GetGPRM( size_t index ) const
375 if ( index >= 0 && index < 16 )
376 return p_GPRM[ index ];
380 uint16 GetSPRM( size_t index ) const
382 // 21,22,23 reserved for future use
383 if ( index >= 0 && index < 21 )
384 return p_SPRM[ index ];
388 bool SetGPRM( size_t index, uint16 value )
390 if ( index >= 0 && index < 16 )
392 p_GPRM[ index ] = value;
398 bool SetSPRM( size_t index, uint16 value )
400 if ( index > 0 && index <= 13 && index != 12 )
402 p_SPRM[ index ] = value;
412 class dvd_chapter_codec_c : public chapter_codec_cmds_c
418 static dvd_command_interpretor_c interpretor;
421 class matroska_script_codec_c : public chapter_codec_cmds_c
425 class chapter_translation_c
428 KaxChapterTranslateID translated;
429 unsigned int codec_id;
430 std::vector<uint64_t> editions;
439 ,i_user_start_time(-1)
442 ,b_display_seekpoint(true)
446 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
447 void PublishChapters( input_title_t & title, int i_level );
448 const chapter_item_c * FindTimecode( mtime_t i_timecode ) const;
449 void Append( const chapter_item_c & edition );
450 chapter_item_c * FindChapter( const chapter_item_c & chapter );
452 int64_t i_start_time, i_end_time;
453 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
454 std::vector<chapter_item_c> sub_chapters;
457 bool b_display_seekpoint;
458 std::string psz_name;
459 chapter_item_c *psz_parent;
461 std::vector<chapter_codec_cmds_c> codecs;
463 bool operator<( const chapter_item_c & item ) const
465 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) );
472 class chapter_edition_c : public chapter_item_c
479 void RefreshChapters( );
480 mtime_t Duration() const;
481 void PublishChapters( input_title_t & title );
488 class matroska_segment_c
491 matroska_segment_c( demux_sys_t & demuxer, EbmlStream & estream )
494 ,i_timescale(MKVD_TIMECODESCALE)
498 ,i_chapters_position(-1)
505 ,psz_muxing_application(NULL)
506 ,psz_writing_application(NULL)
507 ,psz_segment_filename(NULL)
510 ,i_default_edition(0)
515 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
518 virtual ~matroska_segment_c()
520 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
522 #define tk tracks[i_track]
523 if( tk->fmt.psz_description )
525 free( tk->fmt.psz_description );
529 free( tk->psz_codec );
531 if( tk->fmt.psz_language )
533 free( tk->fmt.psz_language );
539 if( psz_writing_application )
541 free( psz_writing_application );
543 if( psz_muxing_application )
545 free( psz_muxing_application );
547 if( psz_segment_filename )
549 free( psz_segment_filename );
557 free( psz_date_utc );
569 uint64_t i_timescale;
571 /* duration of the segment */
573 mtime_t i_start_time;
576 std::vector<mkv_track_t*> tracks;
579 int64_t i_cues_position;
580 int64_t i_chapters_position;
581 int64_t i_tags_position;
585 KaxSegmentUID segment_uid;
586 KaxPrevUID prev_segment_uid;
587 KaxNextUID next_segment_uid;
595 char *psz_muxing_application;
596 char *psz_writing_application;
597 char *psz_segment_filename;
601 std::vector<chapter_edition_c> stored_editions;
602 int i_default_edition;
604 std::vector<chapter_translation_c> translations;
605 std::vector<KaxSegmentFamily> families;
612 bool PreloadFamily( const matroska_segment_c & segment );
613 void ParseInfo( KaxInfo *info );
614 void ParseChapters( KaxChapters *chapters );
615 void ParseSeekHead( KaxSeekHead *seekhead );
616 void ParseTracks( KaxTracks *tracks );
617 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters );
618 void ParseTrackEntry( KaxTrackEntry *m );
619 void ParseCluster( );
620 void IndexAppendCluster( KaxCluster *cluster );
623 void InformationCreate( );
624 void Seek( mtime_t i_date, mtime_t i_time_offset );
625 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
626 bool Select( mtime_t i_start_time );
628 static bool CompareSegmentUIDs( const matroska_segment_c * item_a, const matroska_segment_c * item_b );
631 // class holding hard-linked segment together in the playback order
632 class virtual_segment_c
635 virtual_segment_c( matroska_segment_c *p_segment )
636 :i_current_segment(0)
637 ,i_current_edition(-1)
638 ,psz_current_chapter(NULL)
640 linked_segments.push_back( p_segment );
642 AppendUID( p_segment->segment_uid );
643 AppendUID( p_segment->prev_segment_uid );
644 AppendUID( p_segment->next_segment_uid );
648 size_t AddSegment( matroska_segment_c *p_segment );
649 void PreloadLinked( );
650 mtime_t Duration( ) const;
652 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_c *psz_chapter );
654 inline chapter_edition_c *Edition()
656 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
657 return &editions[i_current_edition];
661 inline bool EditionIsOrdered() const
663 return (editions.size() != 0 && i_current_edition >= 0 && editions[i_current_edition].b_ordered);
666 matroska_segment_c * Segment() const
668 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
670 return linked_segments[i_current_segment];
673 inline const chapter_item_c *CurrentChapter() const {
674 return psz_current_chapter;
679 if ( i_current_segment < linked_segments.size()-1 )
687 /* TODO handle/merge chapters here */
688 void UpdateCurrentToChapter( demux_t & demux );
689 bool Select( input_title_t & title );
692 std::vector<matroska_segment_c*> linked_segments;
693 std::vector<KaxSegmentUID> linked_uids;
694 size_t i_current_segment;
696 std::vector<chapter_edition_c> editions;
697 int i_current_edition;
698 const chapter_item_c *psz_current_chapter;
700 void AppendUID( const EbmlBinary & UID );
703 class matroska_stream_c
706 matroska_stream_c( demux_sys_t & demuxer )
712 virtual ~matroska_stream_c()
721 std::vector<matroska_segment_c*> segments;
729 demux_sys_t( demux_t & demux )
736 ,p_current_segment(NULL)
740 virtual ~demux_sys_t()
742 for (size_t i=0; i<streams.size(); i++)
744 for ( size_t i=0; i<opened_segments.size(); i++ )
745 delete opened_segments[i];
753 mtime_t i_chapter_time;
757 input_title_t *title;
759 std::vector<matroska_stream_c*> streams;
760 std::vector<matroska_segment_c*> opened_segments;
761 virtual_segment_c *p_current_segment;
763 /* duration of the stream */
766 matroska_segment_c *FindSegment( const EbmlBinary & uid ) const;
767 void PreloadFamily( const matroska_segment_c & of_segment );
768 void PreloadLinked( matroska_segment_c *p_segment );
769 bool PreparePlayback( );
770 matroska_stream_c *AnalyseAllSegmentsFound( EbmlStream *p_estream );
773 static int Demux ( demux_t * );
774 static int Control( demux_t *, int, va_list );
775 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_c *psz_chapter );
777 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
779 static char *UTF8ToStr ( const UTFstring &u );
781 /*****************************************************************************
782 * Open: initializes matroska demux structures
783 *****************************************************************************/
784 static int Open( vlc_object_t * p_this )
786 demux_t *p_demux = (demux_t*)p_this;
788 matroska_stream_c *p_stream;
789 matroska_segment_c *p_segment;
791 std::string s_path, s_filename;
792 vlc_stream_io_callback *p_io_callback;
793 EbmlStream *p_io_stream;
795 /* peek the begining */
796 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
798 /* is a valid file */
799 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
800 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
802 /* Set the demux function */
803 p_demux->pf_demux = Demux;
804 p_demux->pf_control = Control;
805 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
807 p_io_callback = new vlc_stream_io_callback( p_demux->s );
808 p_io_stream = new EbmlStream( *p_io_callback );
810 if( p_io_stream == NULL )
812 msg_Err( p_demux, "failed to create EbmlStream" );
813 delete p_io_callback;
818 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
819 if( p_stream == NULL )
821 msg_Err( p_demux, "cannot find KaxSegment" );
824 p_sys->streams.push_back( p_stream );
826 p_stream->p_in = p_io_callback;
827 p_stream->p_es = p_io_stream;
829 for (size_t i=0; i<p_stream->segments.size(); i++)
831 p_stream->segments[i]->Preload();
834 p_segment = p_stream->segments[0];
835 if( p_segment->cluster != NULL )
837 msg_Warn( p_demux, "cannot find any cluster, damaged file ?" );
839 // reset the stream reading to the first cluster of the segment used
840 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
843 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
844 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
846 // assume it's a regular file
847 // get the directory path
848 s_path = p_demux->psz_path;
849 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
851 s_path = s_path.substr(0,s_path.length()-1);
855 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
857 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
861 struct dirent *p_file_item;
862 DIR *p_src_dir = opendir(s_path.c_str());
864 if (p_src_dir != NULL)
866 while ((p_file_item = (dirent *) readdir(p_src_dir)))
868 if (strlen(p_file_item->d_name) > 4)
870 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
872 if (!s_filename.compare(p_demux->psz_path))
873 continue; // don't reuse the original opened file
875 #if defined(__GNUC__) && (__GNUC__ < 3)
876 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
877 !s_filename.compare("mka", s_filename.length() - 3, 3))
879 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
880 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
883 // test wether this file belongs to the our family
884 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
885 EbmlStream *p_estream = new EbmlStream(*p_file_io);
887 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
888 if ( p_stream == NULL )
890 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
896 p_stream->p_in = p_file_io;
897 p_stream->p_es = p_estream;
898 p_sys->streams.push_back( p_stream );
903 closedir( p_src_dir );
907 p_sys->PreloadFamily( *p_segment );
908 p_sys->PreloadLinked( p_segment );
909 if ( !p_sys->PreparePlayback( ) )
911 msg_Err( p_demux, "cannot use the segment" );
922 /*****************************************************************************
923 * Close: frees unused data
924 *****************************************************************************/
925 static void Close( vlc_object_t *p_this )
927 demux_t *p_demux = (demux_t*)p_this;
928 demux_sys_t *p_sys = p_demux->p_sys;
933 /*****************************************************************************
935 *****************************************************************************/
936 static int Control( demux_t *p_demux, int i_query, va_list args )
938 demux_sys_t *p_sys = p_demux->p_sys;
943 vlc_meta_t **pp_meta;
948 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
949 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
952 case DEMUX_GET_LENGTH:
953 pi64 = (int64_t*)va_arg( args, int64_t * );
954 if( p_sys->f_duration > 0.0 )
956 *pi64 = (int64_t)(p_sys->f_duration * 1000);
961 case DEMUX_GET_POSITION:
962 pf = (double*)va_arg( args, double * );
963 if ( p_sys->f_duration > 0.0 )
964 *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);
967 case DEMUX_SET_POSITION:
968 f = (double)va_arg( args, double );
969 Seek( p_demux, -1, f, NULL );
973 pi64 = (int64_t*)va_arg( args, int64_t * );
974 *pi64 = p_sys->i_pts;
977 case DEMUX_GET_TITLE_INFO:
978 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
980 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
981 int *pi_int = (int*)va_arg( args, int* );
984 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
986 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
992 case DEMUX_SET_TITLE:
993 /* TODO handle editions as titles & DVD titles as well */
994 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1000 case DEMUX_SET_SEEKPOINT:
1001 /* FIXME do a better implementation */
1002 i_skp = (int)va_arg( args, int );
1004 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1006 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1007 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1008 p_demux->info.i_seekpoint = i_skp;
1011 return VLC_EGENERIC;
1013 case DEMUX_SET_TIME:
1016 return VLC_EGENERIC;
1020 int matroska_segment_c::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1032 i_level = ep->GetLevel();
1034 if( el == NULL && *pp_block != NULL )
1036 /* update the index */
1037 #define idx index[i_index - 1]
1038 if( i_index > 0 && idx.i_time == -1 )
1040 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1041 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1049 if( ep->GetLevel() > 1 )
1054 msg_Warn( &sys.demuxer, "EOF" );
1055 return VLC_EGENERIC;
1061 if( MKV_IS_ID( el, KaxCluster ) )
1063 cluster = (KaxCluster*)el;
1065 /* add it to the index */
1067 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1069 IndexAppendCluster( cluster );
1072 // reset silent tracks
1073 for (size_t i=0; i<tracks.size(); i++)
1075 tracks[i]->b_silent = VLC_FALSE;
1080 else if( MKV_IS_ID( el, KaxCues ) )
1082 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1083 return VLC_EGENERIC;
1087 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1090 else if( i_level == 2 )
1092 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1094 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1096 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1097 cluster->InitTimecode( uint64( ctc ), i_timescale );
1099 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1103 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1108 else if( i_level == 3 )
1110 if( MKV_IS_ID( el, KaxBlock ) )
1112 *pp_block = (KaxBlock*)el;
1114 (*pp_block)->ReadData( es.I_O() );
1115 (*pp_block)->SetParent( *cluster );
1119 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1121 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1123 dur.ReadData( es.I_O() );
1124 *pi_duration = uint64( dur );
1126 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1128 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1130 ref.ReadData( es.I_O() );
1131 if( *pi_ref1 == -1 )
1133 *pi_ref1 = int64( ref );
1137 *pi_ref2 = int64( ref );
1140 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1142 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1143 track_num.ReadData( es.I_O() );
1145 for (size_t i=0; i<tracks.size(); i++)
1147 if ( tracks[i]->i_number == uint32(track_num))
1149 tracks[i]->b_silent = VLC_TRUE;
1157 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1158 return VLC_EGENERIC;
1163 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1166 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1167 memcpy( p_block->p_buffer, p_mem, i_mem );
1168 //p_block->i_rate = p_input->stream.control.i_rate;
1172 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1173 mtime_t i_duration )
1175 demux_sys_t *p_sys = p_demux->p_sys;
1176 matroska_segment_c *p_segment = p_sys->p_current_segment->Segment();
1182 #define tk p_segment->tracks[i_track]
1183 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1185 if( tk->i_number == block->TrackNum() )
1191 if( i_track >= p_segment->tracks.size() )
1193 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1196 if( tk->p_es == NULL )
1198 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1201 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1203 return; /* discard audio packets that shouldn't be rendered */
1206 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1209 tk->b_inited = VLC_FALSE;
1213 /* First send init data */
1214 if( !tk->b_inited && tk->i_data_init > 0 )
1218 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1219 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1220 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1222 tk->b_inited = VLC_TRUE;
1225 for( i = 0; i < block->NumberFrames(); i++ )
1228 DataBuffer &data = block->GetBuffer(i);
1230 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1232 if( p_block == NULL )
1237 #if defined(HAVE_ZLIB_H)
1238 if( tk->i_compression_type )
1240 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1244 // TODO implement correct timestamping when B frames are used
1245 if( tk->fmt.i_cat != VIDEO_ES )
1247 p_block->i_dts = p_block->i_pts = i_pts;
1251 p_block->i_dts = i_pts;
1255 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1257 p_block->i_length = i_duration * 1000;
1260 es_out_Send( p_demux->out, tk->p_es, p_block );
1262 /* use time stamp only for first block */
1269 matroska_stream_c *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1271 int i_upper_lvl = 0;
1273 EbmlElement *p_l0, *p_l1, *p_l2;
1274 bool b_keep_stream = false, b_keep_segment;
1276 // verify the EBML Header
1277 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1282 p_l0->SkipData(*p_estream, EbmlHead_Context);
1285 // find all segments in this file
1286 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1292 matroska_stream_c *p_stream1 = new matroska_stream_c( *this );
1296 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1299 matroska_segment_c *p_segment1 = new matroska_segment_c( *this, *p_estream );
1300 b_keep_segment = false;
1302 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1303 p_segment1->ep = ep;
1304 p_segment1->segment = (KaxSegment*)p_l0;
1306 while ((p_l1 = ep->Get()))
1308 if (MKV_IS_ID(p_l1, KaxInfo))
1310 // find the families of this segment
1311 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1313 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1314 for( i = 0; i < p_info->ListSize(); i++ )
1316 EbmlElement *l = (*p_info)[i];
1318 if( MKV_IS_ID( l, KaxSegmentUID ) )
1320 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1321 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1322 if ( !b_keep_segment )
1323 break; // this segment is already known
1324 opened_segments.push_back( p_segment1 );
1325 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1327 else if( MKV_IS_ID( l, KaxPrevUID ) )
1329 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1331 else if( MKV_IS_ID( l, KaxNextUID ) )
1333 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1335 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1337 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1338 p_segment1->families.push_back( *p_fam );
1344 if ( b_keep_segment )
1346 b_keep_stream = true;
1347 p_stream1->segments.push_back( p_segment1 );
1353 p_l0->SkipData(*p_estream, EbmlHead_Context);
1354 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1357 if ( !b_keep_stream )
1366 bool matroska_segment_c::Select( mtime_t i_start_time )
1371 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1372 for( i_track = 0; i_track < tracks.size(); i_track++ )
1374 #define tk tracks[i_track]
1375 if( tk->fmt.i_cat == UNKNOWN_ES )
1377 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1382 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1384 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1386 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1387 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1391 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1393 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1394 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1395 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1397 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1398 if( tk->fmt.i_extra > 0 )
1400 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1401 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1405 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1406 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1408 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1410 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1412 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1414 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1416 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1418 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1419 tk->fmt.b_packetized = VLC_FALSE;
1420 tk->fmt.i_extra = tk->i_extra_data;
1421 tk->fmt.p_extra = malloc( tk->i_extra_data );
1422 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1426 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1429 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1431 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1433 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1437 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1442 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1443 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1444 tk->fmt.i_codec = p_box->i_type;
1445 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1446 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1447 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1448 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1449 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1450 MP4_FreeBox_sample_vide( p_box );
1452 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1454 stream_Delete( p_mp4_stream );
1457 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1459 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1461 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1462 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1466 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1468 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1470 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1471 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1472 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1473 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1474 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1476 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1477 if( tk->fmt.i_extra > 0 )
1479 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1480 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1484 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1485 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1486 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1488 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1490 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1492 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1494 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1496 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1498 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1500 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1501 tk->fmt.i_extra = tk->i_extra_data;
1502 tk->fmt.p_extra = malloc( tk->i_extra_data );
1503 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1505 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1507 int i, i_offset = 1, i_size[3], i_extra;
1510 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1512 /* Split the 3 headers */
1513 if( tk->p_extra_data[0] != 0x02 )
1514 msg_Err( &sys.demuxer, "invalid vorbis header" );
1516 for( i = 0; i < 2; i++ )
1519 while( i_offset < tk->i_extra_data )
1521 i_size[i] += tk->p_extra_data[i_offset];
1522 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1526 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1527 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1528 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1530 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1531 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1532 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1533 for( i = 0; i < 3; i++ )
1535 *(p_extra++) = i_size[i] >> 8;
1536 *(p_extra++) = i_size[i] & 0xFF;
1537 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1539 p_extra += i_size[i];
1540 i_extra += i_size[i];
1543 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1544 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1546 int i_profile, i_srate;
1547 static unsigned int i_sample_rates[] =
1549 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1550 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1553 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1554 /* create data for faad (MP4DecSpecificDescrTag)*/
1556 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1560 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1564 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1573 for( i_srate = 0; i_srate < 13; i_srate++ )
1575 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1580 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1582 tk->fmt.i_extra = 2;
1583 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1584 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1585 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1587 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1588 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1589 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1591 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1593 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1597 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1599 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1601 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1603 /* FIXME: support this codec */
1604 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1605 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1607 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1609 /* FIXME: support this codec */
1610 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1611 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1613 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1615 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1616 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1618 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1619 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1620 !strcmp( tk->psz_codec, "S_SSA" ) ||
1621 !strcmp( tk->psz_codec, "S_ASS" ))
1623 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1624 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1626 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1628 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1629 if( tk->i_extra_data )
1632 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1633 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1634 p_buf[tk->i_extra_data] = '\0';
1636 p_start = strstr( p_buf, "size:" );
1637 if( sscanf( p_start, "size: %dx%d",
1638 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1640 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 );
1644 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1649 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1651 /* FIXME: support this codec */
1652 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1653 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1657 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1658 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1662 tk->fmt.i_priority = 1000;
1665 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1667 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1671 sys.i_start_pts = i_start_time;
1672 // reset the stream reading to the first cluster of the segment used
1673 es.I_O().setFilePointer( i_start_pos );
1676 ep = new EbmlParser( &es, segment, &sys.demuxer );
1681 void matroska_segment_c::UnSelect( )
1685 for( i_track = 0; i_track < tracks.size(); i_track++ )
1687 #define tk tracks[i_track]
1688 if ( tk->p_es != NULL )
1690 es_out_Del( sys.demuxer.out, tk->p_es );
1699 bool virtual_segment_c::Select( input_title_t & title )
1701 if ( linked_segments.size() == 0 )
1704 // !!! should be called only once !!!
1705 matroska_segment_c *p_segment;
1708 // copy editions from the first segment
1709 p_segment = linked_segments[0];
1710 editions = p_segment->stored_editions;
1712 for ( i=1 ; i<linked_segments.size(); i++ )
1714 p_segment = linked_segments[i];
1715 // FIXME assume we have the same editions in all segments
1716 for (j=0; j<p_segment->stored_editions.size(); j++)
1717 editions[j].Append( p_segment->stored_editions[j] );
1720 if ( Edition() != NULL )
1721 Edition()->PublishChapters( title );
1726 void chapter_edition_c::PublishChapters( input_title_t & title )
1728 title.i_seekpoint = 0;
1729 if ( title.seekpoint != NULL )
1730 free( title.seekpoint );
1731 chapter_item_c::PublishChapters( title, 0 );
1734 void chapter_item_c::PublishChapters( input_title_t & title, int i_level )
1736 if (b_display_seekpoint)
1738 seekpoint_t *sk = vlc_seekpoint_New();
1740 sk->i_level = i_level;
1741 sk->i_time_offset = i_start_time;
1742 sk->psz_name = strdup( psz_name.c_str() );
1744 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1745 title.i_seekpoint++;
1746 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1747 title.seekpoint[title.i_seekpoint-1] = sk;
1749 i_seekpoint_num = title.i_seekpoint;
1752 for ( size_t i=0; i<sub_chapters.size() ; i++)
1754 sub_chapters[i].PublishChapters( title, i_level+1 );
1758 void virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1760 demux_sys_t & sys = *demux.p_sys;
1761 const chapter_item_c *psz_curr_chapter;
1763 /* update current chapter/seekpoint */
1764 if ( editions.size() )
1766 /* 1st, we need to know in which chapter we are */
1767 psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1769 /* we have moved to a new chapter */
1770 if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1772 if ( psz_current_chapter != NULL )
1773 psz_current_chapter->Leave();
1775 if ( psz_curr_chapter->i_seekpoint_num > 0 )
1777 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1778 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1781 if ( editions[i_current_edition].b_ordered )
1783 psz_curr_chapter->Enter();
1785 // only seek if necessary
1786 if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1787 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1790 psz_current_chapter = psz_curr_chapter;
1794 void chapter_item_c::Append( const chapter_item_c & chapter )
1796 // we are appending content for the same chapter UID
1798 chapter_item_c *p_chapter;
1800 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1802 p_chapter = FindChapter( chapter.sub_chapters[i] );
1803 if ( p_chapter != NULL )
1805 p_chapter->Append( chapter.sub_chapters[i] );
1809 sub_chapters.push_back( chapter.sub_chapters[i] );
1813 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1814 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1817 chapter_item_c * chapter_item_c::FindChapter( const chapter_item_c & chapter )
1820 for ( i=0; i<sub_chapters.size(); i++)
1822 if ( sub_chapters[i].i_uid == chapter.i_uid )
1823 return &sub_chapters[i];
1828 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_c *psz_chapter )
1830 demux_sys_t *p_sys = p_demux->p_sys;
1831 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1832 matroska_segment_c *p_segment = p_vsegment->Segment();
1833 mtime_t i_time_offset = 0;
1837 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1838 if( i_date < 0 && f_percent < 0 )
1840 msg_Warn( p_demux, "cannot seek nowhere !" );
1843 if( f_percent > 1.0 )
1845 msg_Warn( p_demux, "cannot seek so far !" );
1849 /* seek without index or without date */
1850 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1852 if (p_sys->f_duration >= 0)
1854 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1858 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1860 msg_Dbg( p_demux, "inacurate way of seeking" );
1861 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1863 if( p_segment->index[i_index].i_position >= i_pos)
1868 if( i_index == p_segment->i_index )
1873 i_date = p_segment->index[i_index].i_time;
1876 if( p_segment->index[i_index].i_position < i_pos )
1880 msg_Warn( p_demux, "searching for cluster, could take some time" );
1882 /* search a cluster */
1883 while( ( el = p_sys->ep->Get() ) != NULL )
1885 if( MKV_IS_ID( el, KaxCluster ) )
1887 KaxCluster *cluster = (KaxCluster*)el;
1889 /* add it to the index */
1890 p_segment->IndexAppendCluster( cluster );
1892 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1894 p_sys->cluster = cluster;
1905 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1908 /*****************************************************************************
1909 * Demux: reads and demuxes data packets
1910 *****************************************************************************
1911 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1912 *****************************************************************************/
1913 static int Demux( demux_t *p_demux)
1915 demux_sys_t *p_sys = p_demux->p_sys;
1916 virtual_segment_c *p_vsegment = p_sys->p_current_segment;
1917 matroska_segment_c *p_segmet = p_vsegment->Segment();
1918 if ( p_segmet == NULL ) return 0;
1919 int i_block_count = 0;
1922 int64_t i_block_duration;
1923 int64_t i_block_ref1;
1924 int64_t i_block_ref2;
1928 if ( p_sys->demuxer.b_die )
1931 if( p_sys->i_pts >= p_sys->i_start_pts )
1932 p_vsegment->UpdateCurrentToChapter( *p_demux );
1934 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1936 /* nothing left to read in this ordered edition */
1937 if ( !p_vsegment->SelectNext() )
1939 p_segmet->UnSelect( );
1941 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1943 /* switch to the next segment */
1944 p_segmet = p_vsegment->Segment();
1945 if ( !p_segmet->Select( 0 ) )
1947 msg_Err( p_demux, "Failed to select new segment" );
1954 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1956 if ( p_vsegment->EditionIsOrdered() )
1958 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
1959 // check if there are more chapters to read
1960 if ( p_chap != NULL )
1962 /* TODO handle successive chapters with the same user_start_time/user_end_time
1963 if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
1964 p_vsegment->SelectNext();
1966 p_sys->i_pts = p_chap->i_user_end_time;
1967 p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
1974 msg_Warn( p_demux, "cannot get block EOF?" );
1975 p_segmet->UnSelect( );
1977 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1979 /* switch to the next segment */
1980 if ( !p_vsegment->SelectNext() )
1981 // no more segments in this stream
1983 p_segmet = p_vsegment->Segment();
1984 if ( !p_segmet->Select( 0 ) )
1986 msg_Err( p_demux, "Failed to select new segment" );
1993 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1995 if( p_sys->i_pts >= p_sys->i_start_pts )
1997 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2000 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2005 // TODO optimize when there is need to leave or when seeking has been called
2006 if( i_block_count > 5 )
2015 /*****************************************************************************
2017 *****************************************************************************/
2018 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2024 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2026 if( i_size <= 0 || mb_eof )
2031 return stream_Read( s, p_buffer, i_size );
2033 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2039 case seek_beginning:
2043 i_pos = stream_Size( s ) - i_offset;
2046 i_pos= stream_Tell( s ) + i_offset;
2050 if( i_pos < 0 || i_pos >= stream_Size( s ) )
2057 if( stream_Seek( s, i_pos ) )
2063 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2067 uint64 vlc_stream_io_callback::getFilePointer( void )
2069 return stream_Tell( s );
2071 void vlc_stream_io_callback::close( void )
2077 /*****************************************************************************
2078 * Ebml Stream parser
2079 *****************************************************************************/
2080 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2087 mi_remain_size[0] = el_start->GetSize();
2089 for( i = 1; i < 6; i++ )
2095 mb_keep = VLC_FALSE;
2096 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2099 EbmlParser::~EbmlParser( void )
2103 for( i = 1; i < mi_level; i++ )
2109 mb_keep = VLC_FALSE;
2113 void EbmlParser::Up( void )
2115 if( mi_user_level == mi_level )
2117 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2123 void EbmlParser::Down( void )
2129 void EbmlParser::Keep( void )
2134 int EbmlParser::GetLevel( void )
2136 return mi_user_level;
2139 void EbmlParser::Reset( demux_t *p_demux )
2141 while ( mi_level > 0)
2143 delete m_el[mi_level];
2144 m_el[mi_level] = NULL;
2147 mi_user_level = mi_level = 1;
2148 #if LIBEBML_VERSION >= 0x000704
2149 // a little faster and cleaner
2150 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2152 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2154 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2157 EbmlElement *EbmlParser::Get( void )
2161 if( mi_user_level != mi_level )
2167 EbmlElement *ret = m_got;
2173 if( m_el[mi_level] )
2175 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2178 delete m_el[mi_level];
2180 mb_keep = VLC_FALSE;
2183 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2184 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2195 delete m_el[mi_level - 1];
2196 m_got = m_el[mi_level -1] = m_el[mi_level];
2197 m_el[mi_level] = NULL;
2204 else if( m_el[mi_level] == NULL )
2206 fprintf( stderr," m_el[mi_level] == NULL\n" );
2209 return m_el[mi_level];
2213 /*****************************************************************************
2215 * * LoadCues : load the cues element and update index
2217 * * LoadTags : load ... the tags element
2219 * * InformationCreate : create all information, load tags if present
2221 *****************************************************************************/
2222 void matroska_segment_c::LoadCues( )
2224 int64_t i_sav_position = es.I_O().getFilePointer();
2226 EbmlElement *el, *cues;
2228 /* *** Load the cue if found *** */
2229 if( i_cues_position < 0 )
2231 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2233 // IndexAppendCluster( cluster );
2236 vlc_bool_t b_seekable;
2238 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2242 msg_Dbg( &sys.demuxer, "loading cues" );
2243 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2244 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2248 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2249 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2253 ep = new EbmlParser( &es, cues, &sys.demuxer );
2254 while( ( el = ep->Get() ) != NULL )
2256 if( MKV_IS_ID( el, KaxCuePoint ) )
2258 #define idx index[i_index]
2261 idx.i_block_number= -1;
2262 idx.i_position = -1;
2264 idx.b_key = VLC_TRUE;
2267 while( ( el = ep->Get() ) != NULL )
2269 if( MKV_IS_ID( el, KaxCueTime ) )
2271 KaxCueTime &ctime = *(KaxCueTime*)el;
2273 ctime.ReadData( es.I_O() );
2275 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2277 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2280 while( ( el = ep->Get() ) != NULL )
2282 if( MKV_IS_ID( el, KaxCueTrack ) )
2284 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2286 ctrack.ReadData( es.I_O() );
2287 idx.i_track = uint16( ctrack );
2289 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2291 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2293 ccpos.ReadData( es.I_O() );
2294 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2296 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2298 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2300 cbnum.ReadData( es.I_O() );
2301 idx.i_block_number = uint32( cbnum );
2305 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2312 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2318 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2319 " track=%d bnum=%d", idx.i_time, idx.i_position,
2320 idx.i_track, idx.i_block_number );
2324 if( i_index >= i_index_max )
2326 i_index_max += 1024;
2327 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2333 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2341 msg_Dbg( &sys.demuxer, "loading cues done." );
2342 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2345 void matroska_segment_c::LoadTags( )
2347 int64_t i_sav_position = es.I_O().getFilePointer();
2349 EbmlElement *el, *tags;
2351 msg_Dbg( &sys.demuxer, "loading tags" );
2352 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2353 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2357 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2358 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2362 msg_Dbg( &sys.demuxer, "Tags" );
2363 ep = new EbmlParser( &es, tags, &sys.demuxer );
2364 while( ( el = ep->Get() ) != NULL )
2366 if( MKV_IS_ID( el, KaxTag ) )
2368 msg_Dbg( &sys.demuxer, "+ Tag" );
2370 while( ( el = ep->Get() ) != NULL )
2372 if( MKV_IS_ID( el, KaxTagTargets ) )
2374 msg_Dbg( &sys.demuxer, "| + Targets" );
2376 while( ( el = ep->Get() ) != NULL )
2378 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2382 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2384 msg_Dbg( &sys.demuxer, "| + General" );
2386 while( ( el = ep->Get() ) != NULL )
2388 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2392 else if( MKV_IS_ID( el, KaxTagGenres ) )
2394 msg_Dbg( &sys.demuxer, "| + Genres" );
2396 while( ( el = ep->Get() ) != NULL )
2398 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2402 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2404 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2406 while( ( el = ep->Get() ) != NULL )
2408 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2412 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2414 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2416 while( ( el = ep->Get() ) != NULL )
2418 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2422 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2424 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2426 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2428 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2430 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2432 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2434 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2436 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2438 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2440 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2442 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2444 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2446 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2448 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2452 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2459 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2465 msg_Dbg( &sys.demuxer, "loading tags done." );
2466 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2469 /*****************************************************************************
2471 *****************************************************************************/
2472 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2476 int i_upper_level = 0;
2478 msg_Dbg( &sys.demuxer, "| + Seek head" );
2480 /* Master elements */
2481 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2483 for( i = 0; i < seekhead->ListSize(); i++ )
2485 EbmlElement *l = (*seekhead)[i];
2487 if( MKV_IS_ID( l, KaxSeek ) )
2489 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2490 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2493 for( j = 0; j < sk->ListSize(); j++ )
2495 EbmlElement *l = (*sk)[j];
2497 if( MKV_IS_ID( l, KaxSeekID ) )
2499 KaxSeekID &sid = *(KaxSeekID*)l;
2500 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2502 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2504 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2505 i_pos = uint64( spos );
2509 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2515 if( id == KaxCues::ClassInfos.GlobalId )
2517 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2518 i_cues_position = segment->GetGlobalPosition( i_pos );
2520 else if( id == KaxChapters::ClassInfos.GlobalId )
2522 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2523 i_chapters_position = segment->GetGlobalPosition( i_pos );
2525 else if( id == KaxTags::ClassInfos.GlobalId )
2527 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2528 i_tags_position = segment->GetGlobalPosition( i_pos );
2534 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2539 /*****************************************************************************
2541 *****************************************************************************/
2542 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2548 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2550 tk = new mkv_track_t();
2551 tracks.push_back( tk );
2553 /* Init the track */
2554 memset( tk, 0, sizeof( mkv_track_t ) );
2556 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2557 tk->fmt.psz_language = strdup("English");
2558 tk->fmt.psz_description = NULL;
2560 tk->b_default = VLC_TRUE;
2561 tk->b_enabled = VLC_TRUE;
2562 tk->b_silent = VLC_FALSE;
2563 tk->i_number = tracks.size() - 1;
2564 tk->i_extra_data = 0;
2565 tk->p_extra_data = NULL;
2566 tk->psz_codec = NULL;
2567 tk->i_default_duration = 0;
2568 tk->f_timecodescale = 1.0;
2570 tk->b_inited = VLC_FALSE;
2571 tk->i_data_init = 0;
2572 tk->p_data_init = NULL;
2574 tk->psz_codec_name = NULL;
2575 tk->psz_codec_settings = NULL;
2576 tk->psz_codec_info_url = NULL;
2577 tk->psz_codec_download_url = NULL;
2579 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2581 for( i = 0; i < m->ListSize(); i++ )
2583 EbmlElement *l = (*m)[i];
2585 if( MKV_IS_ID( l, KaxTrackNumber ) )
2587 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2589 tk->i_number = uint32( tnum );
2590 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2592 else if( MKV_IS_ID( l, KaxTrackUID ) )
2594 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2596 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2598 else if( MKV_IS_ID( l, KaxTrackType ) )
2601 KaxTrackType &ttype = *(KaxTrackType*)l;
2603 switch( uint8(ttype) )
2607 tk->fmt.i_cat = AUDIO_ES;
2611 tk->fmt.i_cat = VIDEO_ES;
2613 case track_subtitle:
2614 psz_type = "subtitle";
2615 tk->fmt.i_cat = SPU_ES;
2618 psz_type = "unknown";
2619 tk->fmt.i_cat = UNKNOWN_ES;
2623 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2625 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2627 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2629 // tk->b_enabled = uint32( fenb );
2630 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2631 // uint32( fenb ) );
2633 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2635 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2637 tk->b_default = uint32( fdef );
2638 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2640 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2642 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2644 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2646 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2648 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2650 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2652 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2654 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2656 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2658 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2660 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2662 tk->i_default_duration = uint64(defd);
2663 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2665 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2667 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2669 tk->f_timecodescale = float( ttcs );
2670 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2672 else if( MKV_IS_ID( l, KaxTrackName ) )
2674 KaxTrackName &tname = *(KaxTrackName*)l;
2676 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2677 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2679 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2681 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2683 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2684 msg_Dbg( &sys.demuxer,
2685 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2687 else if( MKV_IS_ID( l, KaxCodecID ) )
2689 KaxCodecID &codecid = *(KaxCodecID*)l;
2691 tk->psz_codec = strdup( string( codecid ).c_str() );
2692 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2694 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2696 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2698 tk->i_extra_data = cpriv.GetSize();
2699 if( tk->i_extra_data > 0 )
2701 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2702 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2704 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2706 else if( MKV_IS_ID( l, KaxCodecName ) )
2708 KaxCodecName &cname = *(KaxCodecName*)l;
2710 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2711 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2713 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2715 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2716 MkvTree( sys.demuxer, 3, "Content Encodings" );
2717 for( j = 0; j < cencs->ListSize(); j++ )
2719 EbmlElement *l2 = (*cencs)[j];
2720 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2722 MkvTree( sys.demuxer, 4, "Content Encoding" );
2723 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2724 for( k = 0; k < cenc->ListSize(); k++ )
2726 EbmlElement *l3 = (*cenc)[k];
2727 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2729 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2730 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2732 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2734 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2735 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2737 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2739 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2740 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2742 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2744 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2745 MkvTree( sys.demuxer, 5, "Content Compression" );
2746 for( n = 0; n < compr->ListSize(); n++ )
2748 EbmlElement *l4 = (*compr)[n];
2749 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2751 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2752 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2753 if( uint32( compalg ) == 0 )
2755 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2760 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2767 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2774 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2779 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2781 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2783 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2784 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2786 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2788 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2790 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2791 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2793 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2795 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2797 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2798 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2800 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2802 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2804 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2806 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2808 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2810 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2812 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2814 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2817 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2820 for( j = 0; j < tkv->ListSize(); j++ )
2822 EbmlElement *l = (*tkv)[j];
2823 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2825 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2827 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2829 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2831 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2833 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2836 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2838 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2840 tk->fmt.video.i_width = uint16( vwidth );
2841 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2843 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2845 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2847 tk->fmt.video.i_height = uint16( vheight );
2848 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2850 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2852 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2854 tk->fmt.video.i_visible_width = uint16( vwidth );
2855 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2857 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2859 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2861 tk->fmt.video.i_visible_height = uint16( vheight );
2862 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2864 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2866 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2868 tk->f_fps = float( vfps );
2869 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2871 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2873 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2875 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2876 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2878 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2880 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2882 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2884 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2886 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2888 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2892 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2895 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2896 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2898 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2900 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2903 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2905 for( j = 0; j < tka->ListSize(); j++ )
2907 EbmlElement *l = (*tka)[j];
2909 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2911 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2913 tk->fmt.audio.i_rate = (int)float( afreq );
2914 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2916 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2918 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2920 tk->fmt.audio.i_channels = uint8( achan );
2921 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2923 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2925 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2927 tk->fmt.audio.i_bitspersample = uint8( abits );
2928 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2932 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2938 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2939 typeid(*l).name() );
2944 /*****************************************************************************
2946 *****************************************************************************/
2947 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
2951 int i_upper_level = 0;
2953 msg_Dbg( &sys.demuxer, "| + Tracks" );
2955 /* Master elements */
2956 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2958 for( i = 0; i < tracks->ListSize(); i++ )
2960 EbmlElement *l = (*tracks)[i];
2962 if( MKV_IS_ID( l, KaxTrackEntry ) )
2964 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
2968 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2973 /*****************************************************************************
2975 *****************************************************************************/
2976 void matroska_segment_c::ParseInfo( KaxInfo *info )
2981 int i_upper_level = 0;
2983 msg_Dbg( &sys.demuxer, "| + Information" );
2985 /* Master elements */
2986 m = static_cast<EbmlMaster *>(info);
2987 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2989 for( i = 0; i < m->ListSize(); i++ )
2991 EbmlElement *l = (*m)[i];
2993 if( MKV_IS_ID( l, KaxSegmentUID ) )
2995 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2997 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2999 else if( MKV_IS_ID( l, KaxPrevUID ) )
3001 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3003 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3005 else if( MKV_IS_ID( l, KaxNextUID ) )
3007 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3009 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3011 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3013 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3015 i_timescale = uint64(tcs);
3017 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
3020 else if( MKV_IS_ID( l, KaxDuration ) )
3022 KaxDuration &dur = *(KaxDuration*)l;
3024 i_duration = mtime_t( double( dur ) );
3026 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
3029 else if( MKV_IS_ID( l, KaxMuxingApp ) )
3031 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3033 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3035 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
3036 psz_muxing_application );
3038 else if( MKV_IS_ID( l, KaxWritingApp ) )
3040 KaxWritingApp &wapp = *(KaxWritingApp*)l;
3042 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3044 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
3045 psz_writing_application );
3047 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3049 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3051 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3053 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
3054 psz_segment_filename );
3056 else if( MKV_IS_ID( l, KaxTitle ) )
3058 KaxTitle &title = *(KaxTitle*)l;
3060 psz_title = UTF8ToStr( UTFstring( title ) );
3062 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
3064 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3066 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3068 families.push_back(*uid);
3070 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3072 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3073 else if( MKV_IS_ID( l, KaxDateUTC ) )
3075 KaxDateUTC &date = *(KaxDateUTC*)l;
3080 i_date = date.GetEpochDate();
3081 memset( buffer, 0, 256 );
3082 if( gmtime_r( &i_date, &tmres ) &&
3083 asctime_r( &tmres, buffer ) )
3085 buffer[strlen( buffer)-1]= '\0';
3086 psz_date_utc = strdup( buffer );
3087 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3091 #if LIBMATROSKA_VERSION >= 0x000704
3092 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3094 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3095 chapter_translation_c translated;
3097 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3098 for( j = 0; j < p_trans->ListSize(); j++ )
3100 EbmlElement *l = (*p_trans)[j];
3102 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3104 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3106 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3108 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3110 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3112 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3116 translations.push_back( translated );
3121 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3125 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3126 i_duration = mtime_t(f_dur);
3130 /*****************************************************************************
3132 *****************************************************************************/
3133 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3137 if( sys.title == NULL )
3139 sys.title = vlc_input_title_New();
3142 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3143 for( i = 0; i < ca->ListSize(); i++ )
3145 EbmlElement *l = (*ca)[i];
3147 if( MKV_IS_ID( l, KaxChapterUID ) )
3149 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3150 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3152 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3154 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3155 chapters.b_display_seekpoint = uint8( flag ) == 0;
3157 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3159 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3161 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3162 chapters.i_start_time = uint64( start ) / I64C(1000);
3164 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3166 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3168 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3169 chapters.i_end_time = uint64( end ) / I64C(1000);
3171 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3173 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3175 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3177 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3178 for( j = 0; j < cd->ListSize(); j++ )
3180 EbmlElement *l= (*cd)[j];
3182 if( MKV_IS_ID( l, KaxChapterString ) )
3186 KaxChapterString &name =*(KaxChapterString*)l;
3187 for (k = 0; k < i_level; k++)
3188 chapters.psz_name += '+';
3189 chapters.psz_name += ' ';
3190 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3192 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3194 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3196 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3197 const char *psz = string( lang ).c_str();
3199 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3201 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3203 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3204 const char *psz = string( ct ).c_str();
3206 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3210 else if( MKV_IS_ID( l, KaxChapterProcess ) )
3212 msg_Dbg( &sys.demuxer, "| | | | + ChapterProcess" );
3214 KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3215 chapter_codec_cmds_c *p_ccodec = NULL;
3217 for( j = 0; j < cp->ListSize(); j++ )
3219 EbmlElement *k= (*cp)[j];
3221 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3223 KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3224 if ( uint32(*p_codec_id) == 0 )
3225 p_ccodec = new matroska_script_codec_c();
3226 else if ( uint32(*p_codec_id) == 1 )
3227 p_ccodec = new dvd_chapter_codec_c();
3232 if ( p_ccodec != NULL )
3233 for( j = 0; j < cp->ListSize(); j++ )
3235 EbmlElement *k= (*cp)[j];
3237 if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3239 KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3240 p_ccodec->SetPrivate( *p_private );
3242 else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3244 p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3247 chapters.codecs.push_back( *p_ccodec );
3249 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3251 chapter_item_c new_sub_chapter;
3252 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), new_sub_chapter );
3253 new_sub_chapter.psz_parent = &chapters;
3254 chapters.sub_chapters.push_back( new_sub_chapter );
3259 /*****************************************************************************
3261 *****************************************************************************/
3262 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3266 int i_upper_level = 0;
3269 /* Master elements */
3270 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3272 for( i = 0; i < chapters->ListSize(); i++ )
3274 EbmlElement *l = (*chapters)[i];
3276 if( MKV_IS_ID( l, KaxEditionEntry ) )
3278 chapter_edition_c edition;
3280 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3282 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3283 for( j = 0; j < E->ListSize(); j++ )
3285 EbmlElement *l = (*E)[j];
3287 if( MKV_IS_ID( l, KaxChapterAtom ) )
3289 chapter_item_c new_sub_chapter;
3290 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), new_sub_chapter );
3291 edition.sub_chapters.push_back( new_sub_chapter );
3293 else if( MKV_IS_ID( l, KaxEditionUID ) )
3295 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3297 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3299 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3301 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3303 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3304 i_default_edition = stored_editions.size();
3308 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3311 stored_editions.push_back( edition );
3315 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3319 for( i = 0; i < stored_editions.size(); i++ )
3321 stored_editions[i].RefreshChapters( );
3324 if ( stored_editions[i_default_edition].b_ordered )
3326 /* update the duration of the segment according to the sum of all sub chapters */
3327 i_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3333 void matroska_segment_c::ParseCluster( )
3338 int i_upper_level = 0;
3340 /* Master elements */
3341 m = static_cast<EbmlMaster *>( cluster );
3342 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3344 for( i = 0; i < m->ListSize(); i++ )
3346 EbmlElement *l = (*m)[i];
3348 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3350 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3352 cluster->InitTimecode( uint64( ctc ), i_timescale );
3357 i_start_time = cluster->GlobalTimecode() / 1000;
3360 /*****************************************************************************
3361 * InformationCreate:
3362 *****************************************************************************/
3363 void matroska_segment_c::InformationCreate( )
3367 sys.meta = vlc_meta_New();
3371 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3375 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3377 if( psz_segment_filename )
3379 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3381 if( psz_muxing_application )
3383 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3385 if( psz_writing_application )
3387 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3390 for( i_track = 0; i_track < tracks.size(); i_track++ )
3392 mkv_track_t *tk = tracks[i_track];
3393 vlc_meta_t *mtk = vlc_meta_New();
3395 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3396 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3397 sys.meta->track[sys.meta->i_track++] = mtk;
3399 if( tk->fmt.psz_description )
3401 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3403 if( tk->psz_codec_name )
3405 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3407 if( tk->psz_codec_settings )
3409 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3411 if( tk->psz_codec_info_url )
3413 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3415 if( tk->psz_codec_download_url )
3417 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3421 if( i_tags_position >= 0 )
3423 vlc_bool_t b_seekable;
3425 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3434 /*****************************************************************************
3436 *****************************************************************************/
3438 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3440 #define idx index[i_index]
3442 idx.i_block_number= -1;
3443 idx.i_position = cluster->GetElementPosition();
3445 idx.b_key = VLC_TRUE;
3448 if( i_index >= i_index_max )
3450 i_index_max += 1024;
3451 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3456 static char * UTF8ToStr( const UTFstring &u )
3465 p = dst = (char*)malloc( i_src + 1);
3484 void chapter_edition_c::RefreshChapters( )
3486 chapter_item_c::RefreshChapters( b_ordered, -1 );
3487 b_display_seekpoint = false;
3490 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3492 int64_t i_user_time = i_prev_user_time;
3494 // first the sub-chapters, and then ourself
3495 std::vector<chapter_item_c>::iterator index = sub_chapters.begin();
3496 while ( index != sub_chapters.end() )
3498 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time );
3504 // the ordered chapters always start at zero
3505 if ( i_prev_user_time == -1 )
3507 if ( i_user_time == -1 )
3509 i_prev_user_time = 0;
3512 i_user_start_time = i_prev_user_time;
3513 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3515 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3519 i_user_end_time = i_user_time;
3524 std::sort( sub_chapters.begin(), sub_chapters.end() );
3525 i_user_start_time = i_start_time;
3526 if ( i_end_time != -1 )
3527 i_user_end_time = i_end_time;
3528 else if ( i_user_time != -1 )
3529 i_user_end_time = i_user_time;
3531 i_user_end_time = i_user_start_time;
3534 return i_user_end_time;
3537 mtime_t chapter_edition_c::Duration() const
3539 mtime_t i_result = 0;
3541 if ( sub_chapters.size() )
3543 std::vector<chapter_item_c>::const_iterator index = sub_chapters.end();
3545 i_result = (*index).i_user_end_time;
3551 const chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode ) const
3553 const chapter_item_c *psz_result = NULL;
3555 if ( i_user_timecode >= i_user_start_time &&
3556 ( i_user_timecode < i_user_end_time ||
3557 ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3559 std::vector<chapter_item_c>::const_iterator index = sub_chapters.begin();
3560 while ( index != sub_chapters.end() && psz_result == NULL )
3562 psz_result = (*index).FindTimecode( i_user_timecode );
3566 if ( psz_result == NULL )
3573 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3575 for (size_t i=0; i<opened_segments.size(); i++)
3577 opened_segments[i]->PreloadFamily( of_segment );
3580 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3585 for (size_t i=0; i<families.size(); i++)
3587 for (size_t j=0; j<of_segment.families.size(); j++)
3589 if ( families[i] == of_segment.families[j] )
3597 // preload all the linked segments for all preloaded segments
3598 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3600 size_t i_preloaded, i;
3602 delete p_current_segment;
3603 p_current_segment = new virtual_segment_c( p_segment );
3605 // fill our current virtual segment with all hard linked segments
3608 for ( i=0; i< opened_segments.size(); i++ )
3610 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3612 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3614 p_current_segment->Sort( );
3616 p_current_segment->PreloadLinked( );
3619 bool demux_sys_t::PreparePlayback( )
3621 p_current_segment->LoadCues();
3622 f_duration = p_current_segment->Duration();
3624 /* add information */
3625 p_current_segment->Segment()->InformationCreate( );
3627 p_current_segment->Segment()->Select( 0 );
3629 return p_current_segment->Select( *title );
3632 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
3634 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3635 if ( *p_itema == p_item_b->prev_segment_uid )
3638 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3639 if ( *p_itema == p_item_b->segment_uid )
3642 if ( *p_itema == p_item_b->prev_segment_uid )
3648 bool matroska_segment_c::Preload( )
3653 EbmlElement *el = NULL;
3655 ep->Reset( &sys.demuxer );
3657 while( ( el = ep->Get() ) != NULL )
3659 if( MKV_IS_ID( el, KaxInfo ) )
3661 ParseInfo( static_cast<KaxInfo*>( el ) );
3663 else if( MKV_IS_ID( el, KaxTracks ) )
3665 ParseTracks( static_cast<KaxTracks*>( el ) );
3667 else if( MKV_IS_ID( el, KaxSeekHead ) )
3669 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3671 else if( MKV_IS_ID( el, KaxCues ) )
3673 msg_Dbg( &sys.demuxer, "| + Cues" );
3675 else if( MKV_IS_ID( el, KaxCluster ) )
3677 msg_Dbg( &sys.demuxer, "| + Cluster" );
3679 cluster = (KaxCluster*)el;
3681 i_start_pos = cluster->GetElementPosition();
3685 /* stop parsing the stream */
3688 else if( MKV_IS_ID( el, KaxAttachments ) )
3690 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3692 else if( MKV_IS_ID( el, KaxChapters ) )
3694 msg_Dbg( &sys.demuxer, "| + Chapters" );
3695 ParseChapters( static_cast<KaxChapters*>( el ) );
3697 else if( MKV_IS_ID( el, KaxTag ) )
3699 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3703 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3712 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3714 for (size_t i=0; i<opened_segments.size(); i++)
3716 if ( opened_segments[i]->segment_uid == uid )
3717 return opened_segments[i];
3722 void virtual_segment_c::Sort()
3724 // keep the current segment index
3725 matroska_segment_c *p_segment = linked_segments[i_current_segment];
3727 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
3729 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3730 if ( linked_segments[i_current_segment] == p_segment )
3734 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
3737 // check if it's not already in here
3738 for ( i=0; i<linked_segments.size(); i++ )
3740 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3744 // find possible mates
3745 for ( i=0; i<linked_uids.size(); i++ )
3747 if ( p_segment->segment_uid == linked_uids[i]
3748 || p_segment->prev_segment_uid == linked_uids[i]
3749 || p_segment->next_segment_uid == linked_uids[i] )
3751 linked_segments.push_back( p_segment );
3753 AppendUID( p_segment->prev_segment_uid );
3754 AppendUID( p_segment->next_segment_uid );
3762 void virtual_segment_c::PreloadLinked( )
3764 for ( size_t i=0; i<linked_segments.size(); i++ )
3766 linked_segments[i]->Preload( );
3768 i_current_edition = linked_segments[0]->i_default_edition;
3771 mtime_t virtual_segment_c::Duration() const
3774 if ( linked_segments.size() == 0 )
3777 matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
3778 // p_last_segment->ParseCluster( );
3780 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3785 void virtual_segment_c::LoadCues( )
3787 for ( size_t i=0; i<linked_segments.size(); i++ )
3789 linked_segments[i]->LoadCues();
3793 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
3795 if ( UID.GetBuffer() == NULL )
3798 for (size_t i=0; i<linked_uids.size(); i++)
3800 if ( UID == linked_uids[i] )
3803 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3806 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
3809 int i_track_skipping;
3810 int64_t i_block_duration;
3811 int64_t i_block_ref1;
3812 int64_t i_block_ref2;
3814 int64_t i_seek_position = i_start_pos;
3815 int64_t i_seek_time = i_start_time;
3821 for( ; i_idx < i_index; i_idx++ )
3823 if( index[i_idx].i_time + i_time_offset > i_date )
3834 i_seek_position = index[i_idx].i_position;
3835 i_seek_time = index[i_idx].i_time;
3838 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3839 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3841 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3844 ep = new EbmlParser( &es, segment, &sys.demuxer );
3847 sys.i_start_pts = i_date;
3849 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3851 /* now parse until key frame */
3852 #define tk tracks[i_track]
3853 i_track_skipping = 0;
3854 for( i_track = 0; i_track < tracks.size(); i_track++ )
3856 if( tk->fmt.i_cat == VIDEO_ES )
3858 tk->b_search_keyframe = VLC_TRUE;
3861 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3865 while( i_track_skipping > 0 )
3867 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3869 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3874 for( i_track = 0; i_track < tracks.size(); i_track++ )
3876 if( tk->i_number == block->TrackNum() )
3882 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3884 if( i_track < tracks.size() )
3886 if( sys.i_pts >= sys.i_start_pts )
3888 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3889 i_track_skipping = 0;
3891 else if( tk->fmt.i_cat == VIDEO_ES )
3893 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3895 tk->b_search_keyframe = VLC_FALSE;
3898 if( !tk->b_search_keyframe )
3900 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3910 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_c *psz_chapter )
3912 demux_sys_t *p_sys = demuxer.p_sys;
3915 // find the actual time for an ordered edition
3916 if ( psz_chapter == NULL )
3918 if ( EditionIsOrdered() )
3920 /* 1st, we need to know in which chapter we are */
3921 psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3925 if ( psz_chapter != NULL )
3927 psz_current_chapter = psz_chapter;
3928 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3929 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3930 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3933 // find the best matching segment
3934 for ( i=0; i<linked_segments.size(); i++ )
3936 if ( i_date < linked_segments[i]->i_start_time )
3943 if ( i_current_segment != i )
3945 linked_segments[i_current_segment]->UnSelect();
3946 linked_segments[i]->Select( i_date );
3947 i_current_segment = i;
3950 linked_segments[i]->Seek( i_date, i_time_offset );
3953 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
3957 uint32 codec_time = uint32(-1);
3958 for( i = 0; i < command.ListSize(); i++ )
3960 const EbmlElement *k = command[i];
3962 if( MKV_IS_ID( k, KaxChapterProcessTime ) )
3964 codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
3969 for( i = 0; i < command.ListSize(); i++ )
3971 const EbmlElement *k = command[i];
3973 if( MKV_IS_ID( k, KaxChapterProcessData ) )
3975 KaxChapterProcessData *p_data = new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
3976 switch ( codec_time )
3979 during_cmds.push_back( *p_data );
3982 enter_cmds.push_back( *p_data );
3985 leave_cmds.push_back( *p_data );
3994 bool chapter_item_c::Enter() const
3996 std::vector<chapter_codec_cmds_c>::const_iterator index = codecs.begin();
3997 while ( index != codecs.end() )
4005 bool chapter_item_c::Leave() const
4007 std::vector<chapter_codec_cmds_c>::const_iterator index = codecs.begin();
4008 while ( index != codecs.end() )
4016 bool dvd_chapter_codec_c::Enter() const
4018 std::vector<KaxChapterProcessData>::const_iterator index = enter_cmds.begin();
4019 while ( index != enter_cmds.end() )
4021 if ( *index.GetSize() )
4023 binary *p_data = *index.GetBuffer();
4024 size_t i_size = *p_data++;
4025 // avoid reading too much from the buffer
4026 i_size = min( i_size, (*index.GetSize() - 1) >> 3 );
4027 for ( ; i_size > 0; i_size--, p_data += 8 )
4029 interpretor.Interpret( p_data );
4037 bool dvd_chapter_codec_c::Leave() const
4039 std::vector<KaxChapterProcessData>::const_iterator index = leave_cmds.begin();
4040 while ( index != leave_cmds.end() )
4042 if ( *index.GetSize() )
4044 binary *p_data = *index.GetBuffer();
4045 size_t i_size = *p_data++;
4046 // avoid reading too much from the buffer
4047 i_size = min( i_size, (*index.GetSize() - 1) >> 3 );
4048 for ( ; i_size > 0; i_size--, p_data += 8 )
4050 interpretor.Interpret( p_data );
4058 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )