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"
84 #include "ebml/StdIOCallback.h"
87 #include "mp4/libmp4.h"
93 #define MATROSKA_COMPRESSION_NONE 0
94 #define MATROSKA_COMPRESSION_ZLIB 1
96 #define MKVD_TIMECODESCALE 1000000
99 * What's between a directory and a filename?
102 #define DIRECTORY_SEPARATOR '\\'
104 #define DIRECTORY_SEPARATOR '/'
107 using namespace LIBMATROSKA_NAMESPACE;
110 /*****************************************************************************
112 *****************************************************************************/
113 static int Open ( vlc_object_t * );
114 static void Close( vlc_object_t * );
117 set_shortname( _("Matroska") );
118 set_description( _("Matroska stream demuxer" ) );
119 set_capability( "demux2", 50 );
120 set_callbacks( Open, Close );
121 set_category( CAT_INPUT );
122 set_subcategory( SUBCAT_INPUT_DEMUX );
124 add_bool( "mkv-use-ordered-chapters", 1, NULL,
125 N_("Ordered chapters"),
126 N_("Play ordered chapters as specified in the segment"), VLC_TRUE );
128 add_bool( "mkv-use-chapter-codec", 1, NULL,
129 N_("Chapter codecs"),
130 N_("Use chapter codecs found in the segment"), VLC_TRUE );
132 add_bool( "mkv-seek-percent", 0, NULL,
133 N_("Seek based on percent not time"),
134 N_("Seek based on percent not time"), VLC_TRUE );
136 add_bool( "mkv-use-dummy", 0, NULL,
137 N_("Dummy Elements"),
138 N_("Read and discard unknown EBML elements (not good for broken files)"), VLC_TRUE );
140 add_shortcut( "mka" );
141 add_shortcut( "mkv" );
144 /*****************************************************************************
146 *****************************************************************************/
148 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
149 int result, dstsize, n;
154 d_stream.zalloc = (alloc_func)0;
155 d_stream.zfree = (free_func)0;
156 d_stream.opaque = (voidpf)0;
157 result = inflateInit(&d_stream);
160 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
164 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
165 d_stream.avail_in = p_in_block->i_buffer;
167 p_block = block_New( p_this, 0 );
172 p_block = block_Realloc( p_block, 0, n * 1000 );
173 dst = (unsigned char *)p_block->p_buffer;
174 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
175 d_stream.avail_out = 1000;
176 result = inflate(&d_stream, Z_NO_FLUSH);
177 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
179 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
183 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
184 ( result != Z_STREAM_END ) );
186 dstsize = d_stream.total_out;
187 inflateEnd( &d_stream );
189 p_block = block_Realloc( p_block, 0, dstsize );
190 p_block->i_buffer = dstsize;
191 block_Release( p_in_block );
198 * Helper function to print the mkv parse tree
200 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
205 msg_Err( &demuxer, "too deep tree" );
208 va_start( args, psz_format );
209 static char *psz_foo = "| | | | | | | | | |";
210 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
211 strncpy( psz_foo2, psz_foo, 4 * i_level );
212 psz_foo2[ 4 * i_level ] = '+';
213 psz_foo2[ 4 * i_level + 1 ] = ' ';
214 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
215 __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
220 /*****************************************************************************
222 *****************************************************************************/
223 class vlc_stream_io_callback: public IOCallback
230 vlc_stream_io_callback( stream_t * );
232 virtual uint32 read ( void *p_buffer, size_t i_size);
233 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
234 virtual size_t write ( const void *p_buffer, size_t i_size);
235 virtual uint64 getFilePointer ( void );
236 virtual void close ( void );
239 /*****************************************************************************
241 *****************************************************************************/
245 EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux );
250 void Reset( demux_t *p_demux );
251 EbmlElement *Get( void );
254 int GetLevel( void );
259 EbmlElement *m_el[10];
260 int64_t mi_remain_size[10];
270 /*****************************************************************************
271 * Some functions to manipulate memory
272 *****************************************************************************/
273 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
274 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
276 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
279 /*****************************************************************************
280 * definitions of structures and functions used by this plugins
281 *****************************************************************************/
284 vlc_bool_t b_default;
285 vlc_bool_t b_enabled;
286 unsigned int i_number;
289 uint8_t *p_extra_data;
293 uint64_t i_default_duration;
294 float f_timecodescale;
302 /* data to be send first */
304 uint8_t *p_data_init;
306 /* hack : it's for seek */
307 vlc_bool_t b_search_keyframe;
311 char *psz_codec_name;
312 char *psz_codec_settings;
313 char *psz_codec_info_url;
314 char *psz_codec_download_url;
316 /* encryption/compression */
317 int i_compression_type;
332 class chapter_codec_cmds_t
336 class dvd_chapter_codec_t : public chapter_codec_cmds_t
340 class matroska_script_codec_t : public chapter_codec_cmds_t
350 ,i_user_start_time(-1)
353 ,b_display_seekpoint(true)
360 for (i=0; i<enter_cmds.size(); i++)
361 delete enter_cmds[i];
362 for (i=0; i<during_cmds.size(); i++)
363 delete during_cmds[i];
364 for (i=0; i<leave_cmds.size(); i++)
365 delete leave_cmds[i];
368 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
369 void PublishChapters( input_title_t & title, int i_level );
370 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
371 void Append( const chapter_item_t & edition );
372 chapter_item_t * FindChapter( const chapter_item_t & chapter );
374 int64_t i_start_time, i_end_time;
375 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
376 std::vector<chapter_item_t> sub_chapters;
379 bool b_display_seekpoint;
380 std::string psz_name;
381 chapter_item_t *psz_parent;
383 bool operator<( const chapter_item_t & item ) const
385 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) );
389 std::vector<chapter_codec_cmds_t*> enter_cmds;
390 std::vector<chapter_codec_cmds_t*> during_cmds;
391 std::vector<chapter_codec_cmds_t*> leave_cmds;
397 class chapter_edition_t : public chapter_item_t
404 void RefreshChapters( );
405 mtime_t Duration() const;
406 void PublishChapters( input_title_t & title );
413 class matroska_segment_t
416 matroska_segment_t( demux_sys_t & demuxer, EbmlStream & estream )
419 ,i_timescale(MKVD_TIMECODESCALE)
423 ,i_chapters_position(-1)
430 ,psz_muxing_application(NULL)
431 ,psz_writing_application(NULL)
432 ,psz_segment_filename(NULL)
435 ,i_default_edition(0)
440 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
443 ~matroska_segment_t()
445 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
447 #define tk tracks[i_track]
448 if( tk->fmt.psz_description )
450 free( tk->fmt.psz_description );
454 free( tk->psz_codec );
456 if( tk->fmt.psz_language )
458 free( tk->fmt.psz_language );
464 if( psz_writing_application )
466 free( psz_writing_application );
468 if( psz_muxing_application )
470 free( psz_muxing_application );
472 if( psz_segment_filename )
474 free( psz_segment_filename );
482 free( psz_date_utc );
494 uint64_t i_timescale;
496 /* duration of the segment */
498 mtime_t i_start_time;
501 std::vector<mkv_track_t*> tracks;
504 int64_t i_cues_position;
505 int64_t i_chapters_position;
506 int64_t i_tags_position;
510 KaxSegmentUID segment_uid;
511 KaxPrevUID prev_segment_uid;
512 KaxNextUID next_segment_uid;
520 char *psz_muxing_application;
521 char *psz_writing_application;
522 char *psz_segment_filename;
526 std::vector<chapter_edition_t> stored_editions;
527 int i_default_edition;
529 std::vector<KaxSegmentFamily> families;
536 bool PreloadFamily( const matroska_segment_t & segment );
537 void ParseInfo( EbmlElement *info );
538 void ParseChapters( EbmlElement *chapters );
539 void ParseSeekHead( EbmlElement *seekhead );
540 void ParseTracks( EbmlElement *tracks );
541 void ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters );
542 void ParseTrackEntry( EbmlMaster *m );
543 void ParseCluster( );
544 void IndexAppendCluster( KaxCluster *cluster );
547 void InformationCreate( );
548 void Seek( mtime_t i_date, mtime_t i_time_offset );
549 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
550 bool Select( mtime_t i_start_time );
552 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
555 // class holding hard-linked segment together in the playback order
556 class virtual_segment_t
559 virtual_segment_t( matroska_segment_t *p_segment )
560 :i_current_segment(0)
561 ,i_current_edition(-1)
562 ,psz_current_chapter(NULL)
564 linked_segments.push_back( p_segment );
566 AppendUID( p_segment->segment_uid );
567 AppendUID( p_segment->prev_segment_uid );
568 AppendUID( p_segment->next_segment_uid );
572 size_t AddSegment( matroska_segment_t *p_segment );
573 void PreloadLinked( );
574 mtime_t Duration( ) const;
576 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter );
578 inline chapter_edition_t *Edition()
580 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
581 return &editions[i_current_edition];
585 inline bool EditionIsOrdered() const
587 return (editions.size() != 0 && i_current_edition >= 0 && editions[i_current_edition].b_ordered);
590 matroska_segment_t * Segment() const
592 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
594 return linked_segments[i_current_segment];
597 inline const chapter_item_t *CurrentChapter() const {
598 return psz_current_chapter;
603 if ( i_current_segment < linked_segments.size()-1 )
611 /* TODO handle/merge chapters here */
612 void UpdateCurrentToChapter( demux_t & demux );
613 bool Select( input_title_t & title );
616 std::vector<matroska_segment_t*> linked_segments;
617 std::vector<KaxSegmentUID> linked_uids;
618 size_t i_current_segment;
620 std::vector<chapter_edition_t> editions;
621 int i_current_edition;
622 const chapter_item_t *psz_current_chapter;
624 void AppendUID( const EbmlBinary & UID );
627 class matroska_stream_t
630 matroska_stream_t( demux_sys_t & demuxer )
645 std::vector<matroska_segment_t*> segments;
653 demux_sys_t( demux_t & demux )
660 ,p_current_segment(NULL)
666 for (size_t i=0; i<streams.size(); i++)
668 for ( size_t i=0; i<opened_segments.size(); i++ )
669 delete opened_segments[i];
677 mtime_t i_chapter_time;
681 input_title_t *title;
683 std::vector<matroska_stream_t*> streams;
684 std::vector<matroska_segment_t*> opened_segments;
685 virtual_segment_t *p_current_segment;
687 /* duration of the stream */
690 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
691 void PreloadFamily( const matroska_segment_t & of_segment );
692 void PreloadLinked( matroska_segment_t *p_segment );
693 bool PreparePlayback( );
694 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
697 static int Demux ( demux_t * );
698 static int Control( demux_t *, int, va_list );
699 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
701 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
703 static char *UTF8ToStr ( const UTFstring &u );
705 /*****************************************************************************
706 * Open: initializes matroska demux structures
707 *****************************************************************************/
708 static int Open( vlc_object_t * p_this )
710 demux_t *p_demux = (demux_t*)p_this;
712 matroska_stream_t *p_stream;
713 matroska_segment_t *p_segment;
715 std::string s_path, s_filename;
716 vlc_stream_io_callback *p_io_callback;
717 EbmlStream *p_io_stream;
719 /* peek the begining */
720 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
722 /* is a valid file */
723 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
724 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
726 /* Set the demux function */
727 p_demux->pf_demux = Demux;
728 p_demux->pf_control = Control;
729 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
731 p_io_callback = new vlc_stream_io_callback( p_demux->s );
732 p_io_stream = new EbmlStream( *p_io_callback );
734 if( p_io_stream == NULL )
736 msg_Err( p_demux, "failed to create EbmlStream" );
737 delete p_io_callback;
742 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
743 if( p_stream == NULL )
745 msg_Err( p_demux, "cannot find KaxSegment" );
748 p_sys->streams.push_back( p_stream );
750 p_stream->p_in = p_io_callback;
751 p_stream->p_es = p_io_stream;
753 for (size_t i=0; i<p_stream->segments.size(); i++)
755 p_stream->segments[i]->Preload();
758 p_segment = p_stream->segments[0];
759 if( p_segment->cluster == NULL )
761 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
764 // reset the stream reading to the first cluster of the segment used
765 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
767 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
768 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
770 // assume it's a regular file
771 // get the directory path
772 s_path = p_demux->psz_path;
773 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
775 s_path = s_path.substr(0,s_path.length()-1);
779 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
781 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
785 struct dirent *p_file_item;
786 DIR *p_src_dir = opendir(s_path.c_str());
788 if (p_src_dir != NULL)
790 while ((p_file_item = (dirent *) readdir(p_src_dir)))
792 if (strlen(p_file_item->d_name) > 4)
794 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
796 if (!s_filename.compare(p_demux->psz_path))
797 continue; // don't reuse the original opened file
799 #if defined(__GNUC__) && (__GNUC__ < 3)
800 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
801 !s_filename.compare("mka", s_filename.length() - 3, 3))
803 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
804 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
807 // test wether this file belongs to the our family
808 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
809 EbmlStream *p_estream = new EbmlStream(*p_file_io);
811 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
812 if ( p_stream == NULL )
814 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
820 p_stream->p_in = p_file_io;
821 p_stream->p_es = p_estream;
822 p_sys->streams.push_back( p_stream );
827 closedir( p_src_dir );
831 p_sys->PreloadFamily( *p_segment );
832 p_sys->PreloadLinked( p_segment );
833 if ( !p_sys->PreparePlayback( ) )
835 msg_Err( p_demux, "cannot use the segment" );
846 /*****************************************************************************
847 * Close: frees unused data
848 *****************************************************************************/
849 static void Close( vlc_object_t *p_this )
851 demux_t *p_demux = (demux_t*)p_this;
852 demux_sys_t *p_sys = p_demux->p_sys;
857 /*****************************************************************************
859 *****************************************************************************/
860 static int Control( demux_t *p_demux, int i_query, va_list args )
862 demux_sys_t *p_sys = p_demux->p_sys;
867 vlc_meta_t **pp_meta;
872 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
873 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
876 case DEMUX_GET_LENGTH:
877 pi64 = (int64_t*)va_arg( args, int64_t * );
878 if( p_sys->f_duration > 0.0 )
880 *pi64 = (int64_t)(p_sys->f_duration * 1000);
885 case DEMUX_GET_POSITION:
886 pf = (double*)va_arg( args, double * );
887 if ( p_sys->f_duration > 0.0 )
888 *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);
891 case DEMUX_SET_POSITION:
892 f = (double)va_arg( args, double );
893 Seek( p_demux, -1, f, NULL );
897 pi64 = (int64_t*)va_arg( args, int64_t * );
898 *pi64 = p_sys->i_pts;
901 case DEMUX_GET_TITLE_INFO:
902 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
904 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
905 int *pi_int = (int*)va_arg( args, int* );
908 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
910 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
916 case DEMUX_SET_TITLE:
917 /* TODO handle editions as titles & DVD titles as well */
918 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
924 case DEMUX_SET_SEEKPOINT:
925 /* FIXME do a better implementation */
926 i_skp = (int)va_arg( args, int );
928 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
930 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
931 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
932 p_demux->info.i_seekpoint = i_skp;
944 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
956 i_level = ep->GetLevel();
958 if( el == NULL && *pp_block != NULL )
960 /* update the index */
961 #define idx index[i_index - 1]
962 if( i_index > 0 && idx.i_time == -1 )
964 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
965 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
973 if( ep->GetLevel() > 1 )
978 msg_Warn( &sys.demuxer, "EOF" );
985 if( MKV_IS_ID( el, KaxCluster ) )
987 cluster = (KaxCluster*)el;
989 /* add it to the index */
991 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
993 IndexAppendCluster( cluster );
996 // reset silent tracks
997 for (size_t i=0; i<tracks.size(); i++)
999 tracks[i]->b_silent = VLC_FALSE;
1004 else if( MKV_IS_ID( el, KaxCues ) )
1006 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
1007 return VLC_EGENERIC;
1011 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
1014 else if( i_level == 2 )
1016 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1018 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1020 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
1021 cluster->InitTimecode( uint64( ctc ), i_timescale );
1023 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1027 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1032 else if( i_level == 3 )
1034 if( MKV_IS_ID( el, KaxBlock ) )
1036 *pp_block = (KaxBlock*)el;
1038 (*pp_block)->ReadData( es.I_O() );
1039 (*pp_block)->SetParent( *cluster );
1043 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1045 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1047 dur.ReadData( es.I_O() );
1048 *pi_duration = uint64( dur );
1050 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1052 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1054 ref.ReadData( es.I_O() );
1055 if( *pi_ref1 == -1 )
1057 *pi_ref1 = int64( ref );
1061 *pi_ref2 = int64( ref );
1064 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1066 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1067 track_num.ReadData( es.I_O() );
1069 for (size_t i=0; i<tracks.size(); i++)
1071 if ( tracks[i]->i_number == uint32(track_num))
1073 tracks[i]->b_silent = VLC_TRUE;
1081 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1082 return VLC_EGENERIC;
1087 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1090 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1091 memcpy( p_block->p_buffer, p_mem, i_mem );
1092 //p_block->i_rate = p_input->stream.control.i_rate;
1096 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1097 mtime_t i_duration )
1099 demux_sys_t *p_sys = p_demux->p_sys;
1100 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1106 #define tk p_segment->tracks[i_track]
1107 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1109 if( tk->i_number == block->TrackNum() )
1115 if( i_track >= p_segment->tracks.size() )
1117 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1120 if( tk->p_es == NULL )
1122 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1125 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1127 return; /* discard audio packets that shouldn't be rendered */
1130 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1133 tk->b_inited = VLC_FALSE;
1137 /* First send init data */
1138 if( !tk->b_inited && tk->i_data_init > 0 )
1142 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1143 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1144 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1146 tk->b_inited = VLC_TRUE;
1149 for( i = 0; i < block->NumberFrames(); i++ )
1152 DataBuffer &data = block->GetBuffer(i);
1154 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1156 if( p_block == NULL )
1161 #if defined(HAVE_ZLIB_H)
1162 if( tk->i_compression_type )
1164 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1168 // TODO implement correct timestamping when B frames are used
1169 if( tk->fmt.i_cat != VIDEO_ES )
1171 p_block->i_dts = p_block->i_pts = i_pts;
1175 p_block->i_dts = i_pts;
1179 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1181 p_block->i_length = i_duration * 1000;
1184 es_out_Send( p_demux->out, tk->p_es, p_block );
1186 /* use time stamp only for first block */
1193 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1195 int i_upper_lvl = 0;
1197 EbmlElement *p_l0, *p_l1, *p_l2;
1198 bool b_keep_stream = false, b_keep_segment;
1200 // verify the EBML Header
1201 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1206 p_l0->SkipData(*p_estream, EbmlHead_Context);
1209 // find all segments in this file
1210 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1216 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1220 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1223 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1224 b_keep_segment = false;
1226 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1227 p_segment1->ep = ep;
1228 p_segment1->segment = (KaxSegment*)p_l0;
1230 while ((p_l1 = ep->Get()))
1232 if (MKV_IS_ID(p_l1, KaxInfo))
1234 // find the families of this segment
1235 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1237 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1238 for( i = 0; i < p_info->ListSize(); i++ )
1240 EbmlElement *l = (*p_info)[i];
1242 if( MKV_IS_ID( l, KaxSegmentUID ) )
1244 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1245 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1246 if ( !b_keep_segment )
1247 break; // this segment is already known
1248 opened_segments.push_back( p_segment1 );
1249 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1251 else if( MKV_IS_ID( l, KaxPrevUID ) )
1253 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1255 else if( MKV_IS_ID( l, KaxNextUID ) )
1257 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1259 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1261 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1262 p_segment1->families.push_back( *p_fam );
1268 if ( b_keep_segment )
1270 b_keep_stream = true;
1271 p_stream1->segments.push_back( p_segment1 );
1277 p_l0->SkipData(*p_estream, EbmlHead_Context);
1278 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1281 if ( !b_keep_stream )
1290 bool matroska_segment_t::Select( mtime_t i_start_time )
1295 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1296 for( i_track = 0; i_track < tracks.size(); i_track++ )
1298 #define tk tracks[i_track]
1299 if( tk->fmt.i_cat == UNKNOWN_ES )
1301 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1306 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1308 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1310 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1311 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1315 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1317 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1318 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1319 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1321 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1322 if( tk->fmt.i_extra > 0 )
1324 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1325 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1329 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1330 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1332 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1334 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1336 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1338 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1340 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1342 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1343 tk->fmt.b_packetized = VLC_FALSE;
1344 tk->fmt.i_extra = tk->i_extra_data;
1345 tk->fmt.p_extra = malloc( tk->i_extra_data );
1346 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1350 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1353 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1355 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1357 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1361 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1366 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1367 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1368 tk->fmt.i_codec = p_box->i_type;
1369 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1370 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1371 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1372 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1373 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1374 MP4_FreeBox_sample_vide( p_box );
1376 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1378 stream_Delete( p_mp4_stream );
1381 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1383 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1385 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1386 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1390 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1392 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1394 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1395 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1396 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1397 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1398 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1400 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1401 if( tk->fmt.i_extra > 0 )
1403 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1404 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1408 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1409 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1410 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1412 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1414 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1416 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1418 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1420 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1422 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1424 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1425 tk->fmt.i_extra = tk->i_extra_data;
1426 tk->fmt.p_extra = malloc( tk->i_extra_data );
1427 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1429 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1431 int i, i_offset = 1, i_size[3], i_extra;
1434 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1436 /* Split the 3 headers */
1437 if( tk->p_extra_data[0] != 0x02 )
1438 msg_Err( &sys.demuxer, "invalid vorbis header" );
1440 for( i = 0; i < 2; i++ )
1443 while( i_offset < tk->i_extra_data )
1445 i_size[i] += tk->p_extra_data[i_offset];
1446 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1450 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1451 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1452 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1454 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1455 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1456 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1457 for( i = 0; i < 3; i++ )
1459 *(p_extra++) = i_size[i] >> 8;
1460 *(p_extra++) = i_size[i] & 0xFF;
1461 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1463 p_extra += i_size[i];
1464 i_extra += i_size[i];
1467 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1468 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1470 int i_profile, i_srate;
1471 static unsigned int i_sample_rates[] =
1473 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1474 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1477 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1478 /* create data for faad (MP4DecSpecificDescrTag)*/
1480 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1484 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1488 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1497 for( i_srate = 0; i_srate < 13; i_srate++ )
1499 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1504 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1506 tk->fmt.i_extra = 2;
1507 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1508 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1509 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1511 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1512 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1513 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1515 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1517 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1521 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1523 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1525 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1527 /* FIXME: support this codec */
1528 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1529 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1531 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1533 /* FIXME: support this codec */
1534 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1535 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1537 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1539 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1540 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1542 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1543 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1544 !strcmp( tk->psz_codec, "S_SSA" ) ||
1545 !strcmp( tk->psz_codec, "S_ASS" ))
1547 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1548 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1550 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1552 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1553 if( tk->i_extra_data )
1556 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1557 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1558 p_buf[tk->i_extra_data] = '\0';
1560 p_start = strstr( p_buf, "size:" );
1561 if( sscanf( p_start, "size: %dx%d",
1562 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1564 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 );
1568 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1573 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1575 /* FIXME: support this codec */
1576 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1577 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1581 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1582 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1586 tk->fmt.i_priority = 1000;
1589 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1591 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1595 sys.i_start_pts = i_start_time;
1596 // reset the stream reading to the first cluster of the segment used
1597 es.I_O().setFilePointer( i_start_pos );
1600 ep = new EbmlParser( &es, segment, &sys.demuxer );
1605 void matroska_segment_t::UnSelect( )
1609 for( i_track = 0; i_track < tracks.size(); i_track++ )
1611 #define tk tracks[i_track]
1612 if ( tk->p_es != NULL )
1614 es_out_Del( sys.demuxer.out, tk->p_es );
1623 bool virtual_segment_t::Select( input_title_t & title )
1625 if ( linked_segments.size() == 0 )
1628 // !!! should be called only once !!!
1629 matroska_segment_t *p_segment;
1632 // copy editions from the first segment
1633 p_segment = linked_segments[0];
1634 editions = p_segment->stored_editions;
1636 for ( i=1 ; i<linked_segments.size(); i++ )
1638 p_segment = linked_segments[i];
1639 // FIXME assume we have the same editions in all segments
1640 for (j=0; j<p_segment->stored_editions.size(); j++)
1641 editions[j].Append( p_segment->stored_editions[j] );
1644 if ( Edition() != NULL )
1645 Edition()->PublishChapters( title );
1650 void chapter_edition_t::PublishChapters( input_title_t & title )
1652 title.i_seekpoint = 0;
1653 if ( title.seekpoint != NULL )
1654 free( title.seekpoint );
1655 chapter_item_t::PublishChapters( title, 0 );
1658 void chapter_item_t::PublishChapters( input_title_t & title, int i_level )
1660 if (b_display_seekpoint)
1662 seekpoint_t *sk = vlc_seekpoint_New();
1664 sk->i_level = i_level;
1665 sk->i_time_offset = i_start_time;
1666 sk->psz_name = strdup( psz_name.c_str() );
1668 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1669 title.i_seekpoint++;
1670 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1671 title.seekpoint[title.i_seekpoint-1] = sk;
1673 i_seekpoint_num = title.i_seekpoint;
1676 for ( size_t i=0; i<sub_chapters.size() ; i++)
1678 sub_chapters[i].PublishChapters( title, i_level+1 );
1682 void virtual_segment_t::UpdateCurrentToChapter( demux_t & demux )
1684 demux_sys_t & sys = *demux.p_sys;
1685 const chapter_item_t *psz_curr_chapter;
1687 /* update current chapter/seekpoint */
1688 if ( editions.size() )
1690 /* 1st, we need to know in which chapter we are */
1691 psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1693 /* we have moved to a new chapter */
1694 if (psz_curr_chapter != NULL && psz_current_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1696 if (psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1698 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1699 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1702 if ( editions[i_current_edition].b_ordered )
1704 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1705 if (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1706 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1707 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1708 /* only seek after each duration >= end timecode of the current chapter */
1711 // i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1712 // i_start_pts = psz_curr_chapter->i_user_start_time;
1714 psz_current_chapter = psz_curr_chapter;
1718 void chapter_item_t::Append( const chapter_item_t & chapter )
1720 // we are appending content for the same chapter UID
1722 chapter_item_t *p_chapter;
1724 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1726 p_chapter = FindChapter( chapter.sub_chapters[i] );
1727 if ( p_chapter != NULL )
1729 p_chapter->Append( chapter.sub_chapters[i] );
1733 sub_chapters.push_back( chapter.sub_chapters[i] );
1737 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1738 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1741 chapter_item_t * chapter_item_t::FindChapter( const chapter_item_t & chapter )
1744 for ( i=0; i<sub_chapters.size(); i++)
1746 if ( sub_chapters[i].i_uid == chapter.i_uid )
1747 return &sub_chapters[i];
1752 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter )
1754 demux_sys_t *p_sys = p_demux->p_sys;
1755 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1756 matroska_segment_t *p_segment = p_vsegment->Segment();
1757 mtime_t i_time_offset = 0;
1761 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1762 if( i_date < 0 && f_percent < 0 )
1764 msg_Warn( p_demux, "cannot seek nowhere !" );
1767 if( f_percent > 1.0 )
1769 msg_Warn( p_demux, "cannot seek so far !" );
1773 /* seek without index or without date */
1774 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1776 if (p_sys->f_duration >= 0)
1778 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1782 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1784 msg_Dbg( p_demux, "inacurate way of seeking" );
1785 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1787 if( p_segment->index[i_index].i_position >= i_pos)
1792 if( i_index == p_segment->i_index )
1797 i_date = p_segment->index[i_index].i_time;
1800 if( p_segment->index[i_index].i_position < i_pos )
1804 msg_Warn( p_demux, "searching for cluster, could take some time" );
1806 /* search a cluster */
1807 while( ( el = p_sys->ep->Get() ) != NULL )
1809 if( MKV_IS_ID( el, KaxCluster ) )
1811 KaxCluster *cluster = (KaxCluster*)el;
1813 /* add it to the index */
1814 p_segment->IndexAppendCluster( cluster );
1816 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1818 p_sys->cluster = cluster;
1829 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1832 /*****************************************************************************
1833 * Demux: reads and demuxes data packets
1834 *****************************************************************************
1835 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1836 *****************************************************************************/
1837 static int Demux( demux_t *p_demux)
1839 demux_sys_t *p_sys = p_demux->p_sys;
1840 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1841 matroska_segment_t *p_segmet = p_vsegment->Segment();
1842 if ( p_segmet == NULL ) return 0;
1843 int i_block_count = 0;
1846 int64_t i_block_duration;
1847 int64_t i_block_ref1;
1848 int64_t i_block_ref2;
1852 if ( p_sys->demuxer.b_die )
1855 if( p_sys->i_pts >= p_sys->i_start_pts )
1856 p_vsegment->UpdateCurrentToChapter( *p_demux );
1858 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1860 /* nothing left to read in this ordered edition */
1861 if ( !p_vsegment->SelectNext() )
1863 p_segmet->UnSelect( );
1865 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1867 /* switch to the next segment */
1868 p_segmet = p_vsegment->Segment();
1869 if ( !p_segmet->Select( 0 ) )
1871 msg_Err( p_demux, "Failed to select new segment" );
1878 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1880 if ( p_vsegment->EditionIsOrdered() )
1882 // check if there are more chapters to read
1883 if ( p_vsegment->CurrentChapter() != NULL )
1885 p_sys->i_pts = p_vsegment->CurrentChapter()->i_user_end_time;
1891 msg_Warn( p_demux, "cannot get block EOF?" );
1892 p_segmet->UnSelect( );
1894 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1896 /* switch to the next segment */
1897 if ( !p_vsegment->SelectNext() )
1898 // no more segments in this stream
1900 p_segmet = p_vsegment->Segment();
1901 if ( !p_segmet->Select( 0 ) )
1903 msg_Err( p_demux, "Failed to select new segment" );
1910 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1912 if( p_sys->i_pts >= p_sys->i_start_pts )
1914 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1917 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1922 // TODO optimize when there is need to leave or when seeking has been called
1923 if( i_block_count > 5 )
1932 /*****************************************************************************
1934 *****************************************************************************/
1935 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1941 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1943 if( i_size <= 0 || mb_eof )
1948 return stream_Read( s, p_buffer, i_size );
1950 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1956 case seek_beginning:
1960 i_pos = stream_Size( s ) - i_offset;
1963 i_pos= stream_Tell( s ) + i_offset;
1967 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1974 if( stream_Seek( s, i_pos ) )
1980 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1984 uint64 vlc_stream_io_callback::getFilePointer( void )
1986 return stream_Tell( s );
1988 void vlc_stream_io_callback::close( void )
1994 /*****************************************************************************
1995 * Ebml Stream parser
1996 *****************************************************************************/
1997 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2004 mi_remain_size[0] = el_start->GetSize();
2006 for( i = 1; i < 6; i++ )
2012 mb_keep = VLC_FALSE;
2013 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2016 EbmlParser::~EbmlParser( void )
2020 for( i = 1; i < mi_level; i++ )
2026 mb_keep = VLC_FALSE;
2030 void EbmlParser::Up( void )
2032 if( mi_user_level == mi_level )
2034 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2040 void EbmlParser::Down( void )
2046 void EbmlParser::Keep( void )
2051 int EbmlParser::GetLevel( void )
2053 return mi_user_level;
2056 void EbmlParser::Reset( demux_t *p_demux )
2058 while ( mi_level > 0)
2060 delete m_el[mi_level];
2061 m_el[mi_level] = NULL;
2064 mi_user_level = mi_level = 1;
2065 #if LIBEBML_VERSION >= 0x000704
2066 // a little faster and cleaner
2067 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2069 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2071 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2074 EbmlElement *EbmlParser::Get( void )
2078 if( mi_user_level != mi_level )
2084 EbmlElement *ret = m_got;
2090 if( m_el[mi_level] )
2092 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2095 delete m_el[mi_level];
2097 mb_keep = VLC_FALSE;
2100 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2101 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2112 delete m_el[mi_level - 1];
2113 m_got = m_el[mi_level -1] = m_el[mi_level];
2114 m_el[mi_level] = NULL;
2121 else if( m_el[mi_level] == NULL )
2123 fprintf( stderr," m_el[mi_level] == NULL\n" );
2126 return m_el[mi_level];
2130 /*****************************************************************************
2132 * * LoadCues : load the cues element and update index
2134 * * LoadTags : load ... the tags element
2136 * * InformationCreate : create all information, load tags if present
2138 *****************************************************************************/
2139 void matroska_segment_t::LoadCues( )
2141 int64_t i_sav_position = es.I_O().getFilePointer();
2143 EbmlElement *el, *cues;
2145 /* *** Load the cue if found *** */
2146 if( i_cues_position < 0 )
2148 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2150 // IndexAppendCluster( cluster );
2153 vlc_bool_t b_seekable;
2155 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2159 msg_Dbg( &sys.demuxer, "loading cues" );
2160 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2161 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2165 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2166 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2170 ep = new EbmlParser( &es, cues, &sys.demuxer );
2171 while( ( el = ep->Get() ) != NULL )
2173 if( MKV_IS_ID( el, KaxCuePoint ) )
2175 #define idx index[i_index]
2178 idx.i_block_number= -1;
2179 idx.i_position = -1;
2181 idx.b_key = VLC_TRUE;
2184 while( ( el = ep->Get() ) != NULL )
2186 if( MKV_IS_ID( el, KaxCueTime ) )
2188 KaxCueTime &ctime = *(KaxCueTime*)el;
2190 ctime.ReadData( es.I_O() );
2192 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2194 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2197 while( ( el = ep->Get() ) != NULL )
2199 if( MKV_IS_ID( el, KaxCueTrack ) )
2201 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2203 ctrack.ReadData( es.I_O() );
2204 idx.i_track = uint16( ctrack );
2206 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2208 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2210 ccpos.ReadData( es.I_O() );
2211 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2213 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2215 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2217 cbnum.ReadData( es.I_O() );
2218 idx.i_block_number = uint32( cbnum );
2222 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2229 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2235 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2236 " track=%d bnum=%d", idx.i_time, idx.i_position,
2237 idx.i_track, idx.i_block_number );
2241 if( i_index >= i_index_max )
2243 i_index_max += 1024;
2244 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2250 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2258 msg_Dbg( &sys.demuxer, "loading cues done." );
2259 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2262 void matroska_segment_t::LoadTags( )
2264 int64_t i_sav_position = es.I_O().getFilePointer();
2266 EbmlElement *el, *tags;
2268 msg_Dbg( &sys.demuxer, "loading tags" );
2269 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2270 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2274 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2275 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2279 msg_Dbg( &sys.demuxer, "Tags" );
2280 ep = new EbmlParser( &es, tags, &sys.demuxer );
2281 while( ( el = ep->Get() ) != NULL )
2283 if( MKV_IS_ID( el, KaxTag ) )
2285 msg_Dbg( &sys.demuxer, "+ Tag" );
2287 while( ( el = ep->Get() ) != NULL )
2289 if( MKV_IS_ID( el, KaxTagTargets ) )
2291 msg_Dbg( &sys.demuxer, "| + Targets" );
2293 while( ( el = ep->Get() ) != NULL )
2295 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2299 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2301 msg_Dbg( &sys.demuxer, "| + General" );
2303 while( ( el = ep->Get() ) != NULL )
2305 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2309 else if( MKV_IS_ID( el, KaxTagGenres ) )
2311 msg_Dbg( &sys.demuxer, "| + Genres" );
2313 while( ( el = ep->Get() ) != NULL )
2315 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2319 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2321 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2323 while( ( el = ep->Get() ) != NULL )
2325 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2329 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2331 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2333 while( ( el = ep->Get() ) != NULL )
2335 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2339 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2341 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2343 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2345 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2347 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2349 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2351 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2353 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2355 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2357 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2359 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2361 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2363 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2365 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2369 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2376 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2382 msg_Dbg( &sys.demuxer, "loading tags done." );
2383 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2386 /*****************************************************************************
2388 *****************************************************************************/
2389 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2394 int i_upper_level = 0;
2396 msg_Dbg( &sys.demuxer, "| + Seek head" );
2398 /* Master elements */
2399 m = static_cast<EbmlMaster *>(seekhead);
2400 m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2402 for( i = 0; i < m->ListSize(); i++ )
2404 EbmlElement *l = (*m)[i];
2406 if( MKV_IS_ID( l, KaxSeek ) )
2408 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2409 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2414 for( j = 0; j < sk->ListSize(); j++ )
2416 EbmlElement *l = (*sk)[j];
2418 if( MKV_IS_ID( l, KaxSeekID ) )
2420 KaxSeekID &sid = *(KaxSeekID*)l;
2421 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2423 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2425 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2426 i_pos = uint64( spos );
2430 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2436 if( id == KaxCues::ClassInfos.GlobalId )
2438 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2439 i_cues_position = segment->GetGlobalPosition( i_pos );
2441 else if( id == KaxChapters::ClassInfos.GlobalId )
2443 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2444 i_chapters_position = segment->GetGlobalPosition( i_pos );
2446 else if( id == KaxTags::ClassInfos.GlobalId )
2448 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2449 i_tags_position = segment->GetGlobalPosition( i_pos );
2455 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2460 /*****************************************************************************
2462 *****************************************************************************/
2463 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2469 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2471 tk = new mkv_track_t();
2472 tracks.push_back( tk );
2474 /* Init the track */
2475 memset( tk, 0, sizeof( mkv_track_t ) );
2477 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2478 tk->fmt.psz_language = strdup("English");
2479 tk->fmt.psz_description = NULL;
2481 tk->b_default = VLC_TRUE;
2482 tk->b_enabled = VLC_TRUE;
2483 tk->b_silent = VLC_FALSE;
2484 tk->i_number = tracks.size() - 1;
2485 tk->i_extra_data = 0;
2486 tk->p_extra_data = NULL;
2487 tk->psz_codec = NULL;
2488 tk->i_default_duration = 0;
2489 tk->f_timecodescale = 1.0;
2491 tk->b_inited = VLC_FALSE;
2492 tk->i_data_init = 0;
2493 tk->p_data_init = NULL;
2495 tk->psz_codec_name = NULL;
2496 tk->psz_codec_settings = NULL;
2497 tk->psz_codec_info_url = NULL;
2498 tk->psz_codec_download_url = NULL;
2500 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2502 for( i = 0; i < m->ListSize(); i++ )
2504 EbmlElement *l = (*m)[i];
2506 if( MKV_IS_ID( l, KaxTrackNumber ) )
2508 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2510 tk->i_number = uint32( tnum );
2511 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2513 else if( MKV_IS_ID( l, KaxTrackUID ) )
2515 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2517 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2519 else if( MKV_IS_ID( l, KaxTrackType ) )
2522 KaxTrackType &ttype = *(KaxTrackType*)l;
2524 switch( uint8(ttype) )
2528 tk->fmt.i_cat = AUDIO_ES;
2532 tk->fmt.i_cat = VIDEO_ES;
2534 case track_subtitle:
2535 psz_type = "subtitle";
2536 tk->fmt.i_cat = SPU_ES;
2539 psz_type = "unknown";
2540 tk->fmt.i_cat = UNKNOWN_ES;
2544 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2546 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2548 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2550 // tk->b_enabled = uint32( fenb );
2551 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2552 // uint32( fenb ) );
2554 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2556 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2558 tk->b_default = uint32( fdef );
2559 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2561 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2563 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2565 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2567 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2569 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2571 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2573 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2575 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2577 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2579 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2581 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2583 tk->i_default_duration = uint64(defd);
2584 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2586 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2588 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2590 tk->f_timecodescale = float( ttcs );
2591 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2593 else if( MKV_IS_ID( l, KaxTrackName ) )
2595 KaxTrackName &tname = *(KaxTrackName*)l;
2597 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2598 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2600 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2602 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2604 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2605 msg_Dbg( &sys.demuxer,
2606 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2608 else if( MKV_IS_ID( l, KaxCodecID ) )
2610 KaxCodecID &codecid = *(KaxCodecID*)l;
2612 tk->psz_codec = strdup( string( codecid ).c_str() );
2613 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2615 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2617 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2619 tk->i_extra_data = cpriv.GetSize();
2620 if( tk->i_extra_data > 0 )
2622 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2623 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2625 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2627 else if( MKV_IS_ID( l, KaxCodecName ) )
2629 KaxCodecName &cname = *(KaxCodecName*)l;
2631 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2632 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2634 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2636 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2637 MkvTree( sys.demuxer, 3, "Content Encodings" );
2638 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2640 EbmlElement *l2 = (*cencs)[i];
2641 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2643 MkvTree( sys.demuxer, 4, "Content Encoding" );
2644 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2645 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2647 EbmlElement *l3 = (*cenc)[i];
2648 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2650 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2651 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2653 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2655 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2656 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2658 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2660 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2661 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2663 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2665 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2666 MkvTree( sys.demuxer, 5, "Content Compression" );
2667 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2669 EbmlElement *l4 = (*compr)[i];
2670 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2672 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2673 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2674 if( uint32( compalg ) == 0 )
2676 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2681 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2688 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2695 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2700 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2702 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2704 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2705 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2707 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2709 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2711 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2712 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2714 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2716 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2718 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2719 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2721 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2723 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2725 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2727 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2729 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2731 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2733 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2735 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2738 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2741 for( j = 0; j < tkv->ListSize(); j++ )
2743 EbmlElement *l = (*tkv)[j];
2744 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2746 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2748 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2750 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2752 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2754 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2757 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2759 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2761 tk->fmt.video.i_width = uint16( vwidth );
2762 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2764 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2766 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2768 tk->fmt.video.i_height = uint16( vheight );
2769 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2771 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2773 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2775 tk->fmt.video.i_visible_width = uint16( vwidth );
2776 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2778 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2780 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2782 tk->fmt.video.i_visible_height = uint16( vheight );
2783 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2785 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2787 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2789 tk->f_fps = float( vfps );
2790 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2792 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2794 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2796 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2797 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2799 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2801 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2803 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2805 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2807 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2809 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2813 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2816 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2817 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2819 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2821 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2824 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2826 for( j = 0; j < tka->ListSize(); j++ )
2828 EbmlElement *l = (*tka)[j];
2830 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2832 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2834 tk->fmt.audio.i_rate = (int)float( afreq );
2835 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2837 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2839 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2841 tk->fmt.audio.i_channels = uint8( achan );
2842 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2844 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2846 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2848 tk->fmt.audio.i_bitspersample = uint8( abits );
2849 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2853 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2859 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2860 typeid(*l).name() );
2865 /*****************************************************************************
2867 *****************************************************************************/
2868 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2873 int i_upper_level = 0;
2875 msg_Dbg( &sys.demuxer, "| + Tracks" );
2877 /* Master elements */
2878 m = static_cast<EbmlMaster *>(tracks);
2879 m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2881 for( i = 0; i < m->ListSize(); i++ )
2883 EbmlElement *l = (*m)[i];
2885 if( MKV_IS_ID( l, KaxTrackEntry ) )
2887 ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2891 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2896 /*****************************************************************************
2898 *****************************************************************************/
2899 void matroska_segment_t::ParseInfo( EbmlElement *info )
2904 int i_upper_level = 0;
2906 msg_Dbg( &sys.demuxer, "| + Information" );
2908 /* Master elements */
2909 m = static_cast<EbmlMaster *>(info);
2910 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2912 for( i = 0; i < m->ListSize(); i++ )
2914 EbmlElement *l = (*m)[i];
2916 if( MKV_IS_ID( l, KaxSegmentUID ) )
2918 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2920 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2922 else if( MKV_IS_ID( l, KaxPrevUID ) )
2924 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2926 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2928 else if( MKV_IS_ID( l, KaxNextUID ) )
2930 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2932 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2934 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2936 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2938 i_timescale = uint64(tcs);
2940 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2943 else if( MKV_IS_ID( l, KaxDuration ) )
2945 KaxDuration &dur = *(KaxDuration*)l;
2947 i_duration = mtime_t( double( dur ) );
2949 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
2952 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2954 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2956 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2958 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2959 psz_muxing_application );
2961 else if( MKV_IS_ID( l, KaxWritingApp ) )
2963 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2965 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2967 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2968 psz_writing_application );
2970 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2972 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2974 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2976 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2977 psz_segment_filename );
2979 else if( MKV_IS_ID( l, KaxTitle ) )
2981 KaxTitle &title = *(KaxTitle*)l;
2983 psz_title = UTF8ToStr( UTFstring( title ) );
2985 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2987 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2989 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2991 families.push_back(*uid);
2993 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2995 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2996 else if( MKV_IS_ID( l, KaxDateUTC ) )
2998 KaxDateUTC &date = *(KaxDateUTC*)l;
3003 i_date = date.GetEpochDate();
3004 memset( buffer, 0, 256 );
3005 if( gmtime_r( &i_date, &tmres ) &&
3006 asctime_r( &tmres, buffer ) )
3008 buffer[strlen( buffer)-1]= '\0';
3009 psz_date_utc = strdup( buffer );
3010 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
3016 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3020 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3021 i_duration = mtime_t(f_dur);
3025 /*****************************************************************************
3027 *****************************************************************************/
3028 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
3032 if( sys.title == NULL )
3034 sys.title = vlc_input_title_New();
3037 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3038 for( i = 0; i < ca->ListSize(); i++ )
3040 EbmlElement *l = (*ca)[i];
3042 if( MKV_IS_ID( l, KaxChapterUID ) )
3044 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3045 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3047 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3049 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3050 chapters.b_display_seekpoint = uint8( flag ) == 0;
3052 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3054 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3056 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3057 chapters.i_start_time = uint64( start ) / I64C(1000);
3059 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3061 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3063 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3064 chapters.i_end_time = uint64( end ) / I64C(1000);
3066 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3068 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3070 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3073 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3074 for( j = 0; j < cd->ListSize(); j++ )
3076 EbmlElement *l= (*cd)[j];
3078 if( MKV_IS_ID( l, KaxChapterString ) )
3082 KaxChapterString &name =*(KaxChapterString*)l;
3083 for (k = 0; k < i_level; k++)
3084 chapters.psz_name += '+';
3085 chapters.psz_name += ' ';
3086 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3088 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3090 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3092 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3093 const char *psz = string( lang ).c_str();
3095 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3097 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3099 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3100 const char *psz = string( ct ).c_str();
3102 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3106 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3108 chapter_item_t new_sub_chapter;
3109 ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
3110 new_sub_chapter.psz_parent = &chapters;
3111 chapters.sub_chapters.push_back( new_sub_chapter );
3116 /*****************************************************************************
3118 *****************************************************************************/
3119 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
3124 int i_upper_level = 0;
3127 /* Master elements */
3128 m = static_cast<EbmlMaster *>(chapters);
3129 m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3131 for( i = 0; i < m->ListSize(); i++ )
3133 EbmlElement *l = (*m)[i];
3135 if( MKV_IS_ID( l, KaxEditionEntry ) )
3137 chapter_edition_t edition;
3139 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3141 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3142 for( j = 0; j < E->ListSize(); j++ )
3144 EbmlElement *l = (*E)[j];
3146 if( MKV_IS_ID( l, KaxChapterAtom ) )
3148 chapter_item_t new_sub_chapter;
3149 ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3150 edition.sub_chapters.push_back( new_sub_chapter );
3152 else if( MKV_IS_ID( l, KaxEditionUID ) )
3154 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3156 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3158 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3160 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3162 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3163 i_default_edition = stored_editions.size();
3167 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3170 stored_editions.push_back( edition );
3174 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3178 for( i = 0; i < stored_editions.size(); i++ )
3180 stored_editions[i].RefreshChapters( );
3183 if ( stored_editions[i_default_edition].b_ordered )
3185 /* update the duration of the segment according to the sum of all sub chapters */
3186 i_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3192 void matroska_segment_t::ParseCluster( )
3197 int i_upper_level = 0;
3199 /* Master elements */
3200 m = static_cast<EbmlMaster *>( cluster );
3201 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3203 for( i = 0; i < m->ListSize(); i++ )
3205 EbmlElement *l = (*m)[i];
3207 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3209 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3211 cluster->InitTimecode( uint64( ctc ), i_timescale );
3216 i_start_time = cluster->GlobalTimecode() / 1000;
3219 /*****************************************************************************
3220 * InformationCreate:
3221 *****************************************************************************/
3222 void matroska_segment_t::InformationCreate( )
3226 sys.meta = vlc_meta_New();
3230 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3234 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3236 if( psz_segment_filename )
3238 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3240 if( psz_muxing_application )
3242 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3244 if( psz_writing_application )
3246 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3249 for( i_track = 0; i_track < tracks.size(); i_track++ )
3251 mkv_track_t *tk = tracks[i_track];
3252 vlc_meta_t *mtk = vlc_meta_New();
3254 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3255 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3256 sys.meta->track[sys.meta->i_track++] = mtk;
3258 if( tk->fmt.psz_description )
3260 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3262 if( tk->psz_codec_name )
3264 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3266 if( tk->psz_codec_settings )
3268 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3270 if( tk->psz_codec_info_url )
3272 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3274 if( tk->psz_codec_download_url )
3276 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3280 if( i_tags_position >= 0 )
3282 vlc_bool_t b_seekable;
3284 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3293 /*****************************************************************************
3295 *****************************************************************************/
3297 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3299 #define idx index[i_index]
3301 idx.i_block_number= -1;
3302 idx.i_position = cluster->GetElementPosition();
3304 idx.b_key = VLC_TRUE;
3307 if( i_index >= i_index_max )
3309 i_index_max += 1024;
3310 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3315 static char * UTF8ToStr( const UTFstring &u )
3324 p = dst = (char*)malloc( i_src + 1);
3343 void chapter_edition_t::RefreshChapters( )
3345 chapter_item_t::RefreshChapters( b_ordered, -1 );
3346 b_display_seekpoint = false;
3349 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3351 int64_t i_user_time = i_prev_user_time;
3353 // first the sub-chapters, and then ourself
3354 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3355 while ( index != sub_chapters.end() )
3357 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time );
3363 i_user_start_time = i_prev_user_time;
3364 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3366 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3370 i_user_end_time = i_user_time;
3375 std::sort( sub_chapters.begin(), sub_chapters.end() );
3376 i_user_start_time = i_start_time;
3377 if ( i_end_time != -1 )
3378 i_user_end_time = i_end_time;
3379 else if ( i_user_time != -1 )
3380 i_user_end_time = i_user_time;
3382 i_user_end_time = i_user_start_time;
3385 return i_user_end_time;
3388 mtime_t chapter_edition_t::Duration() const
3390 mtime_t i_result = 0;
3392 if ( sub_chapters.size() )
3394 std::vector<chapter_item_t>::const_iterator index = sub_chapters.end();
3396 i_result = (*index).i_user_end_time;
3402 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3404 const chapter_item_t *psz_result = NULL;
3406 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3408 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3409 while ( index != sub_chapters.end() && psz_result == NULL )
3411 psz_result = (*index).FindTimecode( i_user_timecode );
3415 if ( psz_result == NULL )
3422 void demux_sys_t::PreloadFamily( const matroska_segment_t & of_segment )
3424 for (size_t i=0; i<opened_segments.size(); i++)
3426 opened_segments[i]->PreloadFamily( of_segment );
3429 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3434 for (size_t i=0; i<families.size(); i++)
3436 for (size_t j=0; j<of_segment.families.size(); j++)
3438 if ( families[i] == of_segment.families[j] )
3446 // preload all the linked segments for all preloaded segments
3447 void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
3449 size_t i_preloaded, i;
3451 delete p_current_segment;
3452 p_current_segment = new virtual_segment_t( p_segment );
3454 // fill our current virtual segment with all hard linked segments
3457 for ( i=0; i< opened_segments.size(); i++ )
3459 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3461 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3463 p_current_segment->Sort( );
3465 p_current_segment->PreloadLinked( );
3468 bool demux_sys_t::PreparePlayback( )
3470 p_current_segment->LoadCues();
3471 f_duration = p_current_segment->Duration();
3473 /* add information */
3474 p_current_segment->Segment()->InformationCreate( );
3476 p_current_segment->Segment()->Select( 0 );
3478 return p_current_segment->Select( *title );
3481 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3483 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3484 if ( *p_itema == p_item_b->prev_segment_uid )
3487 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3488 if ( *p_itema == p_item_b->segment_uid )
3491 if ( *p_itema == p_item_b->prev_segment_uid )
3497 bool matroska_segment_t::Preload( )
3502 EbmlElement *el = NULL;
3504 ep->Reset( &sys.demuxer );
3506 while( ( el = ep->Get() ) != NULL )
3508 if( MKV_IS_ID( el, KaxInfo ) )
3512 else if( MKV_IS_ID( el, KaxTracks ) )
3516 else if( MKV_IS_ID( el, KaxSeekHead ) )
3518 ParseSeekHead( el );
3520 else if( MKV_IS_ID( el, KaxCues ) )
3522 msg_Dbg( &sys.demuxer, "| + Cues" );
3524 else if( MKV_IS_ID( el, KaxCluster ) )
3526 msg_Dbg( &sys.demuxer, "| + Cluster" );
3528 cluster = (KaxCluster*)el;
3530 i_start_pos = cluster->GetElementPosition();
3534 /* stop parsing the stream */
3537 else if( MKV_IS_ID( el, KaxAttachments ) )
3539 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3541 else if( MKV_IS_ID( el, KaxChapters ) )
3543 msg_Dbg( &sys.demuxer, "| + Chapters" );
3544 ParseChapters( el );
3546 else if( MKV_IS_ID( el, KaxTag ) )
3548 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3552 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3561 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3563 for (size_t i=0; i<opened_segments.size(); i++)
3565 if ( opened_segments[i]->segment_uid == uid )
3566 return opened_segments[i];
3571 void virtual_segment_t::Sort()
3573 // keep the current segment index
3574 matroska_segment_t *p_segment = linked_segments[i_current_segment];
3576 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
3578 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3579 if ( linked_segments[i_current_segment] == p_segment )
3583 size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
3586 // check if it's not already in here
3587 for ( i=0; i<linked_segments.size(); i++ )
3589 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3593 // find possible mates
3594 for ( i=0; i<linked_uids.size(); i++ )
3596 if ( p_segment->segment_uid == linked_uids[i]
3597 || p_segment->prev_segment_uid == linked_uids[i]
3598 || p_segment->next_segment_uid == linked_uids[i] )
3600 linked_segments.push_back( p_segment );
3602 AppendUID( p_segment->prev_segment_uid );
3603 AppendUID( p_segment->next_segment_uid );
3611 void virtual_segment_t::PreloadLinked( )
3613 for ( size_t i=0; i<linked_segments.size(); i++ )
3615 linked_segments[i]->Preload( );
3617 i_current_edition = linked_segments[0]->i_default_edition;
3620 mtime_t virtual_segment_t::Duration() const
3623 if ( linked_segments.size() == 0 )
3626 matroska_segment_t *p_last_segment = linked_segments[linked_segments.size()-1];
3627 // p_last_segment->ParseCluster( );
3629 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3634 void virtual_segment_t::LoadCues( )
3636 for ( size_t i=0; i<linked_segments.size(); i++ )
3638 linked_segments[i]->LoadCues();
3642 void virtual_segment_t::AppendUID( const EbmlBinary & UID )
3644 if ( UID.GetBuffer() == NULL )
3647 for (size_t i=0; i<linked_uids.size(); i++)
3649 if ( UID == linked_uids[i] )
3652 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3655 void matroska_segment_t::Seek( mtime_t i_date, mtime_t i_time_offset )
3658 int i_track_skipping;
3659 int64_t i_block_duration;
3660 int64_t i_block_ref1;
3661 int64_t i_block_ref2;
3663 int64_t i_seek_position = i_start_pos;
3664 int64_t i_seek_time = i_start_time;
3670 for( ; i_idx < i_index; i_idx++ )
3672 if( index[i_idx].i_time + i_time_offset > i_date )
3683 i_seek_position = index[i_idx].i_position;
3684 i_seek_time = index[i_idx].i_time;
3687 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3688 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3690 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3693 ep = new EbmlParser( &es, segment, &sys.demuxer );
3696 sys.i_start_pts = i_date;
3698 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3700 /* now parse until key frame */
3701 #define tk tracks[i_track]
3702 i_track_skipping = 0;
3703 for( i_track = 0; i_track < tracks.size(); i_track++ )
3705 if( tk->fmt.i_cat == VIDEO_ES )
3707 tk->b_search_keyframe = VLC_TRUE;
3710 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3714 while( i_track_skipping > 0 )
3716 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3718 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3723 for( i_track = 0; i_track < tracks.size(); i_track++ )
3725 if( tk->i_number == block->TrackNum() )
3731 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3733 if( i_track < tracks.size() )
3735 if( sys.i_pts >= sys.i_start_pts )
3737 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3738 i_track_skipping = 0;
3740 else if( tk->fmt.i_cat == VIDEO_ES )
3742 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3744 tk->b_search_keyframe = VLC_FALSE;
3747 if( !tk->b_search_keyframe )
3749 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3759 void virtual_segment_t::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter )
3761 demux_sys_t *p_sys = demuxer.p_sys;
3764 // find the actual time for an ordered edition
3765 if ( psz_chapter == NULL )
3767 if ( EditionIsOrdered() )
3769 /* 1st, we need to know in which chapter we are */
3770 psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3774 if ( psz_chapter != NULL )
3776 psz_current_chapter = psz_chapter;
3777 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3778 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3779 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3782 // find the best matching segment
3783 for ( i=0; i<linked_segments.size(); i++ )
3785 if ( i_date < linked_segments[i]->i_start_time )
3792 if ( i_current_segment != i )
3794 linked_segments[i_current_segment]->UnSelect();
3795 linked_segments[i]->Select( i_date );
3796 i_current_segment = i;
3799 linked_segments[i]->Seek( i_date, i_time_offset );