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 );
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_t
337 class dvd_chapter_codec_t : public chapter_codec_cmds_t
341 class matroska_script_codec_t : public chapter_codec_cmds_t
345 class chapter_translation_t
348 KaxChapterTranslateID translated;
349 unsigned int codec_id;
350 std::vector<uint64_t> editions;
359 ,i_user_start_time(-1)
362 ,b_display_seekpoint(true)
369 for (i=0; i<enter_cmds.size(); i++)
370 delete enter_cmds[i];
371 for (i=0; i<during_cmds.size(); i++)
372 delete during_cmds[i];
373 for (i=0; i<leave_cmds.size(); i++)
374 delete leave_cmds[i];
377 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
378 void PublishChapters( input_title_t & title, int i_level );
379 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
380 void Append( const chapter_item_t & edition );
381 chapter_item_t * FindChapter( const chapter_item_t & chapter );
383 int64_t i_start_time, i_end_time;
384 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
385 std::vector<chapter_item_t> sub_chapters;
388 bool b_display_seekpoint;
389 std::string psz_name;
390 chapter_item_t *psz_parent;
392 bool operator<( const chapter_item_t & item ) const
394 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) );
398 std::vector<chapter_codec_cmds_t*> enter_cmds;
399 std::vector<chapter_codec_cmds_t*> during_cmds;
400 std::vector<chapter_codec_cmds_t*> leave_cmds;
406 class chapter_edition_t : public chapter_item_t
413 void RefreshChapters( );
414 mtime_t Duration() const;
415 void PublishChapters( input_title_t & title );
422 class matroska_segment_t
425 matroska_segment_t( demux_sys_t & demuxer, EbmlStream & estream )
428 ,i_timescale(MKVD_TIMECODESCALE)
432 ,i_chapters_position(-1)
439 ,psz_muxing_application(NULL)
440 ,psz_writing_application(NULL)
441 ,psz_segment_filename(NULL)
444 ,i_default_edition(0)
449 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
452 ~matroska_segment_t()
454 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
456 #define tk tracks[i_track]
457 if( tk->fmt.psz_description )
459 free( tk->fmt.psz_description );
463 free( tk->psz_codec );
465 if( tk->fmt.psz_language )
467 free( tk->fmt.psz_language );
473 if( psz_writing_application )
475 free( psz_writing_application );
477 if( psz_muxing_application )
479 free( psz_muxing_application );
481 if( psz_segment_filename )
483 free( psz_segment_filename );
491 free( psz_date_utc );
503 uint64_t i_timescale;
505 /* duration of the segment */
507 mtime_t i_start_time;
510 std::vector<mkv_track_t*> tracks;
513 int64_t i_cues_position;
514 int64_t i_chapters_position;
515 int64_t i_tags_position;
519 KaxSegmentUID segment_uid;
520 KaxPrevUID prev_segment_uid;
521 KaxNextUID next_segment_uid;
529 char *psz_muxing_application;
530 char *psz_writing_application;
531 char *psz_segment_filename;
535 std::vector<chapter_edition_t> stored_editions;
536 int i_default_edition;
538 std::vector<chapter_translation_t> translations;
539 std::vector<KaxSegmentFamily> families;
546 bool PreloadFamily( const matroska_segment_t & segment );
547 void ParseInfo( KaxInfo *info );
548 void ParseChapters( KaxChapters *chapters );
549 void ParseSeekHead( KaxSeekHead *seekhead );
550 void ParseTracks( KaxTracks *tracks );
551 void ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_t & chapters );
552 void ParseTrackEntry( KaxTrackEntry *m );
553 void ParseCluster( );
554 void IndexAppendCluster( KaxCluster *cluster );
557 void InformationCreate( );
558 void Seek( mtime_t i_date, mtime_t i_time_offset );
559 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
560 bool Select( mtime_t i_start_time );
562 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
565 // class holding hard-linked segment together in the playback order
566 class virtual_segment_t
569 virtual_segment_t( matroska_segment_t *p_segment )
570 :i_current_segment(0)
571 ,i_current_edition(-1)
572 ,psz_current_chapter(NULL)
574 linked_segments.push_back( p_segment );
576 AppendUID( p_segment->segment_uid );
577 AppendUID( p_segment->prev_segment_uid );
578 AppendUID( p_segment->next_segment_uid );
582 size_t AddSegment( matroska_segment_t *p_segment );
583 void PreloadLinked( );
584 mtime_t Duration( ) const;
586 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter );
588 inline chapter_edition_t *Edition()
590 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
591 return &editions[i_current_edition];
595 inline bool EditionIsOrdered() const
597 return (editions.size() != 0 && i_current_edition >= 0 && editions[i_current_edition].b_ordered);
600 matroska_segment_t * Segment() const
602 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
604 return linked_segments[i_current_segment];
607 inline const chapter_item_t *CurrentChapter() const {
608 return psz_current_chapter;
613 if ( i_current_segment < linked_segments.size()-1 )
621 /* TODO handle/merge chapters here */
622 void UpdateCurrentToChapter( demux_t & demux );
623 bool Select( input_title_t & title );
626 std::vector<matroska_segment_t*> linked_segments;
627 std::vector<KaxSegmentUID> linked_uids;
628 size_t i_current_segment;
630 std::vector<chapter_edition_t> editions;
631 int i_current_edition;
632 const chapter_item_t *psz_current_chapter;
634 void AppendUID( const EbmlBinary & UID );
637 class matroska_stream_t
640 matroska_stream_t( demux_sys_t & demuxer )
655 std::vector<matroska_segment_t*> segments;
663 demux_sys_t( demux_t & demux )
670 ,p_current_segment(NULL)
676 for (size_t i=0; i<streams.size(); i++)
678 for ( size_t i=0; i<opened_segments.size(); i++ )
679 delete opened_segments[i];
687 mtime_t i_chapter_time;
691 input_title_t *title;
693 std::vector<matroska_stream_t*> streams;
694 std::vector<matroska_segment_t*> opened_segments;
695 virtual_segment_t *p_current_segment;
697 /* duration of the stream */
700 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
701 void PreloadFamily( const matroska_segment_t & of_segment );
702 void PreloadLinked( matroska_segment_t *p_segment );
703 bool PreparePlayback( );
704 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
707 static int Demux ( demux_t * );
708 static int Control( demux_t *, int, va_list );
709 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
711 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
713 static char *UTF8ToStr ( const UTFstring &u );
715 /*****************************************************************************
716 * Open: initializes matroska demux structures
717 *****************************************************************************/
718 static int Open( vlc_object_t * p_this )
720 demux_t *p_demux = (demux_t*)p_this;
722 matroska_stream_t *p_stream;
723 matroska_segment_t *p_segment;
725 std::string s_path, s_filename;
726 vlc_stream_io_callback *p_io_callback;
727 EbmlStream *p_io_stream;
729 /* peek the begining */
730 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
732 /* is a valid file */
733 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
734 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
736 /* Set the demux function */
737 p_demux->pf_demux = Demux;
738 p_demux->pf_control = Control;
739 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
741 p_io_callback = new vlc_stream_io_callback( p_demux->s );
742 p_io_stream = new EbmlStream( *p_io_callback );
744 if( p_io_stream == NULL )
746 msg_Err( p_demux, "failed to create EbmlStream" );
747 delete p_io_callback;
752 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
753 if( p_stream == NULL )
755 msg_Err( p_demux, "cannot find KaxSegment" );
758 p_sys->streams.push_back( p_stream );
760 p_stream->p_in = p_io_callback;
761 p_stream->p_es = p_io_stream;
763 for (size_t i=0; i<p_stream->segments.size(); i++)
765 p_stream->segments[i]->Preload();
768 p_segment = p_stream->segments[0];
769 if( p_segment->cluster == NULL )
771 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
774 // reset the stream reading to the first cluster of the segment used
775 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
777 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
778 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
780 // assume it's a regular file
781 // get the directory path
782 s_path = p_demux->psz_path;
783 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
785 s_path = s_path.substr(0,s_path.length()-1);
789 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
791 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
795 struct dirent *p_file_item;
796 DIR *p_src_dir = opendir(s_path.c_str());
798 if (p_src_dir != NULL)
800 while ((p_file_item = (dirent *) readdir(p_src_dir)))
802 if (strlen(p_file_item->d_name) > 4)
804 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
806 if (!s_filename.compare(p_demux->psz_path))
807 continue; // don't reuse the original opened file
809 #if defined(__GNUC__) && (__GNUC__ < 3)
810 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
811 !s_filename.compare("mka", s_filename.length() - 3, 3))
813 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
814 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
817 // test wether this file belongs to the our family
818 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
819 EbmlStream *p_estream = new EbmlStream(*p_file_io);
821 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
822 if ( p_stream == NULL )
824 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
830 p_stream->p_in = p_file_io;
831 p_stream->p_es = p_estream;
832 p_sys->streams.push_back( p_stream );
837 closedir( p_src_dir );
841 p_sys->PreloadFamily( *p_segment );
842 p_sys->PreloadLinked( p_segment );
843 if ( !p_sys->PreparePlayback( ) )
845 msg_Err( p_demux, "cannot use the segment" );
856 /*****************************************************************************
857 * Close: frees unused data
858 *****************************************************************************/
859 static void Close( vlc_object_t *p_this )
861 demux_t *p_demux = (demux_t*)p_this;
862 demux_sys_t *p_sys = p_demux->p_sys;
867 /*****************************************************************************
869 *****************************************************************************/
870 static int Control( demux_t *p_demux, int i_query, va_list args )
872 demux_sys_t *p_sys = p_demux->p_sys;
877 vlc_meta_t **pp_meta;
882 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
883 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
886 case DEMUX_GET_LENGTH:
887 pi64 = (int64_t*)va_arg( args, int64_t * );
888 if( p_sys->f_duration > 0.0 )
890 *pi64 = (int64_t)(p_sys->f_duration * 1000);
895 case DEMUX_GET_POSITION:
896 pf = (double*)va_arg( args, double * );
897 if ( p_sys->f_duration > 0.0 )
898 *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);
901 case DEMUX_SET_POSITION:
902 f = (double)va_arg( args, double );
903 Seek( p_demux, -1, f, NULL );
907 pi64 = (int64_t*)va_arg( args, int64_t * );
908 *pi64 = p_sys->i_pts;
911 case DEMUX_GET_TITLE_INFO:
912 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
914 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
915 int *pi_int = (int*)va_arg( args, int* );
918 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
920 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
926 case DEMUX_SET_TITLE:
927 /* TODO handle editions as titles & DVD titles as well */
928 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
934 case DEMUX_SET_SEEKPOINT:
935 /* FIXME do a better implementation */
936 i_skp = (int)va_arg( args, int );
938 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
940 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
941 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
942 p_demux->info.i_seekpoint = i_skp;
954 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
966 i_level = ep->GetLevel();
968 if( el == NULL && *pp_block != NULL )
970 /* update the index */
971 #define idx index[i_index - 1]
972 if( i_index > 0 && idx.i_time == -1 )
974 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
975 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
983 if( ep->GetLevel() > 1 )
988 msg_Warn( &sys.demuxer, "EOF" );
995 if( MKV_IS_ID( el, KaxCluster ) )
997 cluster = (KaxCluster*)el;
999 /* add it to the index */
1001 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
1003 IndexAppendCluster( cluster );
1006 // reset silent tracks
1007 for (size_t i=0; i<tracks.size(); i++)
1009 tracks[i]->b_silent = VLC_FALSE;
1014 else if( MKV_IS_ID( el, KaxCues ) )
1016 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1017 return VLC_EGENERIC;
1021 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1024 else if( i_level == 2 )
1026 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1028 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1030 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1031 cluster->InitTimecode( uint64( ctc ), i_timescale );
1033 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1037 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1042 else if( i_level == 3 )
1044 if( MKV_IS_ID( el, KaxBlock ) )
1046 *pp_block = (KaxBlock*)el;
1048 (*pp_block)->ReadData( es.I_O() );
1049 (*pp_block)->SetParent( *cluster );
1053 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1055 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1057 dur.ReadData( es.I_O() );
1058 *pi_duration = uint64( dur );
1060 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1062 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1064 ref.ReadData( es.I_O() );
1065 if( *pi_ref1 == -1 )
1067 *pi_ref1 = int64( ref );
1071 *pi_ref2 = int64( ref );
1074 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1076 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1077 track_num.ReadData( es.I_O() );
1079 for (size_t i=0; i<tracks.size(); i++)
1081 if ( tracks[i]->i_number == uint32(track_num))
1083 tracks[i]->b_silent = VLC_TRUE;
1091 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1092 return VLC_EGENERIC;
1097 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1100 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1101 memcpy( p_block->p_buffer, p_mem, i_mem );
1102 //p_block->i_rate = p_input->stream.control.i_rate;
1106 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1107 mtime_t i_duration )
1109 demux_sys_t *p_sys = p_demux->p_sys;
1110 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1116 #define tk p_segment->tracks[i_track]
1117 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1119 if( tk->i_number == block->TrackNum() )
1125 if( i_track >= p_segment->tracks.size() )
1127 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1130 if( tk->p_es == NULL )
1132 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1135 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1137 return; /* discard audio packets that shouldn't be rendered */
1140 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1143 tk->b_inited = VLC_FALSE;
1147 /* First send init data */
1148 if( !tk->b_inited && tk->i_data_init > 0 )
1152 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1153 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1154 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1156 tk->b_inited = VLC_TRUE;
1159 for( i = 0; i < block->NumberFrames(); i++ )
1162 DataBuffer &data = block->GetBuffer(i);
1164 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1166 if( p_block == NULL )
1171 #if defined(HAVE_ZLIB_H)
1172 if( tk->i_compression_type )
1174 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1178 // TODO implement correct timestamping when B frames are used
1179 if( tk->fmt.i_cat != VIDEO_ES )
1181 p_block->i_dts = p_block->i_pts = i_pts;
1185 p_block->i_dts = i_pts;
1189 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1191 p_block->i_length = i_duration * 1000;
1194 es_out_Send( p_demux->out, tk->p_es, p_block );
1196 /* use time stamp only for first block */
1203 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1205 int i_upper_lvl = 0;
1207 EbmlElement *p_l0, *p_l1, *p_l2;
1208 bool b_keep_stream = false, b_keep_segment;
1210 // verify the EBML Header
1211 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1216 p_l0->SkipData(*p_estream, EbmlHead_Context);
1219 // find all segments in this file
1220 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1226 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1230 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1233 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1234 b_keep_segment = false;
1236 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1237 p_segment1->ep = ep;
1238 p_segment1->segment = (KaxSegment*)p_l0;
1240 while ((p_l1 = ep->Get()))
1242 if (MKV_IS_ID(p_l1, KaxInfo))
1244 // find the families of this segment
1245 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1247 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1248 for( i = 0; i < p_info->ListSize(); i++ )
1250 EbmlElement *l = (*p_info)[i];
1252 if( MKV_IS_ID( l, KaxSegmentUID ) )
1254 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1255 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1256 if ( !b_keep_segment )
1257 break; // this segment is already known
1258 opened_segments.push_back( p_segment1 );
1259 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1261 else if( MKV_IS_ID( l, KaxPrevUID ) )
1263 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1265 else if( MKV_IS_ID( l, KaxNextUID ) )
1267 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1269 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1271 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1272 p_segment1->families.push_back( *p_fam );
1278 if ( b_keep_segment )
1280 b_keep_stream = true;
1281 p_stream1->segments.push_back( p_segment1 );
1287 p_l0->SkipData(*p_estream, EbmlHead_Context);
1288 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1291 if ( !b_keep_stream )
1300 bool matroska_segment_t::Select( mtime_t i_start_time )
1305 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1306 for( i_track = 0; i_track < tracks.size(); i_track++ )
1308 #define tk tracks[i_track]
1309 if( tk->fmt.i_cat == UNKNOWN_ES )
1311 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1316 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1318 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1320 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1321 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1325 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1327 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1328 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1329 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1331 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1332 if( tk->fmt.i_extra > 0 )
1334 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1335 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1339 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1340 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1342 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1344 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1346 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1348 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1350 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1352 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1353 tk->fmt.b_packetized = VLC_FALSE;
1354 tk->fmt.i_extra = tk->i_extra_data;
1355 tk->fmt.p_extra = malloc( tk->i_extra_data );
1356 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1360 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1363 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1365 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1367 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1371 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1376 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1377 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1378 tk->fmt.i_codec = p_box->i_type;
1379 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1380 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1381 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1382 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1383 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1384 MP4_FreeBox_sample_vide( p_box );
1386 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1388 stream_Delete( p_mp4_stream );
1391 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1393 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1395 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1396 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1400 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1402 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1404 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1405 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1406 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1407 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1408 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1410 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1411 if( tk->fmt.i_extra > 0 )
1413 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1414 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1418 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1419 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1420 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1422 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1424 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1426 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1428 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1430 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1432 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1434 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1435 tk->fmt.i_extra = tk->i_extra_data;
1436 tk->fmt.p_extra = malloc( tk->i_extra_data );
1437 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1439 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1441 int i, i_offset = 1, i_size[3], i_extra;
1444 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1446 /* Split the 3 headers */
1447 if( tk->p_extra_data[0] != 0x02 )
1448 msg_Err( &sys.demuxer, "invalid vorbis header" );
1450 for( i = 0; i < 2; i++ )
1453 while( i_offset < tk->i_extra_data )
1455 i_size[i] += tk->p_extra_data[i_offset];
1456 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1460 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1461 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1462 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1464 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1465 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1466 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1467 for( i = 0; i < 3; i++ )
1469 *(p_extra++) = i_size[i] >> 8;
1470 *(p_extra++) = i_size[i] & 0xFF;
1471 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1473 p_extra += i_size[i];
1474 i_extra += i_size[i];
1477 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1478 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1480 int i_profile, i_srate;
1481 static unsigned int i_sample_rates[] =
1483 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1484 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1487 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1488 /* create data for faad (MP4DecSpecificDescrTag)*/
1490 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1494 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1498 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1507 for( i_srate = 0; i_srate < 13; i_srate++ )
1509 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1514 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1516 tk->fmt.i_extra = 2;
1517 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1518 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1519 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1521 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1522 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1523 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1525 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1527 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1531 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1533 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1535 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1537 /* FIXME: support this codec */
1538 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1539 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1541 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1543 /* FIXME: support this codec */
1544 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1545 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1547 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1549 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1550 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1552 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1553 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1554 !strcmp( tk->psz_codec, "S_SSA" ) ||
1555 !strcmp( tk->psz_codec, "S_ASS" ))
1557 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1558 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1560 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1562 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1563 if( tk->i_extra_data )
1566 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1567 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1568 p_buf[tk->i_extra_data] = '\0';
1570 p_start = strstr( p_buf, "size:" );
1571 if( sscanf( p_start, "size: %dx%d",
1572 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1574 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 );
1578 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1583 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1585 /* FIXME: support this codec */
1586 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1587 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1591 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1592 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1596 tk->fmt.i_priority = 1000;
1599 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1601 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1605 sys.i_start_pts = i_start_time;
1606 // reset the stream reading to the first cluster of the segment used
1607 es.I_O().setFilePointer( i_start_pos );
1610 ep = new EbmlParser( &es, segment, &sys.demuxer );
1615 void matroska_segment_t::UnSelect( )
1619 for( i_track = 0; i_track < tracks.size(); i_track++ )
1621 #define tk tracks[i_track]
1622 if ( tk->p_es != NULL )
1624 es_out_Del( sys.demuxer.out, tk->p_es );
1633 bool virtual_segment_t::Select( input_title_t & title )
1635 if ( linked_segments.size() == 0 )
1638 // !!! should be called only once !!!
1639 matroska_segment_t *p_segment;
1642 // copy editions from the first segment
1643 p_segment = linked_segments[0];
1644 editions = p_segment->stored_editions;
1646 for ( i=1 ; i<linked_segments.size(); i++ )
1648 p_segment = linked_segments[i];
1649 // FIXME assume we have the same editions in all segments
1650 for (j=0; j<p_segment->stored_editions.size(); j++)
1651 editions[j].Append( p_segment->stored_editions[j] );
1654 if ( Edition() != NULL )
1655 Edition()->PublishChapters( title );
1660 void chapter_edition_t::PublishChapters( input_title_t & title )
1662 title.i_seekpoint = 0;
1663 if ( title.seekpoint != NULL )
1664 free( title.seekpoint );
1665 chapter_item_t::PublishChapters( title, 0 );
1668 void chapter_item_t::PublishChapters( input_title_t & title, int i_level )
1670 if (b_display_seekpoint)
1672 seekpoint_t *sk = vlc_seekpoint_New();
1674 sk->i_level = i_level;
1675 sk->i_time_offset = i_start_time;
1676 sk->psz_name = strdup( psz_name.c_str() );
1678 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1679 title.i_seekpoint++;
1680 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1681 title.seekpoint[title.i_seekpoint-1] = sk;
1683 i_seekpoint_num = title.i_seekpoint;
1686 for ( size_t i=0; i<sub_chapters.size() ; i++)
1688 sub_chapters[i].PublishChapters( title, i_level+1 );
1692 void virtual_segment_t::UpdateCurrentToChapter( demux_t & demux )
1694 demux_sys_t & sys = *demux.p_sys;
1695 const chapter_item_t *psz_curr_chapter;
1697 /* update current chapter/seekpoint */
1698 if ( editions.size() )
1700 /* 1st, we need to know in which chapter we are */
1701 psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1703 /* we have moved to a new chapter */
1704 if (psz_curr_chapter != NULL && psz_current_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1706 if (psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1708 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1709 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1712 if ( editions[i_current_edition].b_ordered )
1714 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1715 if (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1716 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1717 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1718 /* only seek after each duration >= end timecode of the current chapter */
1721 // i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1722 // i_start_pts = psz_curr_chapter->i_user_start_time;
1724 psz_current_chapter = psz_curr_chapter;
1728 void chapter_item_t::Append( const chapter_item_t & chapter )
1730 // we are appending content for the same chapter UID
1732 chapter_item_t *p_chapter;
1734 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1736 p_chapter = FindChapter( chapter.sub_chapters[i] );
1737 if ( p_chapter != NULL )
1739 p_chapter->Append( chapter.sub_chapters[i] );
1743 sub_chapters.push_back( chapter.sub_chapters[i] );
1747 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1748 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1751 chapter_item_t * chapter_item_t::FindChapter( const chapter_item_t & chapter )
1754 for ( i=0; i<sub_chapters.size(); i++)
1756 if ( sub_chapters[i].i_uid == chapter.i_uid )
1757 return &sub_chapters[i];
1762 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter )
1764 demux_sys_t *p_sys = p_demux->p_sys;
1765 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1766 matroska_segment_t *p_segment = p_vsegment->Segment();
1767 mtime_t i_time_offset = 0;
1771 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1772 if( i_date < 0 && f_percent < 0 )
1774 msg_Warn( p_demux, "cannot seek nowhere !" );
1777 if( f_percent > 1.0 )
1779 msg_Warn( p_demux, "cannot seek so far !" );
1783 /* seek without index or without date */
1784 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1786 if (p_sys->f_duration >= 0)
1788 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1792 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1794 msg_Dbg( p_demux, "inacurate way of seeking" );
1795 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1797 if( p_segment->index[i_index].i_position >= i_pos)
1802 if( i_index == p_segment->i_index )
1807 i_date = p_segment->index[i_index].i_time;
1810 if( p_segment->index[i_index].i_position < i_pos )
1814 msg_Warn( p_demux, "searching for cluster, could take some time" );
1816 /* search a cluster */
1817 while( ( el = p_sys->ep->Get() ) != NULL )
1819 if( MKV_IS_ID( el, KaxCluster ) )
1821 KaxCluster *cluster = (KaxCluster*)el;
1823 /* add it to the index */
1824 p_segment->IndexAppendCluster( cluster );
1826 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1828 p_sys->cluster = cluster;
1839 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1842 /*****************************************************************************
1843 * Demux: reads and demuxes data packets
1844 *****************************************************************************
1845 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1846 *****************************************************************************/
1847 static int Demux( demux_t *p_demux)
1849 demux_sys_t *p_sys = p_demux->p_sys;
1850 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1851 matroska_segment_t *p_segmet = p_vsegment->Segment();
1852 if ( p_segmet == NULL ) return 0;
1853 int i_block_count = 0;
1856 int64_t i_block_duration;
1857 int64_t i_block_ref1;
1858 int64_t i_block_ref2;
1862 if ( p_sys->demuxer.b_die )
1865 if( p_sys->i_pts >= p_sys->i_start_pts )
1866 p_vsegment->UpdateCurrentToChapter( *p_demux );
1868 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1870 /* nothing left to read in this ordered edition */
1871 if ( !p_vsegment->SelectNext() )
1873 p_segmet->UnSelect( );
1875 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1877 /* switch to the next segment */
1878 p_segmet = p_vsegment->Segment();
1879 if ( !p_segmet->Select( 0 ) )
1881 msg_Err( p_demux, "Failed to select new segment" );
1888 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1890 if ( p_vsegment->EditionIsOrdered() )
1892 // check if there are more chapters to read
1893 if ( p_vsegment->CurrentChapter() != NULL )
1895 p_sys->i_pts = p_vsegment->CurrentChapter()->i_user_end_time;
1901 msg_Warn( p_demux, "cannot get block EOF?" );
1902 p_segmet->UnSelect( );
1904 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1906 /* switch to the next segment */
1907 if ( !p_vsegment->SelectNext() )
1908 // no more segments in this stream
1910 p_segmet = p_vsegment->Segment();
1911 if ( !p_segmet->Select( 0 ) )
1913 msg_Err( p_demux, "Failed to select new segment" );
1920 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1922 if( p_sys->i_pts >= p_sys->i_start_pts )
1924 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1927 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1932 // TODO optimize when there is need to leave or when seeking has been called
1933 if( i_block_count > 5 )
1942 /*****************************************************************************
1944 *****************************************************************************/
1945 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1951 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1953 if( i_size <= 0 || mb_eof )
1958 return stream_Read( s, p_buffer, i_size );
1960 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1966 case seek_beginning:
1970 i_pos = stream_Size( s ) - i_offset;
1973 i_pos= stream_Tell( s ) + i_offset;
1977 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1984 if( stream_Seek( s, i_pos ) )
1990 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1994 uint64 vlc_stream_io_callback::getFilePointer( void )
1996 return stream_Tell( s );
1998 void vlc_stream_io_callback::close( void )
2004 /*****************************************************************************
2005 * Ebml Stream parser
2006 *****************************************************************************/
2007 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2014 mi_remain_size[0] = el_start->GetSize();
2016 for( i = 1; i < 6; i++ )
2022 mb_keep = VLC_FALSE;
2023 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2026 EbmlParser::~EbmlParser( void )
2030 for( i = 1; i < mi_level; i++ )
2036 mb_keep = VLC_FALSE;
2040 void EbmlParser::Up( void )
2042 if( mi_user_level == mi_level )
2044 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2050 void EbmlParser::Down( void )
2056 void EbmlParser::Keep( void )
2061 int EbmlParser::GetLevel( void )
2063 return mi_user_level;
2066 void EbmlParser::Reset( demux_t *p_demux )
2068 while ( mi_level > 0)
2070 delete m_el[mi_level];
2071 m_el[mi_level] = NULL;
2074 mi_user_level = mi_level = 1;
2075 #if LIBEBML_VERSION >= 0x000704
2076 // a little faster and cleaner
2077 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2079 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2081 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2084 EbmlElement *EbmlParser::Get( void )
2088 if( mi_user_level != mi_level )
2094 EbmlElement *ret = m_got;
2100 if( m_el[mi_level] )
2102 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2105 delete m_el[mi_level];
2107 mb_keep = VLC_FALSE;
2110 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2111 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2122 delete m_el[mi_level - 1];
2123 m_got = m_el[mi_level -1] = m_el[mi_level];
2124 m_el[mi_level] = NULL;
2131 else if( m_el[mi_level] == NULL )
2133 fprintf( stderr," m_el[mi_level] == NULL\n" );
2136 return m_el[mi_level];
2140 /*****************************************************************************
2142 * * LoadCues : load the cues element and update index
2144 * * LoadTags : load ... the tags element
2146 * * InformationCreate : create all information, load tags if present
2148 *****************************************************************************/
2149 void matroska_segment_t::LoadCues( )
2151 int64_t i_sav_position = es.I_O().getFilePointer();
2153 EbmlElement *el, *cues;
2155 /* *** Load the cue if found *** */
2156 if( i_cues_position < 0 )
2158 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2160 // IndexAppendCluster( cluster );
2163 vlc_bool_t b_seekable;
2165 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2169 msg_Dbg( &sys.demuxer, "loading cues" );
2170 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2171 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2175 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2176 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2180 ep = new EbmlParser( &es, cues, &sys.demuxer );
2181 while( ( el = ep->Get() ) != NULL )
2183 if( MKV_IS_ID( el, KaxCuePoint ) )
2185 #define idx index[i_index]
2188 idx.i_block_number= -1;
2189 idx.i_position = -1;
2191 idx.b_key = VLC_TRUE;
2194 while( ( el = ep->Get() ) != NULL )
2196 if( MKV_IS_ID( el, KaxCueTime ) )
2198 KaxCueTime &ctime = *(KaxCueTime*)el;
2200 ctime.ReadData( es.I_O() );
2202 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2204 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2207 while( ( el = ep->Get() ) != NULL )
2209 if( MKV_IS_ID( el, KaxCueTrack ) )
2211 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2213 ctrack.ReadData( es.I_O() );
2214 idx.i_track = uint16( ctrack );
2216 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2218 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2220 ccpos.ReadData( es.I_O() );
2221 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2223 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2225 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2227 cbnum.ReadData( es.I_O() );
2228 idx.i_block_number = uint32( cbnum );
2232 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2239 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2245 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2246 " track=%d bnum=%d", idx.i_time, idx.i_position,
2247 idx.i_track, idx.i_block_number );
2251 if( i_index >= i_index_max )
2253 i_index_max += 1024;
2254 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2260 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2268 msg_Dbg( &sys.demuxer, "loading cues done." );
2269 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2272 void matroska_segment_t::LoadTags( )
2274 int64_t i_sav_position = es.I_O().getFilePointer();
2276 EbmlElement *el, *tags;
2278 msg_Dbg( &sys.demuxer, "loading tags" );
2279 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2280 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2284 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2285 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2289 msg_Dbg( &sys.demuxer, "Tags" );
2290 ep = new EbmlParser( &es, tags, &sys.demuxer );
2291 while( ( el = ep->Get() ) != NULL )
2293 if( MKV_IS_ID( el, KaxTag ) )
2295 msg_Dbg( &sys.demuxer, "+ Tag" );
2297 while( ( el = ep->Get() ) != NULL )
2299 if( MKV_IS_ID( el, KaxTagTargets ) )
2301 msg_Dbg( &sys.demuxer, "| + Targets" );
2303 while( ( el = ep->Get() ) != NULL )
2305 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2309 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2311 msg_Dbg( &sys.demuxer, "| + General" );
2313 while( ( el = ep->Get() ) != NULL )
2315 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2319 else if( MKV_IS_ID( el, KaxTagGenres ) )
2321 msg_Dbg( &sys.demuxer, "| + Genres" );
2323 while( ( el = ep->Get() ) != NULL )
2325 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2329 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2331 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2333 while( ( el = ep->Get() ) != NULL )
2335 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2339 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2341 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2343 while( ( el = ep->Get() ) != NULL )
2345 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2349 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2351 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2353 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2355 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2357 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2359 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2361 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2363 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2365 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2367 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2369 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2371 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2373 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2375 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2379 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2386 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2392 msg_Dbg( &sys.demuxer, "loading tags done." );
2393 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2396 /*****************************************************************************
2398 *****************************************************************************/
2399 void matroska_segment_t::ParseSeekHead( KaxSeekHead *seekhead )
2403 int i_upper_level = 0;
2405 msg_Dbg( &sys.demuxer, "| + Seek head" );
2407 /* Master elements */
2408 seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2410 for( i = 0; i < seekhead->ListSize(); i++ )
2412 EbmlElement *l = (*seekhead)[i];
2414 if( MKV_IS_ID( l, KaxSeek ) )
2416 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2417 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2422 for( j = 0; j < sk->ListSize(); j++ )
2424 EbmlElement *l = (*sk)[j];
2426 if( MKV_IS_ID( l, KaxSeekID ) )
2428 KaxSeekID &sid = *(KaxSeekID*)l;
2429 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2431 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2433 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2434 i_pos = uint64( spos );
2438 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2444 if( id == KaxCues::ClassInfos.GlobalId )
2446 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2447 i_cues_position = segment->GetGlobalPosition( i_pos );
2449 else if( id == KaxChapters::ClassInfos.GlobalId )
2451 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2452 i_chapters_position = segment->GetGlobalPosition( i_pos );
2454 else if( id == KaxTags::ClassInfos.GlobalId )
2456 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2457 i_tags_position = segment->GetGlobalPosition( i_pos );
2463 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2468 /*****************************************************************************
2470 *****************************************************************************/
2471 void matroska_segment_t::ParseTrackEntry( KaxTrackEntry *m )
2477 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2479 tk = new mkv_track_t();
2480 tracks.push_back( tk );
2482 /* Init the track */
2483 memset( tk, 0, sizeof( mkv_track_t ) );
2485 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2486 tk->fmt.psz_language = strdup("English");
2487 tk->fmt.psz_description = NULL;
2489 tk->b_default = VLC_TRUE;
2490 tk->b_enabled = VLC_TRUE;
2491 tk->b_silent = VLC_FALSE;
2492 tk->i_number = tracks.size() - 1;
2493 tk->i_extra_data = 0;
2494 tk->p_extra_data = NULL;
2495 tk->psz_codec = NULL;
2496 tk->i_default_duration = 0;
2497 tk->f_timecodescale = 1.0;
2499 tk->b_inited = VLC_FALSE;
2500 tk->i_data_init = 0;
2501 tk->p_data_init = NULL;
2503 tk->psz_codec_name = NULL;
2504 tk->psz_codec_settings = NULL;
2505 tk->psz_codec_info_url = NULL;
2506 tk->psz_codec_download_url = NULL;
2508 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2510 for( i = 0; i < m->ListSize(); i++ )
2512 EbmlElement *l = (*m)[i];
2514 if( MKV_IS_ID( l, KaxTrackNumber ) )
2516 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2518 tk->i_number = uint32( tnum );
2519 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2521 else if( MKV_IS_ID( l, KaxTrackUID ) )
2523 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2525 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2527 else if( MKV_IS_ID( l, KaxTrackType ) )
2530 KaxTrackType &ttype = *(KaxTrackType*)l;
2532 switch( uint8(ttype) )
2536 tk->fmt.i_cat = AUDIO_ES;
2540 tk->fmt.i_cat = VIDEO_ES;
2542 case track_subtitle:
2543 psz_type = "subtitle";
2544 tk->fmt.i_cat = SPU_ES;
2547 psz_type = "unknown";
2548 tk->fmt.i_cat = UNKNOWN_ES;
2552 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2554 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2556 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2558 // tk->b_enabled = uint32( fenb );
2559 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2560 // uint32( fenb ) );
2562 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2564 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2566 tk->b_default = uint32( fdef );
2567 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2569 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2571 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2573 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2575 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2577 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2579 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2581 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2583 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2585 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2587 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2589 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2591 tk->i_default_duration = uint64(defd);
2592 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2594 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2596 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2598 tk->f_timecodescale = float( ttcs );
2599 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2601 else if( MKV_IS_ID( l, KaxTrackName ) )
2603 KaxTrackName &tname = *(KaxTrackName*)l;
2605 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2606 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2608 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2610 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2612 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2613 msg_Dbg( &sys.demuxer,
2614 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2616 else if( MKV_IS_ID( l, KaxCodecID ) )
2618 KaxCodecID &codecid = *(KaxCodecID*)l;
2620 tk->psz_codec = strdup( string( codecid ).c_str() );
2621 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2623 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2625 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2627 tk->i_extra_data = cpriv.GetSize();
2628 if( tk->i_extra_data > 0 )
2630 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2631 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2633 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2635 else if( MKV_IS_ID( l, KaxCodecName ) )
2637 KaxCodecName &cname = *(KaxCodecName*)l;
2639 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2640 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2642 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2644 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2645 MkvTree( sys.demuxer, 3, "Content Encodings" );
2646 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2648 EbmlElement *l2 = (*cencs)[i];
2649 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2651 MkvTree( sys.demuxer, 4, "Content Encoding" );
2652 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2653 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2655 EbmlElement *l3 = (*cenc)[i];
2656 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2658 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2659 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2661 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2663 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2664 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2666 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2668 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2669 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2671 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2673 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2674 MkvTree( sys.demuxer, 5, "Content Compression" );
2675 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2677 EbmlElement *l4 = (*compr)[i];
2678 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2680 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2681 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2682 if( uint32( compalg ) == 0 )
2684 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2689 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2696 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2703 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2708 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2710 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2712 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2713 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2715 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2717 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2719 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2720 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2722 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2724 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2726 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2727 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2729 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2731 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2733 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2735 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2737 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2739 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2741 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2743 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2746 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2749 for( j = 0; j < tkv->ListSize(); j++ )
2751 EbmlElement *l = (*tkv)[j];
2752 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2754 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2756 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2758 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2760 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2762 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2765 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2767 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2769 tk->fmt.video.i_width = uint16( vwidth );
2770 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2772 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2774 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2776 tk->fmt.video.i_height = uint16( vheight );
2777 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2779 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2781 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2783 tk->fmt.video.i_visible_width = uint16( vwidth );
2784 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2786 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2788 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2790 tk->fmt.video.i_visible_height = uint16( vheight );
2791 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2793 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2795 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2797 tk->f_fps = float( vfps );
2798 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2800 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2802 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2804 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2805 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2807 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2809 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2811 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2813 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2815 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2817 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2821 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2824 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2825 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2827 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2829 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2832 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2834 for( j = 0; j < tka->ListSize(); j++ )
2836 EbmlElement *l = (*tka)[j];
2838 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2840 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2842 tk->fmt.audio.i_rate = (int)float( afreq );
2843 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2845 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2847 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2849 tk->fmt.audio.i_channels = uint8( achan );
2850 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2852 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2854 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2856 tk->fmt.audio.i_bitspersample = uint8( abits );
2857 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2861 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2867 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2868 typeid(*l).name() );
2873 /*****************************************************************************
2875 *****************************************************************************/
2876 void matroska_segment_t::ParseTracks( KaxTracks *tracks )
2880 int i_upper_level = 0;
2882 msg_Dbg( &sys.demuxer, "| + Tracks" );
2884 /* Master elements */
2885 tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2887 for( i = 0; i < tracks->ListSize(); i++ )
2889 EbmlElement *l = (*tracks)[i];
2891 if( MKV_IS_ID( l, KaxTrackEntry ) )
2893 ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
2897 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2902 /*****************************************************************************
2904 *****************************************************************************/
2905 void matroska_segment_t::ParseInfo( KaxInfo *info )
2910 int i_upper_level = 0;
2912 msg_Dbg( &sys.demuxer, "| + Information" );
2914 /* Master elements */
2915 m = static_cast<EbmlMaster *>(info);
2916 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2918 for( i = 0; i < m->ListSize(); i++ )
2920 EbmlElement *l = (*m)[i];
2922 if( MKV_IS_ID( l, KaxSegmentUID ) )
2924 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2926 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2928 else if( MKV_IS_ID( l, KaxPrevUID ) )
2930 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2932 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2934 else if( MKV_IS_ID( l, KaxNextUID ) )
2936 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2938 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2940 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2942 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2944 i_timescale = uint64(tcs);
2946 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2949 else if( MKV_IS_ID( l, KaxDuration ) )
2951 KaxDuration &dur = *(KaxDuration*)l;
2953 i_duration = mtime_t( double( dur ) );
2955 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
2958 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2960 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2962 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2964 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2965 psz_muxing_application );
2967 else if( MKV_IS_ID( l, KaxWritingApp ) )
2969 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2971 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2973 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2974 psz_writing_application );
2976 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2978 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2980 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2982 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2983 psz_segment_filename );
2985 else if( MKV_IS_ID( l, KaxTitle ) )
2987 KaxTitle &title = *(KaxTitle*)l;
2989 psz_title = UTF8ToStr( UTFstring( title ) );
2991 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2993 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2995 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2997 families.push_back(*uid);
2999 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
3001 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3002 else if( MKV_IS_ID( l, KaxDateUTC ) )
3004 KaxDateUTC &date = *(KaxDateUTC*)l;
3009 i_date = date.GetEpochDate();
3010 memset( buffer, 0, 256 );
3011 if( gmtime_r( &i_date, &tmres ) &&
3012 asctime_r( &tmres, buffer ) )
3014 buffer[strlen( buffer)-1]= '\0';
3015 psz_date_utc = strdup( buffer );
3016 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3020 #if LIBMATROSKA_VERSION >= 0x000704
3021 else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3023 KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3024 chapter_translation_t translated;
3026 p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3027 for( j = 0; j < p_trans->ListSize(); j++ )
3029 EbmlElement *l = (*p_trans)[j];
3031 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3033 translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3035 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3037 translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3039 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3041 translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3045 translations.push_back( translated );
3050 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3054 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3055 i_duration = mtime_t(f_dur);
3059 /*****************************************************************************
3061 *****************************************************************************/
3062 void matroska_segment_t::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_t & chapters )
3066 if( sys.title == NULL )
3068 sys.title = vlc_input_title_New();
3071 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3072 for( i = 0; i < ca->ListSize(); i++ )
3074 EbmlElement *l = (*ca)[i];
3076 if( MKV_IS_ID( l, KaxChapterUID ) )
3078 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3079 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3081 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3083 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3084 chapters.b_display_seekpoint = uint8( flag ) == 0;
3086 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3088 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3090 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3091 chapters.i_start_time = uint64( start ) / I64C(1000);
3093 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3095 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3097 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3098 chapters.i_end_time = uint64( end ) / I64C(1000);
3100 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3102 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3104 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3107 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3108 for( j = 0; j < cd->ListSize(); j++ )
3110 EbmlElement *l= (*cd)[j];
3112 if( MKV_IS_ID( l, KaxChapterString ) )
3116 KaxChapterString &name =*(KaxChapterString*)l;
3117 for (k = 0; k < i_level; k++)
3118 chapters.psz_name += '+';
3119 chapters.psz_name += ' ';
3120 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3122 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3124 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3126 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3127 const char *psz = string( lang ).c_str();
3129 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3131 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3133 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3134 const char *psz = string( ct ).c_str();
3136 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3140 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3142 chapter_item_t new_sub_chapter;
3143 ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), new_sub_chapter );
3144 new_sub_chapter.psz_parent = &chapters;
3145 chapters.sub_chapters.push_back( new_sub_chapter );
3150 /*****************************************************************************
3152 *****************************************************************************/
3153 void matroska_segment_t::ParseChapters( KaxChapters *chapters )
3157 int i_upper_level = 0;
3160 /* Master elements */
3161 chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3163 for( i = 0; i < chapters->ListSize(); i++ )
3165 EbmlElement *l = (*chapters)[i];
3167 if( MKV_IS_ID( l, KaxEditionEntry ) )
3169 chapter_edition_t edition;
3171 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3173 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3174 for( j = 0; j < E->ListSize(); j++ )
3176 EbmlElement *l = (*E)[j];
3178 if( MKV_IS_ID( l, KaxChapterAtom ) )
3180 chapter_item_t new_sub_chapter;
3181 ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), new_sub_chapter );
3182 edition.sub_chapters.push_back( new_sub_chapter );
3184 else if( MKV_IS_ID( l, KaxEditionUID ) )
3186 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3188 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3190 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3192 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3194 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3195 i_default_edition = stored_editions.size();
3199 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3202 stored_editions.push_back( edition );
3206 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3210 for( i = 0; i < stored_editions.size(); i++ )
3212 stored_editions[i].RefreshChapters( );
3215 if ( stored_editions[i_default_edition].b_ordered )
3217 /* update the duration of the segment according to the sum of all sub chapters */
3218 i_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3224 void matroska_segment_t::ParseCluster( )
3229 int i_upper_level = 0;
3231 /* Master elements */
3232 m = static_cast<EbmlMaster *>( cluster );
3233 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3235 for( i = 0; i < m->ListSize(); i++ )
3237 EbmlElement *l = (*m)[i];
3239 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3241 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3243 cluster->InitTimecode( uint64( ctc ), i_timescale );
3248 i_start_time = cluster->GlobalTimecode() / 1000;
3251 /*****************************************************************************
3252 * InformationCreate:
3253 *****************************************************************************/
3254 void matroska_segment_t::InformationCreate( )
3258 sys.meta = vlc_meta_New();
3262 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3266 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3268 if( psz_segment_filename )
3270 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3272 if( psz_muxing_application )
3274 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3276 if( psz_writing_application )
3278 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3281 for( i_track = 0; i_track < tracks.size(); i_track++ )
3283 mkv_track_t *tk = tracks[i_track];
3284 vlc_meta_t *mtk = vlc_meta_New();
3286 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3287 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3288 sys.meta->track[sys.meta->i_track++] = mtk;
3290 if( tk->fmt.psz_description )
3292 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3294 if( tk->psz_codec_name )
3296 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3298 if( tk->psz_codec_settings )
3300 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3302 if( tk->psz_codec_info_url )
3304 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3306 if( tk->psz_codec_download_url )
3308 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3312 if( i_tags_position >= 0 )
3314 vlc_bool_t b_seekable;
3316 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3325 /*****************************************************************************
3327 *****************************************************************************/
3329 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3331 #define idx index[i_index]
3333 idx.i_block_number= -1;
3334 idx.i_position = cluster->GetElementPosition();
3336 idx.b_key = VLC_TRUE;
3339 if( i_index >= i_index_max )
3341 i_index_max += 1024;
3342 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3347 static char * UTF8ToStr( const UTFstring &u )
3356 p = dst = (char*)malloc( i_src + 1);
3375 void chapter_edition_t::RefreshChapters( )
3377 chapter_item_t::RefreshChapters( b_ordered, -1 );
3378 b_display_seekpoint = false;
3381 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3383 int64_t i_user_time = i_prev_user_time;
3385 // first the sub-chapters, and then ourself
3386 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3387 while ( index != sub_chapters.end() )
3389 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time );
3395 i_user_start_time = i_prev_user_time;
3396 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3398 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3402 i_user_end_time = i_user_time;
3407 std::sort( sub_chapters.begin(), sub_chapters.end() );
3408 i_user_start_time = i_start_time;
3409 if ( i_end_time != -1 )
3410 i_user_end_time = i_end_time;
3411 else if ( i_user_time != -1 )
3412 i_user_end_time = i_user_time;
3414 i_user_end_time = i_user_start_time;
3417 return i_user_end_time;
3420 mtime_t chapter_edition_t::Duration() const
3422 mtime_t i_result = 0;
3424 if ( sub_chapters.size() )
3426 std::vector<chapter_item_t>::const_iterator index = sub_chapters.end();
3428 i_result = (*index).i_user_end_time;
3434 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3436 const chapter_item_t *psz_result = NULL;
3438 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3440 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3441 while ( index != sub_chapters.end() && psz_result == NULL )
3443 psz_result = (*index).FindTimecode( i_user_timecode );
3447 if ( psz_result == NULL )
3454 void demux_sys_t::PreloadFamily( const matroska_segment_t & of_segment )
3456 for (size_t i=0; i<opened_segments.size(); i++)
3458 opened_segments[i]->PreloadFamily( of_segment );
3461 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3466 for (size_t i=0; i<families.size(); i++)
3468 for (size_t j=0; j<of_segment.families.size(); j++)
3470 if ( families[i] == of_segment.families[j] )
3478 // preload all the linked segments for all preloaded segments
3479 void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
3481 size_t i_preloaded, i;
3483 delete p_current_segment;
3484 p_current_segment = new virtual_segment_t( p_segment );
3486 // fill our current virtual segment with all hard linked segments
3489 for ( i=0; i< opened_segments.size(); i++ )
3491 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3493 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3495 p_current_segment->Sort( );
3497 p_current_segment->PreloadLinked( );
3500 bool demux_sys_t::PreparePlayback( )
3502 p_current_segment->LoadCues();
3503 f_duration = p_current_segment->Duration();
3505 /* add information */
3506 p_current_segment->Segment()->InformationCreate( );
3508 p_current_segment->Segment()->Select( 0 );
3510 return p_current_segment->Select( *title );
3513 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3515 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3516 if ( *p_itema == p_item_b->prev_segment_uid )
3519 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3520 if ( *p_itema == p_item_b->segment_uid )
3523 if ( *p_itema == p_item_b->prev_segment_uid )
3529 bool matroska_segment_t::Preload( )
3534 EbmlElement *el = NULL;
3536 ep->Reset( &sys.demuxer );
3538 while( ( el = ep->Get() ) != NULL )
3540 if( MKV_IS_ID( el, KaxInfo ) )
3542 ParseInfo( static_cast<KaxInfo*>( el ) );
3544 else if( MKV_IS_ID( el, KaxTracks ) )
3546 ParseTracks( static_cast<KaxTracks*>( el ) );
3548 else if( MKV_IS_ID( el, KaxSeekHead ) )
3550 ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3552 else if( MKV_IS_ID( el, KaxCues ) )
3554 msg_Dbg( &sys.demuxer, "| + Cues" );
3556 else if( MKV_IS_ID( el, KaxCluster ) )
3558 msg_Dbg( &sys.demuxer, "| + Cluster" );
3560 cluster = (KaxCluster*)el;
3562 i_start_pos = cluster->GetElementPosition();
3566 /* stop parsing the stream */
3569 else if( MKV_IS_ID( el, KaxAttachments ) )
3571 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3573 else if( MKV_IS_ID( el, KaxChapters ) )
3575 msg_Dbg( &sys.demuxer, "| + Chapters" );
3576 ParseChapters( static_cast<KaxChapters*>( el ) );
3578 else if( MKV_IS_ID( el, KaxTag ) )
3580 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3584 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3593 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3595 for (size_t i=0; i<opened_segments.size(); i++)
3597 if ( opened_segments[i]->segment_uid == uid )
3598 return opened_segments[i];
3603 void virtual_segment_t::Sort()
3605 // keep the current segment index
3606 matroska_segment_t *p_segment = linked_segments[i_current_segment];
3608 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
3610 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3611 if ( linked_segments[i_current_segment] == p_segment )
3615 size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
3618 // check if it's not already in here
3619 for ( i=0; i<linked_segments.size(); i++ )
3621 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3625 // find possible mates
3626 for ( i=0; i<linked_uids.size(); i++ )
3628 if ( p_segment->segment_uid == linked_uids[i]
3629 || p_segment->prev_segment_uid == linked_uids[i]
3630 || p_segment->next_segment_uid == linked_uids[i] )
3632 linked_segments.push_back( p_segment );
3634 AppendUID( p_segment->prev_segment_uid );
3635 AppendUID( p_segment->next_segment_uid );
3643 void virtual_segment_t::PreloadLinked( )
3645 for ( size_t i=0; i<linked_segments.size(); i++ )
3647 linked_segments[i]->Preload( );
3649 i_current_edition = linked_segments[0]->i_default_edition;
3652 mtime_t virtual_segment_t::Duration() const
3655 if ( linked_segments.size() == 0 )
3658 matroska_segment_t *p_last_segment = linked_segments[linked_segments.size()-1];
3659 // p_last_segment->ParseCluster( );
3661 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3666 void virtual_segment_t::LoadCues( )
3668 for ( size_t i=0; i<linked_segments.size(); i++ )
3670 linked_segments[i]->LoadCues();
3674 void virtual_segment_t::AppendUID( const EbmlBinary & UID )
3676 if ( UID.GetBuffer() == NULL )
3679 for (size_t i=0; i<linked_uids.size(); i++)
3681 if ( UID == linked_uids[i] )
3684 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3687 void matroska_segment_t::Seek( mtime_t i_date, mtime_t i_time_offset )
3690 int i_track_skipping;
3691 int64_t i_block_duration;
3692 int64_t i_block_ref1;
3693 int64_t i_block_ref2;
3695 int64_t i_seek_position = i_start_pos;
3696 int64_t i_seek_time = i_start_time;
3702 for( ; i_idx < i_index; i_idx++ )
3704 if( index[i_idx].i_time + i_time_offset > i_date )
3715 i_seek_position = index[i_idx].i_position;
3716 i_seek_time = index[i_idx].i_time;
3719 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3720 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3722 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3725 ep = new EbmlParser( &es, segment, &sys.demuxer );
3728 sys.i_start_pts = i_date;
3730 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3732 /* now parse until key frame */
3733 #define tk tracks[i_track]
3734 i_track_skipping = 0;
3735 for( i_track = 0; i_track < tracks.size(); i_track++ )
3737 if( tk->fmt.i_cat == VIDEO_ES )
3739 tk->b_search_keyframe = VLC_TRUE;
3742 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3746 while( i_track_skipping > 0 )
3748 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3750 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3755 for( i_track = 0; i_track < tracks.size(); i_track++ )
3757 if( tk->i_number == block->TrackNum() )
3763 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3765 if( i_track < tracks.size() )
3767 if( sys.i_pts >= sys.i_start_pts )
3769 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3770 i_track_skipping = 0;
3772 else if( tk->fmt.i_cat == VIDEO_ES )
3774 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3776 tk->b_search_keyframe = VLC_FALSE;
3779 if( !tk->b_search_keyframe )
3781 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3791 void virtual_segment_t::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter )
3793 demux_sys_t *p_sys = demuxer.p_sys;
3796 // find the actual time for an ordered edition
3797 if ( psz_chapter == NULL )
3799 if ( EditionIsOrdered() )
3801 /* 1st, we need to know in which chapter we are */
3802 psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3806 if ( psz_chapter != NULL )
3808 psz_current_chapter = psz_chapter;
3809 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3810 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3811 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3814 // find the best matching segment
3815 for ( i=0; i<linked_segments.size(); i++ )
3817 if ( i_date < linked_segments[i]->i_start_time )
3824 if ( i_current_segment != i )
3826 linked_segments[i_current_segment]->UnSelect();
3827 linked_segments[i]->Select( i_date );
3828 i_current_segment = i;
3831 linked_segments[i]->Seek( i_date, i_time_offset );