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;
338 ,i_user_start_time(-1)
341 ,b_display_seekpoint(true)
345 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
346 void PublishChapters( input_title_t & title, int i_level );
347 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
348 void Append( const chapter_item_t & edition );
349 chapter_item_t * FindChapter( const chapter_item_t & chapter );
351 int64_t i_start_time, i_end_time;
352 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
353 std::vector<chapter_item_t> sub_chapters;
356 bool b_display_seekpoint;
357 std::string psz_name;
358 chapter_item_t *psz_parent;
360 bool operator<( const chapter_item_t & item ) const
362 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) );
370 class chapter_edition_t : public chapter_item_t
377 void RefreshChapters( );
378 mtime_t Duration() const;
379 void PublishChapters( input_title_t & title );
386 class matroska_segment_t
389 matroska_segment_t( demux_sys_t & demuxer, EbmlStream & estream )
392 ,i_timescale(MKVD_TIMECODESCALE)
396 ,i_chapters_position(-1)
403 ,psz_muxing_application(NULL)
404 ,psz_writing_application(NULL)
405 ,psz_segment_filename(NULL)
408 ,i_default_edition(0)
413 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
416 ~matroska_segment_t()
418 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
420 #define tk tracks[i_track]
421 if( tk->fmt.psz_description )
423 free( tk->fmt.psz_description );
427 free( tk->psz_codec );
429 if( tk->fmt.psz_language )
431 free( tk->fmt.psz_language );
437 if( psz_writing_application )
439 free( psz_writing_application );
441 if( psz_muxing_application )
443 free( psz_muxing_application );
445 if( psz_segment_filename )
447 free( psz_segment_filename );
455 free( psz_date_utc );
467 uint64_t i_timescale;
469 /* duration of the segment */
471 mtime_t i_start_time;
474 std::vector<mkv_track_t*> tracks;
477 int64_t i_cues_position;
478 int64_t i_chapters_position;
479 int64_t i_tags_position;
483 KaxSegmentUID segment_uid;
484 KaxPrevUID prev_segment_uid;
485 KaxNextUID next_segment_uid;
493 char *psz_muxing_application;
494 char *psz_writing_application;
495 char *psz_segment_filename;
499 std::vector<chapter_edition_t> stored_editions;
500 int i_default_edition;
502 std::vector<KaxSegmentFamily> families;
509 bool PreloadFamily( const matroska_segment_t & segment );
510 void ParseInfo( EbmlElement *info );
511 void ParseChapters( EbmlElement *chapters );
512 void ParseSeekHead( EbmlElement *seekhead );
513 void ParseTracks( EbmlElement *tracks );
514 void ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters );
515 void ParseTrackEntry( EbmlMaster *m );
516 void ParseCluster( );
517 void IndexAppendCluster( KaxCluster *cluster );
520 void InformationCreate( );
521 void Seek( mtime_t i_date, mtime_t i_time_offset );
522 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
523 bool Select( mtime_t i_start_time );
525 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
528 // class holding hard-linked segment together in the playback order
529 class virtual_segment_t
532 virtual_segment_t( matroska_segment_t *p_segment )
533 :i_current_segment(0)
534 ,i_current_edition(-1)
535 ,psz_current_chapter(NULL)
537 linked_segments.push_back( p_segment );
539 AppendUID( p_segment->segment_uid );
540 AppendUID( p_segment->prev_segment_uid );
541 AppendUID( p_segment->next_segment_uid );
545 size_t AddSegment( matroska_segment_t *p_segment );
546 void PreloadLinked( );
547 mtime_t Duration( ) const;
549 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter );
551 inline chapter_edition_t *Edition()
553 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
554 return &editions[i_current_edition];
558 inline bool EditionIsOrdered() const
560 return (editions.size() != 0 && i_current_edition >= 0 && editions[i_current_edition].b_ordered);
563 matroska_segment_t * Segment() const
565 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
567 return linked_segments[i_current_segment];
570 inline const chapter_item_t *CurrentChapter() const {
571 return psz_current_chapter;
576 if ( i_current_segment < linked_segments.size()-1 )
584 /* TODO handle/merge chapters here */
585 void UpdateCurrentToChapter( demux_t & demux );
586 bool Select( input_title_t & title );
589 std::vector<matroska_segment_t*> linked_segments;
590 std::vector<KaxSegmentUID> linked_uids;
591 size_t i_current_segment;
593 std::vector<chapter_edition_t> editions;
594 int i_current_edition;
595 const chapter_item_t *psz_current_chapter;
597 void AppendUID( const EbmlBinary & UID );
600 class matroska_stream_t
603 matroska_stream_t( demux_sys_t & demuxer )
618 std::vector<matroska_segment_t*> segments;
626 demux_sys_t( demux_t & demux )
633 ,p_current_segment(NULL)
639 for (size_t i=0; i<streams.size(); i++)
641 for ( size_t i=0; i<opened_segments.size(); i++ )
642 delete opened_segments[i];
650 mtime_t i_chapter_time;
654 input_title_t *title;
656 std::vector<matroska_stream_t*> streams;
657 std::vector<matroska_segment_t*> opened_segments;
658 virtual_segment_t *p_current_segment;
660 /* duration of the stream */
663 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
664 void PreloadFamily( const matroska_segment_t & of_segment );
665 void PreloadLinked( matroska_segment_t *p_segment );
666 bool PreparePlayback( );
667 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
670 static int Demux ( demux_t * );
671 static int Control( demux_t *, int, va_list );
672 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
674 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
676 static char *UTF8ToStr ( const UTFstring &u );
678 /*****************************************************************************
679 * Open: initializes matroska demux structures
680 *****************************************************************************/
681 static int Open( vlc_object_t * p_this )
683 demux_t *p_demux = (demux_t*)p_this;
685 matroska_stream_t *p_stream;
686 matroska_segment_t *p_segment;
688 std::string s_path, s_filename;
689 vlc_stream_io_callback *p_io_callback;
690 EbmlStream *p_io_stream;
692 /* peek the begining */
693 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
695 /* is a valid file */
696 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
697 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
699 /* Set the demux function */
700 p_demux->pf_demux = Demux;
701 p_demux->pf_control = Control;
702 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
704 p_io_callback = new vlc_stream_io_callback( p_demux->s );
705 p_io_stream = new EbmlStream( *p_io_callback );
707 if( p_io_stream == NULL )
709 msg_Err( p_demux, "failed to create EbmlStream" );
710 delete p_io_callback;
715 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
716 if( p_stream == NULL )
718 msg_Err( p_demux, "cannot find KaxSegment" );
721 p_sys->streams.push_back( p_stream );
723 p_stream->p_in = p_io_callback;
724 p_stream->p_es = p_io_stream;
726 for (size_t i=0; i<p_stream->segments.size(); i++)
728 p_stream->segments[i]->Preload();
731 p_segment = p_stream->segments[0];
732 if( p_segment->cluster == NULL )
734 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
737 // reset the stream reading to the first cluster of the segment used
738 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
740 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
741 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
743 // assume it's a regular file
744 // get the directory path
745 s_path = p_demux->psz_path;
746 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
748 s_path = s_path.substr(0,s_path.length()-1);
752 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
754 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
758 struct dirent *p_file_item;
759 DIR *p_src_dir = opendir(s_path.c_str());
761 if (p_src_dir != NULL)
763 while ((p_file_item = (dirent *) readdir(p_src_dir)))
765 if (strlen(p_file_item->d_name) > 4)
767 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
769 if (!s_filename.compare(p_demux->psz_path))
770 continue; // don't reuse the original opened file
772 #if defined(__GNUC__) && (__GNUC__ < 3)
773 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
774 !s_filename.compare("mka", s_filename.length() - 3, 3))
776 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
777 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
780 // test wether this file belongs to the our family
781 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
782 EbmlStream *p_estream = new EbmlStream(*p_file_io);
784 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
785 if ( p_stream == NULL )
787 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
793 p_stream->p_in = p_file_io;
794 p_stream->p_es = p_estream;
795 p_sys->streams.push_back( p_stream );
800 closedir( p_src_dir );
804 p_sys->PreloadFamily( *p_segment );
805 p_sys->PreloadLinked( p_segment );
806 if ( !p_sys->PreparePlayback( ) )
808 msg_Err( p_demux, "cannot use the segment" );
819 /*****************************************************************************
820 * Close: frees unused data
821 *****************************************************************************/
822 static void Close( vlc_object_t *p_this )
824 demux_t *p_demux = (demux_t*)p_this;
825 demux_sys_t *p_sys = p_demux->p_sys;
830 /*****************************************************************************
832 *****************************************************************************/
833 static int Control( demux_t *p_demux, int i_query, va_list args )
835 demux_sys_t *p_sys = p_demux->p_sys;
840 vlc_meta_t **pp_meta;
845 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
846 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
849 case DEMUX_GET_LENGTH:
850 pi64 = (int64_t*)va_arg( args, int64_t * );
851 if( p_sys->f_duration > 0.0 )
853 *pi64 = (int64_t)(p_sys->f_duration * 1000);
858 case DEMUX_GET_POSITION:
859 pf = (double*)va_arg( args, double * );
860 if ( p_sys->f_duration > 0.0 )
861 *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);
864 case DEMUX_SET_POSITION:
865 f = (double)va_arg( args, double );
866 Seek( p_demux, -1, f, NULL );
870 pi64 = (int64_t*)va_arg( args, int64_t * );
871 *pi64 = p_sys->i_pts;
874 case DEMUX_GET_TITLE_INFO:
875 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
877 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
878 int *pi_int = (int*)va_arg( args, int* );
881 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
883 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
889 case DEMUX_SET_TITLE:
890 /* TODO handle editions as titles & DVD titles as well */
891 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
897 case DEMUX_SET_SEEKPOINT:
898 /* FIXME do a better implementation */
899 i_skp = (int)va_arg( args, int );
901 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
903 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
904 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
905 p_demux->info.i_seekpoint = i_skp;
917 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
929 i_level = ep->GetLevel();
931 if( el == NULL && *pp_block != NULL )
933 /* update the index */
934 #define idx index[i_index - 1]
935 if( i_index > 0 && idx.i_time == -1 )
937 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
938 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
946 if( ep->GetLevel() > 1 )
951 msg_Warn( &sys.demuxer, "EOF" );
958 if( MKV_IS_ID( el, KaxCluster ) )
960 cluster = (KaxCluster*)el;
962 /* add it to the index */
964 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
966 IndexAppendCluster( cluster );
969 // reset silent tracks
970 for (size_t i=0; i<tracks.size(); i++)
972 tracks[i]->b_silent = VLC_FALSE;
977 else if( MKV_IS_ID( el, KaxCues ) )
979 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
984 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
987 else if( i_level == 2 )
989 if( MKV_IS_ID( el, KaxClusterTimecode ) )
991 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
993 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
994 cluster->InitTimecode( uint64( ctc ), i_timescale );
996 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1000 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1005 else if( i_level == 3 )
1007 if( MKV_IS_ID( el, KaxBlock ) )
1009 *pp_block = (KaxBlock*)el;
1011 (*pp_block)->ReadData( es.I_O() );
1012 (*pp_block)->SetParent( *cluster );
1016 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1018 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1020 dur.ReadData( es.I_O() );
1021 *pi_duration = uint64( dur );
1023 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1025 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1027 ref.ReadData( es.I_O() );
1028 if( *pi_ref1 == -1 )
1030 *pi_ref1 = int64( ref );
1034 *pi_ref2 = int64( ref );
1037 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1039 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1040 track_num.ReadData( es.I_O() );
1042 for (size_t i=0; i<tracks.size(); i++)
1044 if ( tracks[i]->i_number == uint32(track_num))
1046 tracks[i]->b_silent = VLC_TRUE;
1054 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1055 return VLC_EGENERIC;
1060 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1063 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1064 memcpy( p_block->p_buffer, p_mem, i_mem );
1065 //p_block->i_rate = p_input->stream.control.i_rate;
1069 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1070 mtime_t i_duration )
1072 demux_sys_t *p_sys = p_demux->p_sys;
1073 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1079 #define tk p_segment->tracks[i_track]
1080 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1082 if( tk->i_number == block->TrackNum() )
1088 if( i_track >= p_segment->tracks.size() )
1090 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1093 if( tk->p_es == NULL )
1095 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1098 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1100 return; /* discard audio packets that shouldn't be rendered */
1103 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1106 tk->b_inited = VLC_FALSE;
1110 /* First send init data */
1111 if( !tk->b_inited && tk->i_data_init > 0 )
1115 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1116 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1117 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1119 tk->b_inited = VLC_TRUE;
1122 for( i = 0; i < block->NumberFrames(); i++ )
1125 DataBuffer &data = block->GetBuffer(i);
1127 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1129 if( p_block == NULL )
1134 #if defined(HAVE_ZLIB_H)
1135 if( tk->i_compression_type )
1137 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1141 // TODO implement correct timestamping when B frames are used
1142 if( tk->fmt.i_cat != VIDEO_ES )
1144 p_block->i_dts = p_block->i_pts = i_pts;
1148 p_block->i_dts = i_pts;
1152 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1154 p_block->i_length = i_duration * 1000;
1157 es_out_Send( p_demux->out, tk->p_es, p_block );
1159 /* use time stamp only for first block */
1166 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1168 int i_upper_lvl = 0;
1170 EbmlElement *p_l0, *p_l1, *p_l2;
1171 bool b_keep_stream = false, b_keep_segment;
1173 // verify the EBML Header
1174 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1179 p_l0->SkipData(*p_estream, EbmlHead_Context);
1182 // find all segments in this file
1183 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1189 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1193 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1196 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1197 b_keep_segment = false;
1199 ep = new EbmlParser(p_estream, p_l0, &demuxer );
1200 p_segment1->ep = ep;
1201 p_segment1->segment = (KaxSegment*)p_l0;
1203 while ((p_l1 = ep->Get()))
1205 if (MKV_IS_ID(p_l1, KaxInfo))
1207 // find the families of this segment
1208 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1210 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1211 for( i = 0; i < p_info->ListSize(); i++ )
1213 EbmlElement *l = (*p_info)[i];
1215 if( MKV_IS_ID( l, KaxSegmentUID ) )
1217 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1218 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1219 if ( !b_keep_segment )
1220 break; // this segment is already known
1221 opened_segments.push_back( p_segment1 );
1222 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1224 else if( MKV_IS_ID( l, KaxPrevUID ) )
1226 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1228 else if( MKV_IS_ID( l, KaxNextUID ) )
1230 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1232 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1234 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1235 std::vector<KaxSegmentFamily>::iterator iter;
1236 p_segment1->families.push_back( *p_fam );
1242 if ( b_keep_segment )
1244 b_keep_stream = true;
1245 p_stream1->segments.push_back( p_segment1 );
1251 p_l0->SkipData(*p_estream, EbmlHead_Context);
1252 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1255 if ( !b_keep_stream )
1264 bool matroska_segment_t::Select( mtime_t i_start_time )
1269 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1270 for( i_track = 0; i_track < tracks.size(); i_track++ )
1272 #define tk tracks[i_track]
1273 if( tk->fmt.i_cat == UNKNOWN_ES )
1275 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1280 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1282 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1284 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1285 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1289 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1291 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1292 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1293 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1295 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1296 if( tk->fmt.i_extra > 0 )
1298 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1299 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1303 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1304 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1306 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1308 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1310 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1312 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1314 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1316 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1317 tk->fmt.b_packetized = VLC_FALSE;
1318 tk->fmt.i_extra = tk->i_extra_data;
1319 tk->fmt.p_extra = malloc( tk->i_extra_data );
1320 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1324 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1327 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1329 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1331 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1335 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1340 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1341 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1342 tk->fmt.i_codec = p_box->i_type;
1343 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1344 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1345 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1346 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1347 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1348 MP4_FreeBox_sample_vide( p_box );
1350 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1352 stream_Delete( p_mp4_stream );
1355 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1357 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1359 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1360 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1364 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1366 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1368 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1369 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1370 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1371 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1372 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1374 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1375 if( tk->fmt.i_extra > 0 )
1377 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1378 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1382 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1383 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1384 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1386 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1388 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1390 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1392 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1394 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1396 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1398 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1399 tk->fmt.i_extra = tk->i_extra_data;
1400 tk->fmt.p_extra = malloc( tk->i_extra_data );
1401 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1403 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1405 int i, i_offset = 1, i_size[3], i_extra;
1408 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1410 /* Split the 3 headers */
1411 if( tk->p_extra_data[0] != 0x02 )
1412 msg_Err( &sys.demuxer, "invalid vorbis header" );
1414 for( i = 0; i < 2; i++ )
1417 while( i_offset < tk->i_extra_data )
1419 i_size[i] += tk->p_extra_data[i_offset];
1420 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1424 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1425 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1426 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1428 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1429 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1430 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1431 for( i = 0; i < 3; i++ )
1433 *(p_extra++) = i_size[i] >> 8;
1434 *(p_extra++) = i_size[i] & 0xFF;
1435 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1437 p_extra += i_size[i];
1438 i_extra += i_size[i];
1441 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1442 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1444 int i_profile, i_srate;
1445 static unsigned int i_sample_rates[] =
1447 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1448 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1451 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1452 /* create data for faad (MP4DecSpecificDescrTag)*/
1454 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1458 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1462 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1471 for( i_srate = 0; i_srate < 13; i_srate++ )
1473 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1478 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1480 tk->fmt.i_extra = 2;
1481 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1482 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1483 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1485 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1486 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1487 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1489 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1491 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1495 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1497 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1499 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1501 /* FIXME: support this codec */
1502 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1503 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1505 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1507 /* FIXME: support this codec */
1508 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1509 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1511 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1513 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1514 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1516 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1517 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1518 !strcmp( tk->psz_codec, "S_SSA" ) ||
1519 !strcmp( tk->psz_codec, "S_ASS" ))
1521 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1522 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1524 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1526 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1527 if( tk->i_extra_data )
1530 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1531 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1532 p_buf[tk->i_extra_data] = '\0';
1534 p_start = strstr( p_buf, "size:" );
1535 if( sscanf( p_start, "size: %dx%d",
1536 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1538 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 );
1542 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1547 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1549 /* FIXME: support this codec */
1550 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1551 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1555 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1556 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1560 tk->fmt.i_priority = 1000;
1563 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1565 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1569 sys.i_start_pts = i_start_time;
1570 // reset the stream reading to the first cluster of the segment used
1571 es.I_O().setFilePointer( i_start_pos );
1574 ep = new EbmlParser( &es, segment, &sys.demuxer );
1579 void matroska_segment_t::UnSelect( )
1583 for( i_track = 0; i_track < tracks.size(); i_track++ )
1585 #define tk tracks[i_track]
1586 if ( tk->p_es != NULL )
1588 es_out_Del( sys.demuxer.out, tk->p_es );
1597 bool virtual_segment_t::Select( input_title_t & title )
1599 if ( linked_segments.size() == 0 )
1602 // !!! should be called only once !!!
1603 matroska_segment_t *p_segment;
1606 // copy editions from the first segment
1607 p_segment = linked_segments[0];
1608 editions = p_segment->stored_editions;
1610 for ( i=1 ; i<linked_segments.size(); i++ )
1612 p_segment = linked_segments[i];
1613 // FIXME assume we have the same editions in all segments
1614 for (j=0; j<p_segment->stored_editions.size(); j++)
1615 editions[j].Append( p_segment->stored_editions[j] );
1618 if ( Edition() != NULL )
1619 Edition()->PublishChapters( title );
1624 void chapter_edition_t::PublishChapters( input_title_t & title )
1626 title.i_seekpoint = 0;
1627 if ( title.seekpoint != NULL )
1628 free( title.seekpoint );
1629 chapter_item_t::PublishChapters( title, 0 );
1632 void chapter_item_t::PublishChapters( input_title_t & title, int i_level )
1634 if (b_display_seekpoint)
1636 seekpoint_t *sk = vlc_seekpoint_New();
1638 sk->i_level = i_level;
1639 sk->i_time_offset = i_start_time;
1640 sk->psz_name = strdup( psz_name.c_str() );
1642 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1643 title.i_seekpoint++;
1644 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1645 title.seekpoint[title.i_seekpoint-1] = sk;
1647 i_seekpoint_num = title.i_seekpoint;
1650 for ( size_t i=0; i<sub_chapters.size() ; i++)
1652 sub_chapters[i].PublishChapters( title, i_level+1 );
1656 void virtual_segment_t::UpdateCurrentToChapter( demux_t & demux )
1658 demux_sys_t & sys = *demux.p_sys;
1659 const chapter_item_t *psz_curr_chapter;
1661 /* update current chapter/seekpoint */
1662 if ( editions.size() )
1664 /* 1st, we need to know in which chapter we are */
1665 psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1667 /* we have moved to a new chapter */
1668 if (psz_curr_chapter != NULL && psz_current_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1670 if (psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1672 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1673 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1676 if ( editions[i_current_edition].b_ordered )
1678 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1679 if (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1680 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1681 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1682 /* only seek after each duration >= end timecode of the current chapter */
1685 // i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1686 // i_start_pts = psz_curr_chapter->i_user_start_time;
1688 psz_current_chapter = psz_curr_chapter;
1692 void chapter_item_t::Append( const chapter_item_t & chapter )
1694 // we are appending content for the same chapter UID
1696 chapter_item_t *p_chapter;
1698 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1700 p_chapter = FindChapter( chapter.sub_chapters[i] );
1701 if ( p_chapter != NULL )
1703 p_chapter->Append( chapter.sub_chapters[i] );
1707 sub_chapters.push_back( chapter.sub_chapters[i] );
1711 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1712 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1715 chapter_item_t * chapter_item_t::FindChapter( const chapter_item_t & chapter )
1718 for ( i=0; i<sub_chapters.size(); i++)
1720 if ( sub_chapters[i].i_uid == chapter.i_uid )
1721 return &sub_chapters[i];
1726 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter )
1728 demux_sys_t *p_sys = p_demux->p_sys;
1729 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1730 matroska_segment_t *p_segment = p_vsegment->Segment();
1731 mtime_t i_time_offset = 0;
1735 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1736 if( i_date < 0 && f_percent < 0 )
1738 msg_Warn( p_demux, "cannot seek nowhere !" );
1741 if( f_percent > 1.0 )
1743 msg_Warn( p_demux, "cannot seek so far !" );
1747 /* seek without index or without date */
1748 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1750 if (p_sys->f_duration >= 0)
1752 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1756 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1758 msg_Dbg( p_demux, "inacurate way of seeking" );
1759 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1761 if( p_segment->index[i_index].i_position >= i_pos)
1766 if( i_index == p_segment->i_index )
1771 i_date = p_segment->index[i_index].i_time;
1774 if( p_segment->index[i_index].i_position < i_pos )
1778 msg_Warn( p_demux, "searching for cluster, could take some time" );
1780 /* search a cluster */
1781 while( ( el = p_sys->ep->Get() ) != NULL )
1783 if( MKV_IS_ID( el, KaxCluster ) )
1785 KaxCluster *cluster = (KaxCluster*)el;
1787 /* add it to the index */
1788 p_segment->IndexAppendCluster( cluster );
1790 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1792 p_sys->cluster = cluster;
1803 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1806 /*****************************************************************************
1807 * Demux: reads and demuxes data packets
1808 *****************************************************************************
1809 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1810 *****************************************************************************/
1811 static int Demux( demux_t *p_demux)
1813 demux_sys_t *p_sys = p_demux->p_sys;
1814 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1815 matroska_segment_t *p_segmet = p_vsegment->Segment();
1816 if ( p_segmet == NULL ) return 0;
1817 int i_block_count = 0;
1820 int64_t i_block_duration;
1821 int64_t i_block_ref1;
1822 int64_t i_block_ref2;
1826 if ( p_sys->demuxer.b_die )
1829 if( p_sys->i_pts >= p_sys->i_start_pts )
1830 p_vsegment->UpdateCurrentToChapter( *p_demux );
1832 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1834 /* nothing left to read in this ordered edition */
1835 if ( !p_vsegment->SelectNext() )
1837 p_segmet->UnSelect( );
1839 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1841 /* switch to the next segment */
1842 p_segmet = p_vsegment->Segment();
1843 if ( !p_segmet->Select( 0 ) )
1845 msg_Err( p_demux, "Failed to select new segment" );
1852 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1854 if ( p_vsegment->EditionIsOrdered() )
1856 // check if there are more chapters to read
1857 if ( p_vsegment->CurrentChapter() != NULL )
1859 p_sys->i_pts = p_vsegment->CurrentChapter()->i_user_end_time;
1865 msg_Warn( p_demux, "cannot get block EOF?" );
1866 p_segmet->UnSelect( );
1868 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1870 /* switch to the next segment */
1871 if ( !p_vsegment->SelectNext() )
1872 // no more segments in this stream
1874 p_segmet = p_vsegment->Segment();
1875 if ( !p_segmet->Select( 0 ) )
1877 msg_Err( p_demux, "Failed to select new segment" );
1884 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1886 if( p_sys->i_pts >= p_sys->i_start_pts )
1888 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1891 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1896 // TODO optimize when there is need to leave or when seeking has been called
1897 if( i_block_count > 5 )
1906 /*****************************************************************************
1908 *****************************************************************************/
1909 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1915 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1917 if( i_size <= 0 || mb_eof )
1922 return stream_Read( s, p_buffer, i_size );
1924 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1930 case seek_beginning:
1934 i_pos = stream_Size( s ) - i_offset;
1937 i_pos= stream_Tell( s ) + i_offset;
1941 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1948 if( stream_Seek( s, i_pos ) )
1954 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1958 uint64 vlc_stream_io_callback::getFilePointer( void )
1960 return stream_Tell( s );
1962 void vlc_stream_io_callback::close( void )
1968 /*****************************************************************************
1969 * Ebml Stream parser
1970 *****************************************************************************/
1971 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
1978 mi_remain_size[0] = el_start->GetSize();
1980 for( i = 1; i < 6; i++ )
1986 mb_keep = VLC_FALSE;
1987 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
1990 EbmlParser::~EbmlParser( void )
1994 for( i = 1; i < mi_level; i++ )
2000 mb_keep = VLC_FALSE;
2004 void EbmlParser::Up( void )
2006 if( mi_user_level == mi_level )
2008 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2014 void EbmlParser::Down( void )
2020 void EbmlParser::Keep( void )
2025 int EbmlParser::GetLevel( void )
2027 return mi_user_level;
2030 void EbmlParser::Reset( demux_t *p_demux )
2032 while ( mi_level > 0)
2034 delete m_el[mi_level];
2035 m_el[mi_level] = NULL;
2038 mi_user_level = mi_level = 1;
2039 #if LIBEBML_VERSION >= 0x000704
2040 // a little faster and cleaner
2041 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2043 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2045 mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2048 EbmlElement *EbmlParser::Get( void )
2052 if( mi_user_level != mi_level )
2058 EbmlElement *ret = m_got;
2064 if( m_el[mi_level] )
2066 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2069 delete m_el[mi_level];
2071 mb_keep = VLC_FALSE;
2074 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2075 // mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2086 delete m_el[mi_level - 1];
2087 m_got = m_el[mi_level -1] = m_el[mi_level];
2088 m_el[mi_level] = NULL;
2095 else if( m_el[mi_level] == NULL )
2097 fprintf( stderr," m_el[mi_level] == NULL\n" );
2100 return m_el[mi_level];
2104 /*****************************************************************************
2106 * * LoadCues : load the cues element and update index
2108 * * LoadTags : load ... the tags element
2110 * * InformationCreate : create all information, load tags if present
2112 *****************************************************************************/
2113 void matroska_segment_t::LoadCues( )
2115 int64_t i_sav_position = es.I_O().getFilePointer();
2117 EbmlElement *el, *cues;
2119 /* *** Load the cue if found *** */
2120 if( i_cues_position < 0 )
2122 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2124 // IndexAppendCluster( cluster );
2127 vlc_bool_t b_seekable;
2129 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2133 msg_Dbg( &sys.demuxer, "loading cues" );
2134 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2135 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2139 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2140 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2144 ep = new EbmlParser( &es, cues, &sys.demuxer );
2145 while( ( el = ep->Get() ) != NULL )
2147 if( MKV_IS_ID( el, KaxCuePoint ) )
2149 #define idx index[i_index]
2152 idx.i_block_number= -1;
2153 idx.i_position = -1;
2155 idx.b_key = VLC_TRUE;
2158 while( ( el = ep->Get() ) != NULL )
2160 if( MKV_IS_ID( el, KaxCueTime ) )
2162 KaxCueTime &ctime = *(KaxCueTime*)el;
2164 ctime.ReadData( es.I_O() );
2166 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2168 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2171 while( ( el = ep->Get() ) != NULL )
2173 if( MKV_IS_ID( el, KaxCueTrack ) )
2175 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2177 ctrack.ReadData( es.I_O() );
2178 idx.i_track = uint16( ctrack );
2180 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2182 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2184 ccpos.ReadData( es.I_O() );
2185 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2187 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2189 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2191 cbnum.ReadData( es.I_O() );
2192 idx.i_block_number = uint32( cbnum );
2196 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2203 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2209 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2210 " track=%d bnum=%d", idx.i_time, idx.i_position,
2211 idx.i_track, idx.i_block_number );
2215 if( i_index >= i_index_max )
2217 i_index_max += 1024;
2218 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2224 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2232 msg_Dbg( &sys.demuxer, "loading cues done." );
2233 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2236 void matroska_segment_t::LoadTags( )
2238 int64_t i_sav_position = es.I_O().getFilePointer();
2240 EbmlElement *el, *tags;
2242 msg_Dbg( &sys.demuxer, "loading tags" );
2243 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2244 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2248 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2249 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2253 msg_Dbg( &sys.demuxer, "Tags" );
2254 ep = new EbmlParser( &es, tags, &sys.demuxer );
2255 while( ( el = ep->Get() ) != NULL )
2257 if( MKV_IS_ID( el, KaxTag ) )
2259 msg_Dbg( &sys.demuxer, "+ Tag" );
2261 while( ( el = ep->Get() ) != NULL )
2263 if( MKV_IS_ID( el, KaxTagTargets ) )
2265 msg_Dbg( &sys.demuxer, "| + Targets" );
2267 while( ( el = ep->Get() ) != NULL )
2269 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2273 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2275 msg_Dbg( &sys.demuxer, "| + General" );
2277 while( ( el = ep->Get() ) != NULL )
2279 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2283 else if( MKV_IS_ID( el, KaxTagGenres ) )
2285 msg_Dbg( &sys.demuxer, "| + Genres" );
2287 while( ( el = ep->Get() ) != NULL )
2289 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2293 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2295 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2297 while( ( el = ep->Get() ) != NULL )
2299 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2303 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2305 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2307 while( ( el = ep->Get() ) != NULL )
2309 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2313 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2315 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2317 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2319 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2321 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2323 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2325 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2327 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2329 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2331 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2333 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2335 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2337 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2339 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2343 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2350 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2356 msg_Dbg( &sys.demuxer, "loading tags done." );
2357 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2360 /*****************************************************************************
2362 *****************************************************************************/
2363 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2368 int i_upper_level = 0;
2370 msg_Dbg( &sys.demuxer, "| + Seek head" );
2372 /* Master elements */
2373 m = static_cast<EbmlMaster *>(seekhead);
2374 m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2376 for( i = 0; i < m->ListSize(); i++ )
2378 EbmlElement *l = (*m)[i];
2380 if( MKV_IS_ID( l, KaxSeek ) )
2382 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2383 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2388 for( j = 0; j < sk->ListSize(); j++ )
2390 EbmlElement *l = (*sk)[j];
2392 if( MKV_IS_ID( l, KaxSeekID ) )
2394 KaxSeekID &sid = *(KaxSeekID*)l;
2395 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2397 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2399 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2400 i_pos = uint64( spos );
2404 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2410 if( id == KaxCues::ClassInfos.GlobalId )
2412 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2413 i_cues_position = segment->GetGlobalPosition( i_pos );
2415 else if( id == KaxChapters::ClassInfos.GlobalId )
2417 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2418 i_chapters_position = segment->GetGlobalPosition( i_pos );
2420 else if( id == KaxTags::ClassInfos.GlobalId )
2422 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2423 i_tags_position = segment->GetGlobalPosition( i_pos );
2429 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2434 /*****************************************************************************
2436 *****************************************************************************/
2437 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2443 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2445 tk = new mkv_track_t();
2446 tracks.push_back( tk );
2448 /* Init the track */
2449 memset( tk, 0, sizeof( mkv_track_t ) );
2451 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2452 tk->fmt.psz_language = strdup("English");
2453 tk->fmt.psz_description = NULL;
2455 tk->b_default = VLC_TRUE;
2456 tk->b_enabled = VLC_TRUE;
2457 tk->b_silent = VLC_FALSE;
2458 tk->i_number = tracks.size() - 1;
2459 tk->i_extra_data = 0;
2460 tk->p_extra_data = NULL;
2461 tk->psz_codec = NULL;
2462 tk->i_default_duration = 0;
2463 tk->f_timecodescale = 1.0;
2465 tk->b_inited = VLC_FALSE;
2466 tk->i_data_init = 0;
2467 tk->p_data_init = NULL;
2469 tk->psz_codec_name = NULL;
2470 tk->psz_codec_settings = NULL;
2471 tk->psz_codec_info_url = NULL;
2472 tk->psz_codec_download_url = NULL;
2474 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2476 for( i = 0; i < m->ListSize(); i++ )
2478 EbmlElement *l = (*m)[i];
2480 if( MKV_IS_ID( l, KaxTrackNumber ) )
2482 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2484 tk->i_number = uint32( tnum );
2485 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2487 else if( MKV_IS_ID( l, KaxTrackUID ) )
2489 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2491 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2493 else if( MKV_IS_ID( l, KaxTrackType ) )
2496 KaxTrackType &ttype = *(KaxTrackType*)l;
2498 switch( uint8(ttype) )
2502 tk->fmt.i_cat = AUDIO_ES;
2506 tk->fmt.i_cat = VIDEO_ES;
2508 case track_subtitle:
2509 psz_type = "subtitle";
2510 tk->fmt.i_cat = SPU_ES;
2513 psz_type = "unknown";
2514 tk->fmt.i_cat = UNKNOWN_ES;
2518 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2520 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2522 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2524 // tk->b_enabled = uint32( fenb );
2525 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2526 // uint32( fenb ) );
2528 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2530 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2532 tk->b_default = uint32( fdef );
2533 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2535 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2537 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2539 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2541 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2543 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2545 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2547 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2549 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2551 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2553 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2555 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2557 tk->i_default_duration = uint64(defd);
2558 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2560 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2562 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2564 tk->f_timecodescale = float( ttcs );
2565 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2567 else if( MKV_IS_ID( l, KaxTrackName ) )
2569 KaxTrackName &tname = *(KaxTrackName*)l;
2571 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2572 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2574 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2576 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2578 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2579 msg_Dbg( &sys.demuxer,
2580 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2582 else if( MKV_IS_ID( l, KaxCodecID ) )
2584 KaxCodecID &codecid = *(KaxCodecID*)l;
2586 tk->psz_codec = strdup( string( codecid ).c_str() );
2587 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2589 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2591 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2593 tk->i_extra_data = cpriv.GetSize();
2594 if( tk->i_extra_data > 0 )
2596 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2597 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2599 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2601 else if( MKV_IS_ID( l, KaxCodecName ) )
2603 KaxCodecName &cname = *(KaxCodecName*)l;
2605 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2606 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2608 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2610 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2611 MkvTree( sys.demuxer, 3, "Content Encodings" );
2612 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2614 EbmlElement *l2 = (*cencs)[i];
2615 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2617 MkvTree( sys.demuxer, 4, "Content Encoding" );
2618 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2619 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2621 EbmlElement *l3 = (*cenc)[i];
2622 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2624 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2625 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2627 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2629 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2630 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2632 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2634 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2635 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2637 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2639 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2640 MkvTree( sys.demuxer, 5, "Content Compression" );
2641 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2643 EbmlElement *l4 = (*compr)[i];
2644 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2646 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2647 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2648 if( uint32( compalg ) == 0 )
2650 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2655 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2662 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2669 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2674 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2676 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2678 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2679 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2681 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2683 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2685 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2686 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2688 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2690 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2692 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2693 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2695 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2697 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2699 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2701 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2703 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2705 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2707 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2709 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2712 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2715 for( j = 0; j < tkv->ListSize(); j++ )
2717 EbmlElement *l = (*tkv)[j];
2718 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2720 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2722 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2724 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2726 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2728 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2731 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2733 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2735 tk->fmt.video.i_width = uint16( vwidth );
2736 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2738 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2740 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2742 tk->fmt.video.i_height = uint16( vheight );
2743 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2745 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2747 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2749 tk->fmt.video.i_visible_width = uint16( vwidth );
2750 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2752 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2754 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2756 tk->fmt.video.i_visible_height = uint16( vheight );
2757 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2759 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2761 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2763 tk->f_fps = float( vfps );
2764 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2766 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2768 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2770 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2771 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2773 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2775 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2777 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2779 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2781 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2783 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2787 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2790 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2791 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2793 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2795 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2798 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2800 for( j = 0; j < tka->ListSize(); j++ )
2802 EbmlElement *l = (*tka)[j];
2804 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2806 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2808 tk->fmt.audio.i_rate = (int)float( afreq );
2809 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2811 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2813 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2815 tk->fmt.audio.i_channels = uint8( achan );
2816 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2818 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2820 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2822 tk->fmt.audio.i_bitspersample = uint8( abits );
2823 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2827 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2833 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2834 typeid(*l).name() );
2839 /*****************************************************************************
2841 *****************************************************************************/
2842 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2847 int i_upper_level = 0;
2849 msg_Dbg( &sys.demuxer, "| + Tracks" );
2851 /* Master elements */
2852 m = static_cast<EbmlMaster *>(tracks);
2853 m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2855 for( i = 0; i < m->ListSize(); i++ )
2857 EbmlElement *l = (*m)[i];
2859 if( MKV_IS_ID( l, KaxTrackEntry ) )
2861 ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2865 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2870 /*****************************************************************************
2872 *****************************************************************************/
2873 void matroska_segment_t::ParseInfo( EbmlElement *info )
2878 int i_upper_level = 0;
2880 msg_Dbg( &sys.demuxer, "| + Information" );
2882 /* Master elements */
2883 m = static_cast<EbmlMaster *>(info);
2884 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2886 for( i = 0; i < m->ListSize(); i++ )
2888 EbmlElement *l = (*m)[i];
2890 if( MKV_IS_ID( l, KaxSegmentUID ) )
2892 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2894 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2896 else if( MKV_IS_ID( l, KaxPrevUID ) )
2898 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2900 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2902 else if( MKV_IS_ID( l, KaxNextUID ) )
2904 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2906 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2908 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2910 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2912 i_timescale = uint64(tcs);
2914 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2917 else if( MKV_IS_ID( l, KaxDuration ) )
2919 KaxDuration &dur = *(KaxDuration*)l;
2921 i_duration = mtime_t( double( dur ) );
2923 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
2926 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2928 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2930 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2932 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2933 psz_muxing_application );
2935 else if( MKV_IS_ID( l, KaxWritingApp ) )
2937 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2939 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2941 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2942 psz_writing_application );
2944 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2946 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2948 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2950 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2951 psz_segment_filename );
2953 else if( MKV_IS_ID( l, KaxTitle ) )
2955 KaxTitle &title = *(KaxTitle*)l;
2957 psz_title = UTF8ToStr( UTFstring( title ) );
2959 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2961 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2963 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2965 families.push_back(*uid);
2967 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2969 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2970 else if( MKV_IS_ID( l, KaxDateUTC ) )
2972 KaxDateUTC &date = *(KaxDateUTC*)l;
2977 i_date = date.GetEpochDate();
2978 memset( buffer, 0, 256 );
2979 if( gmtime_r( &i_date, &tmres ) &&
2980 asctime_r( &tmres, buffer ) )
2982 buffer[strlen( buffer)-1]= '\0';
2983 psz_date_utc = strdup( buffer );
2984 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
2990 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2994 double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
2995 i_duration = mtime_t(f_dur);
2999 /*****************************************************************************
3001 *****************************************************************************/
3002 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
3006 if( sys.title == NULL )
3008 sys.title = vlc_input_title_New();
3011 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3012 for( i = 0; i < ca->ListSize(); i++ )
3014 EbmlElement *l = (*ca)[i];
3016 if( MKV_IS_ID( l, KaxChapterUID ) )
3018 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3019 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3021 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3023 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3024 chapters.b_display_seekpoint = uint8( flag ) == 0;
3026 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3028 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3030 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3031 chapters.i_start_time = uint64( start ) / I64C(1000);
3033 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3035 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3037 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3038 chapters.i_end_time = uint64( end ) / I64C(1000);
3040 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3042 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3044 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3047 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3048 for( j = 0; j < cd->ListSize(); j++ )
3050 EbmlElement *l= (*cd)[j];
3052 if( MKV_IS_ID( l, KaxChapterString ) )
3056 KaxChapterString &name =*(KaxChapterString*)l;
3057 for (k = 0; k < i_level; k++)
3058 chapters.psz_name += '+';
3059 chapters.psz_name += ' ';
3060 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3062 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3064 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3066 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3067 const char *psz = string( lang ).c_str();
3069 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3071 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3073 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3074 const char *psz = string( ct ).c_str();
3076 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3080 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3082 chapter_item_t new_sub_chapter;
3083 ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
3084 new_sub_chapter.psz_parent = &chapters;
3085 chapters.sub_chapters.push_back( new_sub_chapter );
3090 /*****************************************************************************
3092 *****************************************************************************/
3093 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
3098 int i_upper_level = 0;
3101 /* Master elements */
3102 m = static_cast<EbmlMaster *>(chapters);
3103 m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3105 for( i = 0; i < m->ListSize(); i++ )
3107 EbmlElement *l = (*m)[i];
3109 if( MKV_IS_ID( l, KaxEditionEntry ) )
3111 chapter_edition_t edition;
3113 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3115 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3116 for( j = 0; j < E->ListSize(); j++ )
3118 EbmlElement *l = (*E)[j];
3120 if( MKV_IS_ID( l, KaxChapterAtom ) )
3122 chapter_item_t new_sub_chapter;
3123 ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3124 edition.sub_chapters.push_back( new_sub_chapter );
3126 else if( MKV_IS_ID( l, KaxEditionUID ) )
3128 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3130 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3132 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3134 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3136 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3137 i_default_edition = stored_editions.size();
3141 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3144 stored_editions.push_back( edition );
3148 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3152 for( i = 0; i < stored_editions.size(); i++ )
3154 stored_editions[i].RefreshChapters( );
3157 if ( stored_editions[i_default_edition].b_ordered )
3159 /* update the duration of the segment according to the sum of all sub chapters */
3160 i_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3166 void matroska_segment_t::ParseCluster( )
3171 int i_upper_level = 0;
3173 /* Master elements */
3174 m = static_cast<EbmlMaster *>( cluster );
3175 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3177 for( i = 0; i < m->ListSize(); i++ )
3179 EbmlElement *l = (*m)[i];
3181 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3183 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3185 cluster->InitTimecode( uint64( ctc ), i_timescale );
3190 i_start_time = cluster->GlobalTimecode() / 1000;
3193 /*****************************************************************************
3194 * InformationCreate:
3195 *****************************************************************************/
3196 void matroska_segment_t::InformationCreate( )
3200 sys.meta = vlc_meta_New();
3204 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3208 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3210 if( psz_segment_filename )
3212 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3214 if( psz_muxing_application )
3216 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3218 if( psz_writing_application )
3220 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3223 for( i_track = 0; i_track < tracks.size(); i_track++ )
3225 mkv_track_t *tk = tracks[i_track];
3226 vlc_meta_t *mtk = vlc_meta_New();
3228 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3229 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3230 sys.meta->track[sys.meta->i_track++] = mtk;
3232 if( tk->fmt.psz_description )
3234 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3236 if( tk->psz_codec_name )
3238 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3240 if( tk->psz_codec_settings )
3242 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3244 if( tk->psz_codec_info_url )
3246 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3248 if( tk->psz_codec_download_url )
3250 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3254 if( i_tags_position >= 0 )
3256 vlc_bool_t b_seekable;
3258 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3267 /*****************************************************************************
3269 *****************************************************************************/
3271 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3273 #define idx index[i_index]
3275 idx.i_block_number= -1;
3276 idx.i_position = cluster->GetElementPosition();
3278 idx.b_key = VLC_TRUE;
3281 if( i_index >= i_index_max )
3283 i_index_max += 1024;
3284 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3289 static char * UTF8ToStr( const UTFstring &u )
3298 p = dst = (char*)malloc( i_src + 1);
3317 void chapter_edition_t::RefreshChapters( )
3319 chapter_item_t::RefreshChapters( b_ordered, -1 );
3320 b_display_seekpoint = false;
3323 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3325 int64_t i_user_time = i_prev_user_time;
3327 // first the sub-chapters, and then ourself
3328 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3329 while ( index != sub_chapters.end() )
3331 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time );
3337 i_user_start_time = i_prev_user_time;
3338 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3340 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3344 i_user_end_time = i_user_time;
3349 std::sort( sub_chapters.begin(), sub_chapters.end() );
3350 i_user_start_time = i_start_time;
3351 if ( i_end_time != -1 )
3352 i_user_end_time = i_end_time;
3353 else if ( i_user_time != -1 )
3354 i_user_end_time = i_user_time;
3356 i_user_end_time = i_user_start_time;
3359 return i_user_end_time;
3362 mtime_t chapter_edition_t::Duration() const
3364 mtime_t i_result = 0;
3366 if ( sub_chapters.size() )
3368 std::vector<chapter_item_t>::const_iterator index = sub_chapters.end();
3370 i_result = (*index).i_user_end_time;
3376 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3378 const chapter_item_t *psz_result = NULL;
3380 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3382 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3383 while ( index != sub_chapters.end() && psz_result == NULL )
3385 psz_result = (*index).FindTimecode( i_user_timecode );
3389 if ( psz_result == NULL )
3396 void demux_sys_t::PreloadFamily( const matroska_segment_t & of_segment )
3398 for (size_t i=0; i<opened_segments.size(); i++)
3400 opened_segments[i]->PreloadFamily( of_segment );
3403 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3408 for (size_t i=0; i<families.size(); i++)
3410 for (size_t j=0; j<of_segment.families.size(); j++)
3412 if ( families[i] == of_segment.families[j] )
3420 // preload all the linked segments for all preloaded segments
3421 void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
3423 size_t i_preloaded, i;
3425 delete p_current_segment;
3426 p_current_segment = new virtual_segment_t( p_segment );
3428 // fill our current virtual segment with all hard linked segments
3431 for ( i=0; i< opened_segments.size(); i++ )
3433 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3435 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3437 p_current_segment->Sort( );
3439 p_current_segment->PreloadLinked( );
3442 bool demux_sys_t::PreparePlayback( )
3444 p_current_segment->LoadCues();
3445 f_duration = p_current_segment->Duration();
3447 /* add information */
3448 p_current_segment->Segment()->InformationCreate( );
3450 p_current_segment->Segment()->Select( 0 );
3452 return p_current_segment->Select( *title );
3455 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3457 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3458 if ( *p_itema == p_item_b->prev_segment_uid )
3461 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3462 if ( *p_itema == p_item_b->segment_uid )
3465 if ( *p_itema == p_item_b->prev_segment_uid )
3471 bool matroska_segment_t::Preload( )
3476 EbmlElement *el = NULL;
3478 ep->Reset( &sys.demuxer );
3480 while( ( el = ep->Get() ) != NULL )
3482 if( MKV_IS_ID( el, KaxInfo ) )
3486 else if( MKV_IS_ID( el, KaxTracks ) )
3490 else if( MKV_IS_ID( el, KaxSeekHead ) )
3492 ParseSeekHead( el );
3494 else if( MKV_IS_ID( el, KaxCues ) )
3496 msg_Dbg( &sys.demuxer, "| + Cues" );
3498 else if( MKV_IS_ID( el, KaxCluster ) )
3500 msg_Dbg( &sys.demuxer, "| + Cluster" );
3502 cluster = (KaxCluster*)el;
3504 i_start_pos = cluster->GetElementPosition();
3508 /* stop parsing the stream */
3511 else if( MKV_IS_ID( el, KaxAttachments ) )
3513 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3515 else if( MKV_IS_ID( el, KaxChapters ) )
3517 msg_Dbg( &sys.demuxer, "| + Chapters" );
3518 ParseChapters( el );
3520 else if( MKV_IS_ID( el, KaxTag ) )
3522 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3526 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3535 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3537 for (size_t i=0; i<opened_segments.size(); i++)
3539 if ( opened_segments[i]->segment_uid == uid )
3540 return opened_segments[i];
3545 void virtual_segment_t::Sort()
3547 // keep the current segment index
3548 matroska_segment_t *p_segment = linked_segments[i_current_segment];
3550 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
3552 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3553 if ( linked_segments[i_current_segment] == p_segment )
3557 size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
3560 // check if it's not already in here
3561 for ( i=0; i<linked_segments.size(); i++ )
3563 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3567 // find possible mates
3568 for ( i=0; i<linked_uids.size(); i++ )
3570 if ( p_segment->segment_uid == linked_uids[i]
3571 || p_segment->prev_segment_uid == linked_uids[i]
3572 || p_segment->next_segment_uid == linked_uids[i] )
3574 linked_segments.push_back( p_segment );
3576 AppendUID( p_segment->prev_segment_uid );
3577 AppendUID( p_segment->next_segment_uid );
3585 void virtual_segment_t::PreloadLinked( )
3587 for ( size_t i=0; i<linked_segments.size(); i++ )
3589 linked_segments[i]->Preload( );
3591 i_current_edition = linked_segments[0]->i_default_edition;
3594 mtime_t virtual_segment_t::Duration() const
3597 if ( linked_segments.size() == 0 )
3600 matroska_segment_t *p_last_segment = linked_segments[linked_segments.size()-1];
3601 // p_last_segment->ParseCluster( );
3603 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3608 void virtual_segment_t::LoadCues( )
3610 for ( size_t i=0; i<linked_segments.size(); i++ )
3612 linked_segments[i]->LoadCues();
3616 void virtual_segment_t::AppendUID( const EbmlBinary & UID )
3618 if ( UID.GetBuffer() == NULL )
3621 for (size_t i=0; i<linked_uids.size(); i++)
3623 if ( UID == linked_uids[i] )
3626 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3629 void matroska_segment_t::Seek( mtime_t i_date, mtime_t i_time_offset )
3632 int i_track_skipping;
3633 int64_t i_block_duration;
3634 int64_t i_block_ref1;
3635 int64_t i_block_ref2;
3637 int64_t i_seek_position = i_start_pos;
3638 int64_t i_seek_time = i_start_time;
3644 for( ; i_idx < i_index; i_idx++ )
3646 if( index[i_idx].i_time + i_time_offset > i_date )
3657 i_seek_position = index[i_idx].i_position;
3658 i_seek_time = index[i_idx].i_time;
3661 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3662 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3664 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3667 ep = new EbmlParser( &es, segment, &sys.demuxer );
3670 sys.i_start_pts = i_date;
3672 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3674 /* now parse until key frame */
3675 #define tk tracks[i_track]
3676 i_track_skipping = 0;
3677 for( i_track = 0; i_track < tracks.size(); i_track++ )
3679 if( tk->fmt.i_cat == VIDEO_ES )
3681 tk->b_search_keyframe = VLC_TRUE;
3684 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3688 while( i_track_skipping > 0 )
3690 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3692 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3697 for( i_track = 0; i_track < tracks.size(); i_track++ )
3699 if( tk->i_number == block->TrackNum() )
3705 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3707 if( i_track < tracks.size() )
3709 if( sys.i_pts >= sys.i_start_pts )
3711 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3712 i_track_skipping = 0;
3714 else if( tk->fmt.i_cat == VIDEO_ES )
3716 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3718 tk->b_search_keyframe = VLC_FALSE;
3721 if( !tk->b_search_keyframe )
3723 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3733 void virtual_segment_t::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter )
3735 demux_sys_t *p_sys = demuxer.p_sys;
3738 // find the actual time for an ordered edition
3739 if ( psz_chapter == NULL )
3741 if ( EditionIsOrdered() )
3743 /* 1st, we need to know in which chapter we are */
3744 psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3748 if ( psz_chapter != NULL )
3750 psz_current_chapter = psz_chapter;
3751 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3752 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3753 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3756 // find the best matching segment
3757 for ( i=0; i<linked_segments.size(); i++ )
3759 if ( i_date < linked_segments[i]->i_start_time )
3766 if ( i_current_segment != i )
3768 linked_segments[i_current_segment]->UnSelect();
3769 linked_segments[i]->Select( i_date );
3770 i_current_segment = i;
3773 linked_segments[i]->Seek( i_date, i_time_offset );