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_shortcut( "mka" );
137 add_shortcut( "mkv" );
140 /*****************************************************************************
142 *****************************************************************************/
144 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
145 int result, dstsize, n;
150 d_stream.zalloc = (alloc_func)0;
151 d_stream.zfree = (free_func)0;
152 d_stream.opaque = (voidpf)0;
153 result = inflateInit(&d_stream);
156 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
160 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
161 d_stream.avail_in = p_in_block->i_buffer;
163 p_block = block_New( p_this, 0 );
168 p_block = block_Realloc( p_block, 0, n * 1000 );
169 dst = (unsigned char *)p_block->p_buffer;
170 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
171 d_stream.avail_out = 1000;
172 result = inflate(&d_stream, Z_NO_FLUSH);
173 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
175 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
179 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
180 ( result != Z_STREAM_END ) );
182 dstsize = d_stream.total_out;
183 inflateEnd( &d_stream );
185 p_block = block_Realloc( p_block, 0, dstsize );
186 p_block->i_buffer = dstsize;
187 block_Release( p_in_block );
194 * Helper function to print the mkv parse tree
196 static void MkvTree( demux_t & demuxer, int i_level, char *psz_format, ... )
201 msg_Err( &demuxer, "too deep tree" );
204 va_start( args, psz_format );
205 static char *psz_foo = "| | | | | | | | | |";
206 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
207 strncpy( psz_foo2, psz_foo, 4 * i_level );
208 psz_foo2[ 4 * i_level ] = '+';
209 psz_foo2[ 4 * i_level + 1 ] = ' ';
210 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
211 __msg_GenericVa( VLC_OBJECT(&demuxer), VLC_MSG_DBG, "mkv", psz_foo2, args );
216 /*****************************************************************************
218 *****************************************************************************/
219 class vlc_stream_io_callback: public IOCallback
226 vlc_stream_io_callback( stream_t * );
228 virtual uint32 read ( void *p_buffer, size_t i_size);
229 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
230 virtual size_t write ( const void *p_buffer, size_t i_size);
231 virtual uint64 getFilePointer ( void );
232 virtual void close ( void );
235 /*****************************************************************************
237 *****************************************************************************/
241 EbmlParser( EbmlStream *es, EbmlElement *el_start );
247 EbmlElement *Get( void );
250 int GetLevel( void );
255 EbmlElement *m_el[10];
264 /*****************************************************************************
265 * Some functions to manipulate memory
266 *****************************************************************************/
267 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
268 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
270 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
273 /*****************************************************************************
274 * definitions of structures and functions used by this plugins
275 *****************************************************************************/
278 vlc_bool_t b_default;
279 vlc_bool_t b_enabled;
280 unsigned int i_number;
283 uint8_t *p_extra_data;
287 uint64_t i_default_duration;
288 float f_timecodescale;
296 /* data to be send first */
298 uint8_t *p_data_init;
300 /* hack : it's for seek */
301 vlc_bool_t b_search_keyframe;
305 char *psz_codec_name;
306 char *psz_codec_settings;
307 char *psz_codec_info_url;
308 char *psz_codec_download_url;
310 /* encryption/compression */
311 int i_compression_type;
332 ,i_user_start_time(-1)
335 ,b_display_seekpoint(true)
339 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time );
340 void PublishChapters( input_title_t & title, int i_level );
341 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
342 void Append( const chapter_item_t & edition );
343 chapter_item_t * FindChapter( const chapter_item_t & chapter );
345 int64_t i_start_time, i_end_time;
346 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
347 std::vector<chapter_item_t> sub_chapters;
350 bool b_display_seekpoint;
351 std::string psz_name;
352 chapter_item_t *psz_parent;
354 bool operator<( const chapter_item_t & item ) const
356 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) );
364 class chapter_edition_t : public chapter_item_t
371 void RefreshChapters( );
372 mtime_t Duration() const;
373 void PublishChapters( input_title_t & title );
380 class matroska_segment_t
383 matroska_segment_t( demux_sys_t & demuxer, EbmlStream & estream )
386 ,i_timescale(MKVD_TIMECODESCALE)
390 ,i_chapters_position(-1)
397 ,psz_muxing_application(NULL)
398 ,psz_writing_application(NULL)
399 ,psz_segment_filename(NULL)
402 ,i_default_edition(0)
407 index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) * i_index_max );
410 ~matroska_segment_t()
412 for( size_t i_track = 0; i_track < tracks.size(); i_track++ )
414 #define tk tracks[i_track]
415 if( tk->fmt.psz_description )
417 free( tk->fmt.psz_description );
421 free( tk->psz_codec );
423 if( tk->fmt.psz_language )
425 free( tk->fmt.psz_language );
431 if( psz_writing_application )
433 free( psz_writing_application );
435 if( psz_muxing_application )
437 free( psz_muxing_application );
439 if( psz_segment_filename )
441 free( psz_segment_filename );
449 free( psz_date_utc );
461 uint64_t i_timescale;
463 /* duration of the segment */
465 mtime_t i_start_time;
468 std::vector<mkv_track_t*> tracks;
471 int64_t i_cues_position;
472 int64_t i_chapters_position;
473 int64_t i_tags_position;
477 KaxSegmentUID segment_uid;
478 KaxPrevUID prev_segment_uid;
479 KaxNextUID next_segment_uid;
487 char *psz_muxing_application;
488 char *psz_writing_application;
489 char *psz_segment_filename;
493 std::vector<chapter_edition_t> stored_editions;
494 int i_default_edition;
496 std::vector<KaxSegmentFamily> families;
503 bool PreloadFamily( const matroska_segment_t & segment );
504 void ParseInfo( EbmlElement *info );
505 void ParseChapters( EbmlElement *chapters );
506 void ParseSeekHead( EbmlElement *seekhead );
507 void ParseTracks( EbmlElement *tracks );
508 void ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters );
509 void ParseTrackEntry( EbmlMaster *m );
510 void ParseCluster( );
511 void IndexAppendCluster( KaxCluster *cluster );
514 void InformationCreate( );
515 void Seek( mtime_t i_date, mtime_t i_time_offset );
516 int BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration );
517 bool Select( mtime_t i_start_time );
519 static bool CompareSegmentUIDs( const matroska_segment_t * item_a, const matroska_segment_t * item_b );
522 // class holding hard-linked segment together in the playback order
523 class virtual_segment_t
526 virtual_segment_t( matroska_segment_t *p_segment )
527 :i_current_segment(0)
528 ,i_current_edition(-1)
529 ,psz_current_chapter(NULL)
531 linked_segments.push_back( p_segment );
533 AppendUID( p_segment->segment_uid );
534 AppendUID( p_segment->prev_segment_uid );
535 AppendUID( p_segment->next_segment_uid );
539 size_t AddSegment( matroska_segment_t *p_segment );
540 void PreloadLinked( );
541 mtime_t Duration( ) const;
543 void Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter );
545 inline chapter_edition_t *Edition()
547 if ( i_current_edition >= 0 && size_t(i_current_edition) < editions.size() )
548 return &editions[i_current_edition];
552 inline bool EditionIsOrdered() const
554 return (editions.size() != 0 && i_current_edition >= 0 && editions[i_current_edition].b_ordered);
557 matroska_segment_t * Segment() const
559 if ( linked_segments.size() == 0 || i_current_segment >= linked_segments.size() )
561 return linked_segments[i_current_segment];
564 inline const chapter_item_t *CurrentChapter() const {
565 return psz_current_chapter;
570 if ( i_current_segment < linked_segments.size()-1 )
578 /* TODO handle/merge chapters here */
579 void UpdateCurrentToChapter( demux_t & demux );
580 bool Select( input_title_t & title );
583 std::vector<matroska_segment_t*> linked_segments;
584 std::vector<KaxSegmentUID> linked_uids;
585 size_t i_current_segment;
587 std::vector<chapter_edition_t> editions;
588 int i_current_edition;
589 const chapter_item_t *psz_current_chapter;
591 void AppendUID( const EbmlBinary & UID );
594 class matroska_stream_t
597 matroska_stream_t( demux_sys_t & demuxer )
612 std::vector<matroska_segment_t*> segments;
616 void PreloadFamily( const matroska_segment_t & segment );
622 demux_sys_t( demux_t & demux )
629 ,p_current_segment(NULL)
635 for (size_t i=0; i<streams.size(); i++)
637 for ( size_t i=0; i<opened_segments.size(); i++ )
638 delete opened_segments[i];
646 mtime_t i_chapter_time;
650 input_title_t *title;
652 std::vector<matroska_stream_t*> streams;
653 std::vector<matroska_segment_t*> opened_segments;
654 virtual_segment_t *p_current_segment;
656 /* duration of the stream */
659 matroska_segment_t *FindSegment( const EbmlBinary & uid ) const;
660 void PreloadFamily( );
661 void PreloadLinked( matroska_segment_t *p_segment );
662 bool PreparePlayback( );
663 matroska_stream_t *AnalyseAllSegmentsFound( EbmlStream *p_estream );
666 static int Demux ( demux_t * );
667 static int Control( demux_t *, int, va_list );
668 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
670 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
672 static char *UTF8ToStr ( const UTFstring &u );
674 /*****************************************************************************
675 * Open: initializes matroska demux structures
676 *****************************************************************************/
677 static int Open( vlc_object_t * p_this )
679 demux_t *p_demux = (demux_t*)p_this;
681 matroska_stream_t *p_stream;
682 matroska_segment_t *p_segment;
684 std::string s_path, s_filename;
685 vlc_stream_io_callback *p_io_callback;
686 EbmlStream *p_io_stream;
688 /* peek the begining */
689 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
691 /* is a valid file */
692 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
693 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
695 /* Set the demux function */
696 p_demux->pf_demux = Demux;
697 p_demux->pf_control = Control;
698 p_demux->p_sys = p_sys = new demux_sys_t( *p_demux );
700 p_io_callback = new vlc_stream_io_callback( p_demux->s );
701 p_io_stream = new EbmlStream( *p_io_callback );
703 if( p_io_stream == NULL )
705 msg_Err( p_demux, "failed to create EbmlStream" );
706 delete p_io_callback;
711 p_stream = p_sys->AnalyseAllSegmentsFound( p_io_stream );
712 if( p_stream == NULL )
714 msg_Err( p_demux, "cannot find KaxSegment" );
717 p_sys->streams.push_back( p_stream );
719 p_stream->p_in = p_io_callback;
720 p_stream->p_es = p_io_stream;
722 for (size_t i=0; i<p_stream->segments.size(); i++)
724 p_stream->segments[i]->Preload();
727 p_segment = p_stream->segments[0];
728 if( p_segment->cluster == NULL )
730 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
733 // reset the stream reading to the first cluster of the segment used
734 p_stream->p_in->setFilePointer( p_segment->cluster->GetElementPosition() );
736 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
737 if (p_demux->psz_path[0] != '\0' && !strcmp(p_demux->psz_access, ""))
739 // assume it's a regular file
740 // get the directory path
741 s_path = p_demux->psz_path;
742 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
744 s_path = s_path.substr(0,s_path.length()-1);
748 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
750 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
754 struct dirent *p_file_item;
755 DIR *p_src_dir = opendir(s_path.c_str());
757 if (p_src_dir != NULL)
759 while ((p_file_item = (dirent *) readdir(p_src_dir)))
761 if (strlen(p_file_item->d_name) > 4)
763 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
765 if (!s_filename.compare(p_demux->psz_path))
766 continue; // don't reuse the original opened file
768 #if defined(__GNUC__) && (__GNUC__ < 3)
769 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
770 !s_filename.compare("mka", s_filename.length() - 3, 3))
772 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
773 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
776 // test wether this file belongs to the our family
777 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
778 EbmlStream *p_estream = new EbmlStream(*p_file_io);
780 p_stream = p_sys->AnalyseAllSegmentsFound( p_estream );
781 if ( p_stream == NULL )
783 msg_Dbg( p_demux, "the file '%s' will not be used", s_filename.c_str() );
789 p_stream->p_in = p_file_io;
790 p_stream->p_es = p_estream;
791 p_sys->streams.push_back( p_stream );
796 closedir( p_src_dir );
800 p_sys->PreloadFamily( );
801 p_sys->PreloadLinked( p_segment );
802 if ( !p_sys->PreparePlayback( ) )
804 msg_Err( p_demux, "cannot use the segment" );
815 /*****************************************************************************
816 * Close: frees unused data
817 *****************************************************************************/
818 static void Close( vlc_object_t *p_this )
820 demux_t *p_demux = (demux_t*)p_this;
821 demux_sys_t *p_sys = p_demux->p_sys;
826 /*****************************************************************************
828 *****************************************************************************/
829 static int Control( demux_t *p_demux, int i_query, va_list args )
831 demux_sys_t *p_sys = p_demux->p_sys;
836 vlc_meta_t **pp_meta;
841 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
842 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
845 case DEMUX_GET_LENGTH:
846 pi64 = (int64_t*)va_arg( args, int64_t * );
847 if( p_sys->f_duration > 0.0 )
849 *pi64 = (int64_t)(p_sys->f_duration * 1000);
854 case DEMUX_GET_POSITION:
855 pf = (double*)va_arg( args, double * );
856 if ( p_sys->f_duration > 0.0 )
857 *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);
860 case DEMUX_SET_POSITION:
861 f = (double)va_arg( args, double );
862 Seek( p_demux, -1, f, NULL );
866 pi64 = (int64_t*)va_arg( args, int64_t * );
867 *pi64 = p_sys->i_pts;
870 case DEMUX_GET_TITLE_INFO:
871 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
873 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
874 int *pi_int = (int*)va_arg( args, int* );
877 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
879 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
885 case DEMUX_SET_TITLE:
886 /* TODO handle editions as titles & DVD titles as well */
887 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
893 case DEMUX_SET_SEEKPOINT:
894 /* FIXME do a better implementation */
895 i_skp = (int)va_arg( args, int );
897 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
899 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
900 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
901 p_demux->info.i_seekpoint = i_skp;
913 int matroska_segment_t::BlockGet( KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
924 if( sys.demuxer.b_die )
930 i_level = ep->GetLevel();
932 if( el == NULL && *pp_block != NULL )
934 /* update the index */
935 #define idx index[i_index - 1]
936 if( i_index > 0 && idx.i_time == -1 )
938 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
939 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
947 if( ep->GetLevel() > 1 )
952 msg_Warn( &sys.demuxer, "EOF" );
959 if( MKV_IS_ID( el, KaxCluster ) )
961 cluster = (KaxCluster*)el;
963 /* add it to the index */
965 ( i_index > 0 && index[i_index - 1].i_position < (int64_t)cluster->GetElementPosition() ) )
967 IndexAppendCluster( cluster );
970 // reset silent tracks
971 for (size_t i=0; i<tracks.size(); i++)
973 tracks[i]->b_silent = VLC_FALSE;
978 else if( MKV_IS_ID( el, KaxCues ) )
980 msg_Warn( &sys.demuxer, "find KaxCues FIXME" );
985 msg_Dbg( &sys.demuxer, "unknown (%s)", typeid( el ).name() );
988 else if( i_level == 2 )
990 if( MKV_IS_ID( el, KaxClusterTimecode ) )
992 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
994 ctc.ReadData( es.I_O(), SCOPE_ALL_DATA );
995 cluster->InitTimecode( uint64( ctc ), i_timescale );
997 else if( MKV_IS_ID( el, KaxClusterSilentTracks ) )
1001 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1006 else if( i_level == 3 )
1008 if( MKV_IS_ID( el, KaxBlock ) )
1010 *pp_block = (KaxBlock*)el;
1012 (*pp_block)->ReadData( es.I_O() );
1013 (*pp_block)->SetParent( *cluster );
1017 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1019 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1021 dur.ReadData( es.I_O() );
1022 *pi_duration = uint64( dur );
1024 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1026 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1028 ref.ReadData( es.I_O() );
1029 if( *pi_ref1 == -1 )
1031 *pi_ref1 = int64( ref );
1035 *pi_ref2 = int64( ref );
1038 else if( MKV_IS_ID( el, KaxClusterSilentTrackNumber ) )
1040 KaxClusterSilentTrackNumber &track_num = *(KaxClusterSilentTrackNumber*)el;
1041 track_num.ReadData( es.I_O() );
1043 for (size_t i=0; i<tracks.size(); i++)
1045 if ( tracks[i]->i_number == uint32(track_num))
1047 tracks[i]->b_silent = VLC_TRUE;
1055 msg_Err( &sys.demuxer, "invalid level = %d", i_level );
1056 return VLC_EGENERIC;
1061 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1064 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1065 memcpy( p_block->p_buffer, p_mem, i_mem );
1066 //p_block->i_rate = p_input->stream.control.i_rate;
1070 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1071 mtime_t i_duration )
1073 demux_sys_t *p_sys = p_demux->p_sys;
1074 matroska_segment_t *p_segment = p_sys->p_current_segment->Segment();
1080 #define tk p_segment->tracks[i_track]
1081 for( i_track = 0; i_track < p_segment->tracks.size(); i_track++ )
1083 if( tk->i_number == block->TrackNum() )
1089 if( i_track >= p_segment->tracks.size() )
1091 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1094 if( tk->p_es == NULL )
1096 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1099 if( i_pts < p_sys->i_start_pts && tk->fmt.i_cat == AUDIO_ES )
1101 return; /* discard audio packets that shouldn't be rendered */
1104 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk->p_es, &b );
1107 tk->b_inited = VLC_FALSE;
1111 /* First send init data */
1112 if( !tk->b_inited && tk->i_data_init > 0 )
1116 msg_Dbg( p_demux, "sending header (%d bytes)", tk->i_data_init );
1117 p_init = MemToBlock( p_demux, tk->p_data_init, tk->i_data_init );
1118 if( p_init ) es_out_Send( p_demux->out, tk->p_es, p_init );
1120 tk->b_inited = VLC_TRUE;
1123 for( i = 0; i < block->NumberFrames(); i++ )
1126 DataBuffer &data = block->GetBuffer(i);
1128 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1130 if( p_block == NULL )
1135 #if defined(HAVE_ZLIB_H)
1136 if( tk->i_compression_type )
1138 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1142 // TODO implement correct timestamping when B frames are used
1143 if( tk->fmt.i_cat != VIDEO_ES )
1145 p_block->i_dts = p_block->i_pts = i_pts;
1149 p_block->i_dts = i_pts;
1153 if( tk->fmt.i_cat == SPU_ES && strcmp( tk->psz_codec, "S_VOBSUB" ) )
1155 p_block->i_length = i_duration * 1000;
1158 es_out_Send( p_demux->out, tk->p_es, p_block );
1160 /* use time stamp only for first block */
1167 matroska_stream_t *demux_sys_t::AnalyseAllSegmentsFound( EbmlStream *p_estream )
1169 int i_upper_lvl = 0;
1171 EbmlElement *p_l0, *p_l1, *p_l2;
1172 bool b_keep_stream = false, b_keep_segment;
1174 // verify the EBML Header
1175 p_l0 = p_estream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
1180 p_l0->SkipData(*p_estream, EbmlHead_Context);
1183 // find all segments in this file
1184 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1190 matroska_stream_t *p_stream1 = new matroska_stream_t( *this );
1194 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
1197 matroska_segment_t *p_segment1 = new matroska_segment_t( *this, *p_estream );
1198 b_keep_segment = false;
1200 ep = new EbmlParser(p_estream, p_l0);
1201 p_segment1->ep = ep;
1202 p_segment1->segment = (KaxSegment*)p_l0;
1204 while ((p_l1 = ep->Get()))
1206 if (MKV_IS_ID(p_l1, KaxInfo))
1208 // find the families of this segment
1209 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
1211 p_info->Read(*p_estream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
1212 for( i = 0; i < p_info->ListSize(); i++ )
1214 EbmlElement *l = (*p_info)[i];
1216 if( MKV_IS_ID( l, KaxSegmentUID ) )
1218 KaxSegmentUID *p_uid = static_cast<KaxSegmentUID*>(l);
1219 b_keep_segment = (FindSegment( *p_uid ) == NULL);
1220 if ( !b_keep_segment )
1221 break; // this segment is already known
1222 opened_segments.push_back( p_segment1 );
1223 p_segment1->segment_uid = *( new KaxSegmentUID(*p_uid) );
1225 else if( MKV_IS_ID( l, KaxPrevUID ) )
1227 p_segment1->prev_segment_uid = *( new KaxPrevUID( *static_cast<KaxPrevUID*>(l) ) );
1229 else if( MKV_IS_ID( l, KaxNextUID ) )
1231 p_segment1->next_segment_uid = *( new KaxNextUID( *static_cast<KaxNextUID*>(l) ) );
1233 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
1235 KaxSegmentFamily *p_fam = new KaxSegmentFamily( *static_cast<KaxSegmentFamily*>(l) );
1236 std::vector<KaxSegmentFamily>::iterator iter;
1237 p_segment1->families.push_back( *p_fam );
1243 if ( b_keep_segment )
1245 b_keep_stream = true;
1246 p_stream1->segments.push_back( p_segment1 );
1252 p_l0->SkipData(*p_estream, EbmlHead_Context);
1253 p_l0 = p_estream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
1256 if ( !b_keep_stream )
1265 bool matroska_segment_t::Select( mtime_t i_start_time )
1270 msg_Dbg( &sys.demuxer, "found %d es", tracks.size() );
1271 for( i_track = 0; i_track < tracks.size(); i_track++ )
1273 #define tk tracks[i_track]
1274 if( tk->fmt.i_cat == UNKNOWN_ES )
1276 msg_Warn( &sys.demuxer, "invalid track[%d, n=%d]", i_track, tk->i_number );
1281 if( !strcmp( tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1283 if( tk->i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
1285 msg_Err( &sys.demuxer, "missing/invalid BITMAPINFOHEADER" );
1286 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1290 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk->p_extra_data;
1292 tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1293 tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1294 tk->fmt.i_codec = GetFOURCC( &p_bih->biCompression );
1296 tk->fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
1297 if( tk->fmt.i_extra > 0 )
1299 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1300 memcpy( tk->fmt.p_extra, &p_bih[1], tk->fmt.i_extra );
1304 else if( !strcmp( tk->psz_codec, "V_MPEG1" ) ||
1305 !strcmp( tk->psz_codec, "V_MPEG2" ) )
1307 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
1309 else if( !strncmp( tk->psz_codec, "V_MPEG4", 7 ) )
1311 if( !strcmp( tk->psz_codec, "V_MPEG4/MS/V3" ) )
1313 tk->fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
1315 else if( !strcmp( tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1317 tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1318 tk->fmt.b_packetized = VLC_FALSE;
1319 tk->fmt.i_extra = tk->i_extra_data;
1320 tk->fmt.p_extra = malloc( tk->i_extra_data );
1321 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1325 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
1328 else if( !strcmp( tk->psz_codec, "V_QUICKTIME" ) )
1330 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
1332 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1336 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1341 MP4_ReadBoxCommon( p_mp4_stream, p_box );
1342 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1343 tk->fmt.i_codec = p_box->i_type;
1344 tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1345 tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1346 tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1347 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1348 memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1349 MP4_FreeBox_sample_vide( p_box );
1351 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1353 stream_Delete( p_mp4_stream );
1356 else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1358 if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1360 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1361 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1365 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1367 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1369 tk->fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
1370 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1371 tk->fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1372 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1373 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1375 tk->fmt.i_extra = GetWLE( &p_wf->cbSize );
1376 if( tk->fmt.i_extra > 0 )
1378 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1379 memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1383 else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1384 !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1385 !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1387 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1389 else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1391 tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1393 else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1395 tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1397 else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1399 tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1400 tk->fmt.i_extra = tk->i_extra_data;
1401 tk->fmt.p_extra = malloc( tk->i_extra_data );
1402 memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1404 else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1406 int i, i_offset = 1, i_size[3], i_extra;
1409 tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1411 /* Split the 3 headers */
1412 if( tk->p_extra_data[0] != 0x02 )
1413 msg_Err( &sys.demuxer, "invalid vorbis header" );
1415 for( i = 0; i < 2; i++ )
1418 while( i_offset < tk->i_extra_data )
1420 i_size[i] += tk->p_extra_data[i_offset];
1421 if( tk->p_extra_data[i_offset++] != 0xff ) break;
1425 i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1426 i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1427 i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1429 tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1430 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1431 p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1432 for( i = 0; i < 3; i++ )
1434 *(p_extra++) = i_size[i] >> 8;
1435 *(p_extra++) = i_size[i] & 0xFF;
1436 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1438 p_extra += i_size[i];
1439 i_extra += i_size[i];
1442 else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1443 !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1445 int i_profile, i_srate;
1446 static unsigned int i_sample_rates[] =
1448 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1449 16000, 12000, 11025, 8000, 7350, 0, 0, 0
1452 tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1453 /* create data for faad (MP4DecSpecificDescrTag)*/
1455 if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1459 else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1463 else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1472 for( i_srate = 0; i_srate < 13; i_srate++ )
1474 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1479 msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1481 tk->fmt.i_extra = 2;
1482 tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1483 ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1484 ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1486 else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1487 !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1488 !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1490 if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1492 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1496 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1498 tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1500 else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1502 /* FIXME: support this codec */
1503 msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1504 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1506 else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1508 /* FIXME: support this codec */
1509 msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1510 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1512 else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1514 tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1515 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1517 else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1518 !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1519 !strcmp( tk->psz_codec, "S_SSA" ) ||
1520 !strcmp( tk->psz_codec, "S_ASS" ))
1522 tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1523 tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1525 else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1527 tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1528 if( tk->i_extra_data )
1531 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1532 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1533 p_buf[tk->i_extra_data] = '\0';
1535 p_start = strstr( p_buf, "size:" );
1536 if( sscanf( p_start, "size: %dx%d",
1537 &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1539 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 );
1543 msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1548 else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1550 /* FIXME: support this codec */
1551 msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1552 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1556 msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1557 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1561 tk->fmt.i_priority = 1000;
1564 tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1566 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1570 sys.i_start_pts = i_start_time;
1573 // reset the stream reading to the first cluster of the segment used
1574 es.I_O().setFilePointer( i_start_pos );
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 );
1595 bool virtual_segment_t::Select( input_title_t & title )
1597 if ( linked_segments.size() == 0 )
1600 // !!! should be called only once !!!
1601 matroska_segment_t *p_segment;
1604 // copy editions from the first segment
1605 p_segment = linked_segments[0];
1606 editions = p_segment->stored_editions;
1608 for ( i=1 ; i<linked_segments.size(); i++ )
1610 p_segment = linked_segments[i];
1611 // FIXME assume we have the same editions in all segments
1612 for (j=0; j<p_segment->stored_editions.size(); j++)
1613 editions[j].Append( p_segment->stored_editions[j] );
1616 Edition()->PublishChapters( title );
1621 void chapter_edition_t::PublishChapters( input_title_t & title )
1623 title.i_seekpoint = 0;
1624 if ( title.seekpoint != NULL )
1625 free( title.seekpoint );
1626 chapter_item_t::PublishChapters( title, 0 );
1629 void chapter_item_t::PublishChapters( input_title_t & title, int i_level )
1631 if (b_display_seekpoint)
1633 seekpoint_t *sk = vlc_seekpoint_New();
1635 sk->i_level = i_level;
1636 sk->i_time_offset = i_start_time;
1637 sk->psz_name = strdup( psz_name.c_str() );
1639 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1640 title.i_seekpoint++;
1641 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1642 title.seekpoint[title.i_seekpoint-1] = sk;
1644 i_seekpoint_num = title.i_seekpoint;
1647 for ( size_t i=0; i<sub_chapters.size() ; i++)
1649 sub_chapters[i].PublishChapters( title, i_level+1 );
1653 void virtual_segment_t::UpdateCurrentToChapter( demux_t & demux )
1655 demux_sys_t & sys = *demux.p_sys;
1656 const chapter_item_t *psz_curr_chapter;
1658 /* update current chapter/seekpoint */
1659 if ( editions.size() )
1661 /* 1st, we need to know in which chapter we are */
1662 psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1664 /* we have moved to a new chapter */
1665 if (psz_curr_chapter != NULL && psz_current_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1667 if (psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1669 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1670 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1673 if ( editions[i_current_edition].b_ordered )
1675 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1676 if (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1677 Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1678 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1679 /* only seek after each duration >= end timecode of the current chapter */
1682 // i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1683 // i_start_pts = psz_curr_chapter->i_user_start_time;
1685 psz_current_chapter = psz_curr_chapter;
1689 void chapter_item_t::Append( const chapter_item_t & chapter )
1691 // we are appending content for the same chapter UID
1693 chapter_item_t *p_chapter;
1695 for ( i=0; i<chapter.sub_chapters.size(); i++ )
1697 p_chapter = FindChapter( chapter.sub_chapters[i] );
1698 if ( p_chapter != NULL )
1700 p_chapter->Append( chapter.sub_chapters[i] );
1704 sub_chapters.push_back( chapter.sub_chapters[i] );
1708 i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1709 i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1712 chapter_item_t * chapter_item_t::FindChapter( const chapter_item_t & chapter )
1715 for ( i=0; i<sub_chapters.size(); i++)
1717 if ( sub_chapters[i].i_uid == chapter.i_uid )
1718 return &sub_chapters[i];
1723 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter )
1725 demux_sys_t *p_sys = p_demux->p_sys;
1726 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1727 matroska_segment_t *p_segment = p_vsegment->Segment();
1728 mtime_t i_time_offset = 0;
1732 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1733 if( i_date < 0 && f_percent < 0 )
1735 msg_Warn( p_demux, "cannot seek nowhere !" );
1738 if( f_percent > 1.0 )
1740 msg_Warn( p_demux, "cannot seek so far !" );
1744 /* seek without index or without date */
1745 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1747 if (p_sys->f_duration >= 0)
1749 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1753 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1755 msg_Dbg( p_demux, "inacurate way of seeking" );
1756 for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1758 if( p_segment->index[i_index].i_position >= i_pos)
1763 if( i_index == p_segment->i_index )
1768 i_date = p_segment->index[i_index].i_time;
1771 if( p_segment->index[i_index].i_position < i_pos )
1775 msg_Warn( p_demux, "searching for cluster, could take some time" );
1777 /* search a cluster */
1778 while( ( el = p_sys->ep->Get() ) != NULL )
1780 if( MKV_IS_ID( el, KaxCluster ) )
1782 KaxCluster *cluster = (KaxCluster*)el;
1784 /* add it to the index */
1785 p_segment->IndexAppendCluster( cluster );
1787 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1789 p_sys->cluster = cluster;
1800 p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1803 /*****************************************************************************
1804 * Demux: reads and demuxes data packets
1805 *****************************************************************************
1806 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1807 *****************************************************************************/
1808 static int Demux( demux_t *p_demux)
1810 demux_sys_t *p_sys = p_demux->p_sys;
1811 virtual_segment_t *p_vsegment = p_sys->p_current_segment;
1812 matroska_segment_t *p_segmet = p_vsegment->Segment();
1813 if ( p_segmet == NULL ) return 0;
1814 int i_block_count = 0;
1817 int64_t i_block_duration;
1818 int64_t i_block_ref1;
1819 int64_t i_block_ref2;
1823 if( p_sys->i_pts >= p_sys->i_start_pts )
1824 p_vsegment->UpdateCurrentToChapter( *p_demux );
1826 if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1828 /* nothing left to read in this ordered edition */
1829 if ( !p_vsegment->SelectNext() )
1831 p_segmet->UnSelect( );
1833 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1835 /* switch to the next segment */
1836 p_segmet = p_vsegment->Segment();
1837 if ( !p_segmet->Select( 0 ) )
1839 msg_Err( p_demux, "Failed to select new segment" );
1845 if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1847 if ( p_sys->demuxer.b_die )
1850 if ( p_vsegment->EditionIsOrdered() )
1852 // check if there are more chapters to read
1853 if ( p_vsegment->CurrentChapter() != NULL )
1855 p_sys->i_pts = p_vsegment->CurrentChapter()->i_user_end_time;
1861 msg_Warn( p_demux, "cannot get block EOF?" );
1862 p_segmet->UnSelect( );
1864 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1866 /* switch to the next segment */
1867 if ( !p_vsegment->SelectNext() )
1868 // no more segments in this stream
1870 p_segmet = p_vsegment->Segment();
1871 if ( !p_segmet->Select( 0 ) )
1873 msg_Err( p_demux, "Failed to select new segment" );
1880 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1882 if( p_sys->i_pts >= p_sys->i_start_pts )
1884 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1887 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1892 // TODO optimize when there is need to leave or when seeking has been called
1893 if( i_block_count > 5 )
1902 /*****************************************************************************
1904 *****************************************************************************/
1905 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1911 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1913 if( i_size <= 0 || mb_eof )
1918 return stream_Read( s, p_buffer, i_size );
1920 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1926 case seek_beginning:
1930 i_pos = stream_Size( s ) - i_offset;
1933 i_pos= stream_Tell( s ) + i_offset;
1937 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1944 if( stream_Seek( s, i_pos ) )
1950 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1954 uint64 vlc_stream_io_callback::getFilePointer( void )
1956 return stream_Tell( s );
1958 void vlc_stream_io_callback::close( void )
1964 /*****************************************************************************
1965 * Ebml Stream parser
1966 *****************************************************************************/
1967 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1975 for( i = 1; i < 6; i++ )
1981 mb_keep = VLC_FALSE;
1984 EbmlParser::~EbmlParser( void )
1988 for( i = 1; i < mi_level; i++ )
1994 mb_keep = VLC_FALSE;
1998 void EbmlParser::Up( void )
2000 if( mi_user_level == mi_level )
2002 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2008 void EbmlParser::Down( void )
2014 void EbmlParser::Keep( void )
2019 int EbmlParser::GetLevel( void )
2021 return mi_user_level;
2024 void EbmlParser::Reset( void )
2026 while ( mi_level > 0)
2028 delete m_el[mi_level];
2029 m_el[mi_level] = NULL;
2032 mi_user_level = mi_level = 1;
2033 #if LIBEBML_VERSION >= 0x000704
2034 // a little faster and cleaner
2035 m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2037 m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2041 EbmlElement *EbmlParser::Get( void )
2045 if( mi_user_level != mi_level )
2051 EbmlElement *ret = m_got;
2057 if( m_el[mi_level] )
2059 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2062 delete m_el[mi_level];
2064 mb_keep = VLC_FALSE;
2067 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
2078 delete m_el[mi_level - 1];
2079 m_got = m_el[mi_level -1] = m_el[mi_level];
2080 m_el[mi_level] = NULL;
2087 else if( m_el[mi_level] == NULL )
2089 fprintf( stderr," m_el[mi_level] == NULL\n" );
2092 return m_el[mi_level];
2096 /*****************************************************************************
2098 * * LoadCues : load the cues element and update index
2100 * * LoadTags : load ... the tags element
2102 * * InformationCreate : create all information, load tags if present
2104 *****************************************************************************/
2105 void matroska_segment_t::LoadCues( )
2107 int64_t i_sav_position = es.I_O().getFilePointer();
2109 EbmlElement *el, *cues;
2111 /* *** Load the cue if found *** */
2112 if( i_cues_position < 0 )
2114 msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2116 // IndexAppendCluster( cluster );
2119 vlc_bool_t b_seekable;
2121 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2125 msg_Dbg( &sys.demuxer, "loading cues" );
2126 es.I_O().setFilePointer( i_cues_position, seek_beginning );
2127 cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2131 msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2132 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2136 ep = new EbmlParser( &es, cues );
2137 while( ( el = ep->Get() ) != NULL )
2139 if( MKV_IS_ID( el, KaxCuePoint ) )
2141 #define idx index[i_index]
2144 idx.i_block_number= -1;
2145 idx.i_position = -1;
2147 idx.b_key = VLC_TRUE;
2150 while( ( el = ep->Get() ) != NULL )
2152 if( MKV_IS_ID( el, KaxCueTime ) )
2154 KaxCueTime &ctime = *(KaxCueTime*)el;
2156 ctime.ReadData( es.I_O() );
2158 idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2160 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2163 while( ( el = ep->Get() ) != NULL )
2165 if( MKV_IS_ID( el, KaxCueTrack ) )
2167 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2169 ctrack.ReadData( es.I_O() );
2170 idx.i_track = uint16( ctrack );
2172 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2174 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2176 ccpos.ReadData( es.I_O() );
2177 idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2179 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2181 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2183 cbnum.ReadData( es.I_O() );
2184 idx.i_block_number = uint32( cbnum );
2188 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2195 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2201 msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2202 " track=%d bnum=%d", idx.i_time, idx.i_position,
2203 idx.i_track, idx.i_block_number );
2207 if( i_index >= i_index_max )
2209 i_index_max += 1024;
2210 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2216 msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2224 msg_Dbg( &sys.demuxer, "loading cues done." );
2225 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2228 void matroska_segment_t::LoadTags( )
2230 int64_t i_sav_position = es.I_O().getFilePointer();
2232 EbmlElement *el, *tags;
2234 msg_Dbg( &sys.demuxer, "loading tags" );
2235 es.I_O().setFilePointer( i_tags_position, seek_beginning );
2236 tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2240 msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2241 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2245 msg_Dbg( &sys.demuxer, "Tags" );
2246 ep = new EbmlParser( &es, tags );
2247 while( ( el = ep->Get() ) != NULL )
2249 if( MKV_IS_ID( el, KaxTag ) )
2251 msg_Dbg( &sys.demuxer, "+ Tag" );
2253 while( ( el = ep->Get() ) != NULL )
2255 if( MKV_IS_ID( el, KaxTagTargets ) )
2257 msg_Dbg( &sys.demuxer, "| + Targets" );
2259 while( ( el = ep->Get() ) != NULL )
2261 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2265 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2267 msg_Dbg( &sys.demuxer, "| + General" );
2269 while( ( el = ep->Get() ) != NULL )
2271 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2275 else if( MKV_IS_ID( el, KaxTagGenres ) )
2277 msg_Dbg( &sys.demuxer, "| + Genres" );
2279 while( ( el = ep->Get() ) != NULL )
2281 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2285 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2287 msg_Dbg( &sys.demuxer, "| + Audio Specific" );
2289 while( ( el = ep->Get() ) != NULL )
2291 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2295 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2297 msg_Dbg( &sys.demuxer, "| + Images Specific" );
2299 while( ( el = ep->Get() ) != NULL )
2301 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid( *el ).name() );
2305 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2307 msg_Dbg( &sys.demuxer, "| + Multi Comment" );
2309 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2311 msg_Dbg( &sys.demuxer, "| + Multi Commercial" );
2313 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2315 msg_Dbg( &sys.demuxer, "| + Multi Date" );
2317 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2319 msg_Dbg( &sys.demuxer, "| + Multi Entity" );
2321 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2323 msg_Dbg( &sys.demuxer, "| + Multi Identifier" );
2325 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2327 msg_Dbg( &sys.demuxer, "| + Multi Legal" );
2329 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2331 msg_Dbg( &sys.demuxer, "| + Multi Title" );
2335 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid( *el ).name() );
2342 msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2348 msg_Dbg( &sys.demuxer, "loading tags done." );
2349 es.I_O().setFilePointer( i_sav_position, seek_beginning );
2352 /*****************************************************************************
2354 *****************************************************************************/
2355 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2360 int i_upper_level = 0;
2362 msg_Dbg( &sys.demuxer, "| + Seek head" );
2364 /* Master elements */
2365 m = static_cast<EbmlMaster *>(seekhead);
2366 m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2368 for( i = 0; i < m->ListSize(); i++ )
2370 EbmlElement *l = (*m)[i];
2372 if( MKV_IS_ID( l, KaxSeek ) )
2374 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2375 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2380 for( j = 0; j < sk->ListSize(); j++ )
2382 EbmlElement *l = (*sk)[j];
2384 if( MKV_IS_ID( l, KaxSeekID ) )
2386 KaxSeekID &sid = *(KaxSeekID*)l;
2387 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2389 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2391 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2392 i_pos = uint64( spos );
2396 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
2402 if( id == KaxCues::ClassInfos.GlobalId )
2404 msg_Dbg( &sys.demuxer, "| | | = cues at "I64Fd, i_pos );
2405 i_cues_position = segment->GetGlobalPosition( i_pos );
2407 else if( id == KaxChapters::ClassInfos.GlobalId )
2409 msg_Dbg( &sys.demuxer, "| | | = chapters at "I64Fd, i_pos );
2410 i_chapters_position = segment->GetGlobalPosition( i_pos );
2412 else if( id == KaxTags::ClassInfos.GlobalId )
2414 msg_Dbg( &sys.demuxer, "| | | = tags at "I64Fd, i_pos );
2415 i_tags_position = segment->GetGlobalPosition( i_pos );
2421 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2426 /*****************************************************************************
2428 *****************************************************************************/
2429 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2435 msg_Dbg( &sys.demuxer, "| | + Track Entry" );
2437 tk = new mkv_track_t();
2438 tracks.push_back( tk );
2440 /* Init the track */
2441 memset( tk, 0, sizeof( mkv_track_t ) );
2443 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2444 tk->fmt.psz_language = strdup("English");
2445 tk->fmt.psz_description = NULL;
2447 tk->b_default = VLC_TRUE;
2448 tk->b_enabled = VLC_TRUE;
2449 tk->b_silent = VLC_FALSE;
2450 tk->i_number = tracks.size() - 1;
2451 tk->i_extra_data = 0;
2452 tk->p_extra_data = NULL;
2453 tk->psz_codec = NULL;
2454 tk->i_default_duration = 0;
2455 tk->f_timecodescale = 1.0;
2457 tk->b_inited = VLC_FALSE;
2458 tk->i_data_init = 0;
2459 tk->p_data_init = NULL;
2461 tk->psz_codec_name = NULL;
2462 tk->psz_codec_settings = NULL;
2463 tk->psz_codec_info_url = NULL;
2464 tk->psz_codec_download_url = NULL;
2466 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2468 for( i = 0; i < m->ListSize(); i++ )
2470 EbmlElement *l = (*m)[i];
2472 if( MKV_IS_ID( l, KaxTrackNumber ) )
2474 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2476 tk->i_number = uint32( tnum );
2477 msg_Dbg( &sys.demuxer, "| | | + Track Number=%u", uint32( tnum ) );
2479 else if( MKV_IS_ID( l, KaxTrackUID ) )
2481 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2483 msg_Dbg( &sys.demuxer, "| | | + Track UID=%u", uint32( tuid ) );
2485 else if( MKV_IS_ID( l, KaxTrackType ) )
2488 KaxTrackType &ttype = *(KaxTrackType*)l;
2490 switch( uint8(ttype) )
2494 tk->fmt.i_cat = AUDIO_ES;
2498 tk->fmt.i_cat = VIDEO_ES;
2500 case track_subtitle:
2501 psz_type = "subtitle";
2502 tk->fmt.i_cat = SPU_ES;
2505 psz_type = "unknown";
2506 tk->fmt.i_cat = UNKNOWN_ES;
2510 msg_Dbg( &sys.demuxer, "| | | + Track Type=%s", psz_type );
2512 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2514 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2516 // tk->b_enabled = uint32( fenb );
2517 // msg_Dbg( &sys.demuxer, "| | | + Track Enabled=%u",
2518 // uint32( fenb ) );
2520 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2522 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2524 tk->b_default = uint32( fdef );
2525 msg_Dbg( &sys.demuxer, "| | | + Track Default=%u", uint32( fdef ) );
2527 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2529 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2531 msg_Dbg( &sys.demuxer, "| | | + Track Lacing=%d", uint32( lac ) );
2533 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2535 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2537 msg_Dbg( &sys.demuxer, "| | | + Track MinCache=%d", uint32( cmin ) );
2539 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2541 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2543 msg_Dbg( &sys.demuxer, "| | | + Track MaxCache=%d", uint32( cmax ) );
2545 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2547 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2549 tk->i_default_duration = uint64(defd);
2550 msg_Dbg( &sys.demuxer, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2552 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2554 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2556 tk->f_timecodescale = float( ttcs );
2557 msg_Dbg( &sys.demuxer, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2559 else if( MKV_IS_ID( l, KaxTrackName ) )
2561 KaxTrackName &tname = *(KaxTrackName*)l;
2563 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2564 msg_Dbg( &sys.demuxer, "| | | + Track Name=%s", tk->fmt.psz_description );
2566 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2568 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2570 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2571 msg_Dbg( &sys.demuxer,
2572 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2574 else if( MKV_IS_ID( l, KaxCodecID ) )
2576 KaxCodecID &codecid = *(KaxCodecID*)l;
2578 tk->psz_codec = strdup( string( codecid ).c_str() );
2579 msg_Dbg( &sys.demuxer, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2581 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2583 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2585 tk->i_extra_data = cpriv.GetSize();
2586 if( tk->i_extra_data > 0 )
2588 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2589 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2591 msg_Dbg( &sys.demuxer, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2593 else if( MKV_IS_ID( l, KaxCodecName ) )
2595 KaxCodecName &cname = *(KaxCodecName*)l;
2597 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2598 msg_Dbg( &sys.demuxer, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2600 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2602 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2603 MkvTree( sys.demuxer, 3, "Content Encodings" );
2604 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2606 EbmlElement *l2 = (*cencs)[i];
2607 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2609 MkvTree( sys.demuxer, 4, "Content Encoding" );
2610 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2611 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2613 EbmlElement *l3 = (*cenc)[i];
2614 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2616 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2617 MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2619 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2621 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2622 MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2624 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2626 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2627 MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2629 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2631 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2632 MkvTree( sys.demuxer, 5, "Content Compression" );
2633 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2635 EbmlElement *l4 = (*compr)[i];
2636 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2638 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2639 MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2640 if( uint32( compalg ) == 0 )
2642 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2647 MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2654 MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2661 MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2666 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2668 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2670 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2671 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2673 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2675 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2677 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2678 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2680 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2682 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2684 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2685 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2687 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2689 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2691 // msg_Dbg( &sys.demuxer, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2693 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2695 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2697 // msg_Dbg( &sys.demuxer, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2699 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2701 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2704 msg_Dbg( &sys.demuxer, "| | | + Track Video" );
2707 for( j = 0; j < tkv->ListSize(); j++ )
2709 EbmlElement *l = (*tkv)[j];
2710 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2712 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2714 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2716 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2718 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2720 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2723 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2725 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2727 tk->fmt.video.i_width = uint16( vwidth );
2728 msg_Dbg( &sys.demuxer, "| | | | + width=%d", uint16( vwidth ) );
2730 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2732 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2734 tk->fmt.video.i_height = uint16( vheight );
2735 msg_Dbg( &sys.demuxer, "| | | | + height=%d", uint16( vheight ) );
2737 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2739 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2741 tk->fmt.video.i_visible_width = uint16( vwidth );
2742 msg_Dbg( &sys.demuxer, "| | | | + display width=%d", uint16( vwidth ) );
2744 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2746 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2748 tk->fmt.video.i_visible_height = uint16( vheight );
2749 msg_Dbg( &sys.demuxer, "| | | | + display height=%d", uint16( vheight ) );
2751 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2753 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2755 tk->f_fps = float( vfps );
2756 msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( vfps ) );
2758 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2760 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2762 // msg_Dbg( &sys.demuxer, "| | | | + Track Video Display Unit=%s",
2763 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2765 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2767 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2769 // msg_Dbg( &sys.demuxer, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2771 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2773 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2775 // msg_Dbg( &sys.demuxer, " | | | + fps=%f", float( gamma ) );
2779 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2782 if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2783 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2785 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2787 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2790 msg_Dbg( &sys.demuxer, "| | | + Track Audio" );
2792 for( j = 0; j < tka->ListSize(); j++ )
2794 EbmlElement *l = (*tka)[j];
2796 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2798 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2800 tk->fmt.audio.i_rate = (int)float( afreq );
2801 msg_Dbg( &sys.demuxer, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2803 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2805 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2807 tk->fmt.audio.i_channels = uint8( achan );
2808 msg_Dbg( &sys.demuxer, "| | | | + achan=%u", uint8( achan ) );
2810 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2812 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2814 tk->fmt.audio.i_bitspersample = uint8( abits );
2815 msg_Dbg( &sys.demuxer, "| | | | + abits=%u", uint8( abits ) );
2819 msg_Dbg( &sys.demuxer, "| | | | + Unknown (%s)", typeid(*l).name() );
2825 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)",
2826 typeid(*l).name() );
2831 /*****************************************************************************
2833 *****************************************************************************/
2834 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2839 int i_upper_level = 0;
2841 msg_Dbg( &sys.demuxer, "| + Tracks" );
2843 /* Master elements */
2844 m = static_cast<EbmlMaster *>(tracks);
2845 m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2847 for( i = 0; i < m->ListSize(); i++ )
2849 EbmlElement *l = (*m)[i];
2851 if( MKV_IS_ID( l, KaxTrackEntry ) )
2853 ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2857 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2862 /*****************************************************************************
2864 *****************************************************************************/
2865 void matroska_segment_t::ParseInfo( EbmlElement *info )
2870 int i_upper_level = 0;
2872 msg_Dbg( &sys.demuxer, "| + Information" );
2874 /* Master elements */
2875 m = static_cast<EbmlMaster *>(info);
2876 m->Read( es, info->Generic().Context, i_upper_level, el, true );
2878 for( i = 0; i < m->ListSize(); i++ )
2880 EbmlElement *l = (*m)[i];
2882 if( MKV_IS_ID( l, KaxSegmentUID ) )
2884 segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2886 msg_Dbg( &sys.demuxer, "| | + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2888 else if( MKV_IS_ID( l, KaxPrevUID ) )
2890 prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2892 msg_Dbg( &sys.demuxer, "| | + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2894 else if( MKV_IS_ID( l, KaxNextUID ) )
2896 next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2898 msg_Dbg( &sys.demuxer, "| | + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2900 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2902 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2904 i_timescale = uint64(tcs);
2906 msg_Dbg( &sys.demuxer, "| | + TimecodeScale="I64Fd,
2909 else if( MKV_IS_ID( l, KaxDuration ) )
2911 KaxDuration &dur = *(KaxDuration*)l;
2913 i_duration = mtime_t( double( dur ) );
2915 msg_Dbg( &sys.demuxer, "| | + Duration="I64Fd,
2918 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2920 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2922 psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2924 msg_Dbg( &sys.demuxer, "| | + Muxing Application=%s",
2925 psz_muxing_application );
2927 else if( MKV_IS_ID( l, KaxWritingApp ) )
2929 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2931 psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2933 msg_Dbg( &sys.demuxer, "| | + Writing Application=%s",
2934 psz_writing_application );
2936 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2938 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2940 psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2942 msg_Dbg( &sys.demuxer, "| | + Segment Filename=%s",
2943 psz_segment_filename );
2945 else if( MKV_IS_ID( l, KaxTitle ) )
2947 KaxTitle &title = *(KaxTitle*)l;
2949 psz_title = UTF8ToStr( UTFstring( title ) );
2951 msg_Dbg( &sys.demuxer, "| | + Title=%s", psz_title );
2953 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2955 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2957 families.push_back(*uid);
2959 msg_Dbg( &sys.demuxer, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2961 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2962 else if( MKV_IS_ID( l, KaxDateUTC ) )
2964 KaxDateUTC &date = *(KaxDateUTC*)l;
2969 i_date = date.GetEpochDate();
2970 memset( buffer, 0, 256 );
2971 if( gmtime_r( &i_date, &tmres ) &&
2972 asctime_r( &tmres, buffer ) )
2974 buffer[strlen( buffer)-1]= '\0';
2975 psz_date_utc = strdup( buffer );
2976 msg_Dbg( &sys.demuxer, "| | + Date=%s", psz_date_utc );
2982 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
2986 i_duration *= i_timescale / 1000000.0;
2990 /*****************************************************************************
2992 *****************************************************************************/
2993 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2997 if( sys.title == NULL )
2999 sys.title = vlc_input_title_New();
3002 msg_Dbg( &sys.demuxer, "| | | + ChapterAtom (level=%d)", i_level );
3003 for( i = 0; i < ca->ListSize(); i++ )
3005 EbmlElement *l = (*ca)[i];
3007 if( MKV_IS_ID( l, KaxChapterUID ) )
3009 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3010 msg_Dbg( &sys.demuxer, "| | | | + ChapterUID: %lld", chapters.i_uid );
3012 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3014 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3015 chapters.b_display_seekpoint = uint8( flag ) == 0;
3017 msg_Dbg( &sys.demuxer, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3019 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3021 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3022 chapters.i_start_time = uint64( start ) / I64C(1000);
3024 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
3026 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3028 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3029 chapters.i_end_time = uint64( end ) / I64C(1000);
3031 msg_Dbg( &sys.demuxer, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
3033 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3035 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3038 msg_Dbg( &sys.demuxer, "| | | | + ChapterDisplay" );
3039 for( j = 0; j < cd->ListSize(); j++ )
3041 EbmlElement *l= (*cd)[j];
3043 if( MKV_IS_ID( l, KaxChapterString ) )
3047 KaxChapterString &name =*(KaxChapterString*)l;
3048 for (k = 0; k < i_level; k++)
3049 chapters.psz_name += '+';
3050 chapters.psz_name += ' ';
3051 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3053 msg_Dbg( &sys.demuxer, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3055 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3057 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3058 const char *psz = string( lang ).c_str();
3060 msg_Dbg( &sys.demuxer, "| | | | | + ChapterLanguage '%s'", psz );
3062 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3064 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3065 const char *psz = string( ct ).c_str();
3067 msg_Dbg( &sys.demuxer, "| | | | | + ChapterCountry '%s'", psz );
3071 else if( MKV_IS_ID( l, KaxChapterAtom ) )
3073 chapter_item_t new_sub_chapter;
3074 ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
3075 new_sub_chapter.psz_parent = &chapters;
3076 chapters.sub_chapters.push_back( new_sub_chapter );
3081 /*****************************************************************************
3083 *****************************************************************************/
3084 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
3089 int i_upper_level = 0;
3092 /* Master elements */
3093 m = static_cast<EbmlMaster *>(chapters);
3094 m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3096 for( i = 0; i < m->ListSize(); i++ )
3098 EbmlElement *l = (*m)[i];
3100 if( MKV_IS_ID( l, KaxEditionEntry ) )
3102 chapter_edition_t edition;
3104 EbmlMaster *E = static_cast<EbmlMaster *>(l );
3106 msg_Dbg( &sys.demuxer, "| | + EditionEntry" );
3107 for( j = 0; j < E->ListSize(); j++ )
3109 EbmlElement *l = (*E)[j];
3111 if( MKV_IS_ID( l, KaxChapterAtom ) )
3113 chapter_item_t new_sub_chapter;
3114 ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3115 edition.sub_chapters.push_back( new_sub_chapter );
3117 else if( MKV_IS_ID( l, KaxEditionUID ) )
3119 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3121 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3123 edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3125 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3127 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3128 i_default_edition = stored_editions.size();
3132 msg_Dbg( &sys.demuxer, "| | | + Unknown (%s)", typeid(*l).name() );
3135 stored_editions.push_back( edition );
3139 msg_Dbg( &sys.demuxer, "| | + Unknown (%s)", typeid(*l).name() );
3143 for( i = 0; i < stored_editions.size(); i++ )
3145 stored_editions[i].RefreshChapters( );
3148 if ( stored_editions[i_default_edition].b_ordered )
3150 /* update the duration of the segment according to the sum of all sub chapters */
3151 i_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3157 void matroska_segment_t::ParseCluster( )
3162 int i_upper_level = 0;
3164 /* Master elements */
3165 m = static_cast<EbmlMaster *>( cluster );
3166 m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3168 for( i = 0; i < m->ListSize(); i++ )
3170 EbmlElement *l = (*m)[i];
3172 if( MKV_IS_ID( l, KaxClusterTimecode ) )
3174 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3176 cluster->InitTimecode( uint64( ctc ), i_timescale );
3181 i_start_time = cluster->GlobalTimecode() / 1000;
3184 /*****************************************************************************
3185 * InformationCreate:
3186 *****************************************************************************/
3187 void matroska_segment_t::InformationCreate( )
3191 sys.meta = vlc_meta_New();
3195 vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3199 vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3201 if( psz_segment_filename )
3203 vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3205 if( psz_muxing_application )
3207 vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3209 if( psz_writing_application )
3211 vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3214 for( i_track = 0; i_track < tracks.size(); i_track++ )
3216 mkv_track_t *tk = tracks[i_track];
3217 vlc_meta_t *mtk = vlc_meta_New();
3219 sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3220 sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3221 sys.meta->track[sys.meta->i_track++] = mtk;
3223 if( tk->fmt.psz_description )
3225 vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3227 if( tk->psz_codec_name )
3229 vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3231 if( tk->psz_codec_settings )
3233 vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3235 if( tk->psz_codec_info_url )
3237 vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3239 if( tk->psz_codec_download_url )
3241 vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3245 if( i_tags_position >= 0 )
3247 vlc_bool_t b_seekable;
3249 stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3258 /*****************************************************************************
3260 *****************************************************************************/
3262 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3264 #define idx index[i_index]
3266 idx.i_block_number= -1;
3267 idx.i_position = cluster->GetElementPosition();
3269 idx.b_key = VLC_TRUE;
3272 if( i_index >= i_index_max )
3274 i_index_max += 1024;
3275 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3280 static char * UTF8ToStr( const UTFstring &u )
3289 p = dst = (char*)malloc( i_src + 1);
3308 void chapter_edition_t::RefreshChapters( )
3310 chapter_item_t::RefreshChapters( b_ordered, -1 );
3311 b_display_seekpoint = false;
3314 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3316 int64_t i_user_time = i_prev_user_time;
3318 // first the sub-chapters, and then ourself
3319 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3320 while ( index != sub_chapters.end() )
3322 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time );
3328 i_user_start_time = i_prev_user_time;
3329 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3331 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3335 i_user_end_time = i_user_time;
3340 std::sort( sub_chapters.begin(), sub_chapters.end() );
3341 i_user_start_time = i_start_time;
3342 if ( i_end_time != -1 )
3343 i_user_end_time = i_end_time;
3344 else if ( i_user_time != -1 )
3345 i_user_end_time = i_user_time;
3347 i_user_end_time = i_user_start_time;
3350 return i_user_end_time;
3353 mtime_t chapter_edition_t::Duration() const
3355 mtime_t i_result = 0.0;
3357 if ( sub_chapters.size() )
3359 std::vector<chapter_item_t>::const_iterator index = sub_chapters.end();
3361 i_result = (*index).i_user_end_time;
3367 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3369 const chapter_item_t *psz_result = NULL;
3371 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3373 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3374 while ( index != sub_chapters.end() && psz_result == NULL )
3376 psz_result = (*index).FindTimecode( i_user_timecode );
3380 if ( psz_result == NULL )
3387 void demux_sys_t::PreloadFamily( )
3389 /* TODO enable family handling again
3390 matroska_stream_t *p_stream = Stream();
3393 matroska_segment_t *p_segment = p_stream->Segment();
3396 for (size_t i=0; i<streams.size(); i++)
3398 streams[i]->PreloadFamily( *p_segment );
3405 void matroska_stream_t::PreloadFamily( const matroska_segment_t & of_segment )
3407 for (size_t i=0; i<segments.size(); i++)
3409 segments[i]->PreloadFamily( of_segment );
3413 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3418 for (size_t i=0; i<families.size(); i++)
3420 for (size_t j=0; j<of_segment.families.size(); j++)
3422 if ( families[i] == of_segment.families[j] )
3430 // preload all the linked segments for all preloaded segments
3431 void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
3433 size_t i_preloaded, i;
3435 delete p_current_segment;
3436 p_current_segment = new virtual_segment_t( p_segment );
3438 // fill our current virtual segment with all hard linked segments
3441 for ( i=0; i< opened_segments.size(); i++ )
3443 i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3445 } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3447 p_current_segment->Sort( );
3449 p_current_segment->PreloadLinked( );
3452 bool demux_sys_t::PreparePlayback( )
3454 p_current_segment->LoadCues();
3455 f_duration = p_current_segment->Duration();
3457 /* add information */
3458 p_current_segment->Segment()->InformationCreate( );
3460 p_current_segment->Segment()->Select( 0 );
3462 return p_current_segment->Select( *title );
3465 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3467 EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3468 if ( *p_itema == p_item_b->prev_segment_uid )
3471 p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3472 if ( *p_itema == p_item_b->segment_uid )
3475 if ( *p_itema == p_item_b->prev_segment_uid )
3481 bool matroska_segment_t::Preload( )
3486 EbmlElement *el = NULL;
3490 while( ( el = ep->Get() ) != NULL )
3492 if( MKV_IS_ID( el, KaxInfo ) )
3496 else if( MKV_IS_ID( el, KaxTracks ) )
3500 else if( MKV_IS_ID( el, KaxSeekHead ) )
3502 ParseSeekHead( el );
3504 else if( MKV_IS_ID( el, KaxCues ) )
3506 msg_Dbg( &sys.demuxer, "| + Cues" );
3508 else if( MKV_IS_ID( el, KaxCluster ) )
3510 msg_Dbg( &sys.demuxer, "| + Cluster" );
3512 cluster = (KaxCluster*)el;
3514 i_start_pos = cluster->GetElementPosition();
3518 /* stop parsing the stream */
3521 else if( MKV_IS_ID( el, KaxAttachments ) )
3523 msg_Dbg( &sys.demuxer, "| + Attachments FIXME TODO (but probably never supported)" );
3525 else if( MKV_IS_ID( el, KaxChapters ) )
3527 msg_Dbg( &sys.demuxer, "| + Chapters" );
3528 ParseChapters( el );
3530 else if( MKV_IS_ID( el, KaxTag ) )
3532 msg_Dbg( &sys.demuxer, "| + Tags FIXME TODO" );
3536 msg_Dbg( &sys.demuxer, "| + Unknown (%s)", typeid(*el).name() );
3545 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3547 for (size_t i=0; i<opened_segments.size(); i++)
3549 if ( opened_segments[i]->segment_uid == uid )
3550 return opened_segments[i];
3555 void virtual_segment_t::Sort()
3557 // keep the current segment index
3558 matroska_segment_t *p_segment = linked_segments[i_current_segment];
3560 std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
3562 for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3563 if ( linked_segments[i_current_segment] == p_segment )
3567 size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
3570 // check if it's not already in here
3571 for ( i=0; i<linked_segments.size(); i++ )
3573 if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3577 // find possible mates
3578 for ( i=0; i<linked_uids.size(); i++ )
3580 if ( p_segment->segment_uid == linked_uids[i]
3581 || p_segment->prev_segment_uid == linked_uids[i]
3582 || p_segment->next_segment_uid == linked_uids[i] )
3584 linked_segments.push_back( p_segment );
3586 AppendUID( p_segment->prev_segment_uid );
3587 AppendUID( p_segment->next_segment_uid );
3595 void virtual_segment_t::PreloadLinked( )
3597 for ( size_t i=0; i<linked_segments.size(); i++ )
3599 linked_segments[i]->Preload( );
3601 i_current_edition = linked_segments[0]->i_default_edition;
3604 mtime_t virtual_segment_t::Duration() const
3607 if ( linked_segments.size() == 0 )
3610 matroska_segment_t *p_last_segment = linked_segments[linked_segments.size()-1];
3611 // p_last_segment->ParseCluster( );
3613 i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
3618 void virtual_segment_t::LoadCues( )
3620 for ( size_t i=0; i<linked_segments.size(); i++ )
3622 linked_segments[i]->LoadCues();
3626 void virtual_segment_t::AppendUID( const EbmlBinary & UID )
3628 if ( UID.GetBuffer() == NULL )
3631 for (size_t i=0; i<linked_uids.size(); i++)
3633 if ( UID == linked_uids[i] )
3636 linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3639 void matroska_segment_t::Seek( mtime_t i_date, mtime_t i_time_offset )
3642 int i_track_skipping;
3643 int64_t i_block_duration;
3644 int64_t i_block_ref1;
3645 int64_t i_block_ref2;
3647 int64_t i_seek_position = i_start_pos;
3648 int64_t i_seek_time = i_start_time;
3654 for( ; i_idx < i_index; i_idx++ )
3656 if( index[i_idx].i_time + i_time_offset > i_date )
3667 i_seek_position = index[i_idx].i_position;
3668 i_seek_time = index[i_idx].i_time;
3671 msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3672 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3675 ep = new EbmlParser( &es, segment );
3678 es.I_O().setFilePointer( i_seek_position, seek_beginning );
3680 sys.i_start_pts = i_date;
3682 es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3684 /* now parse until key frame */
3685 #define tk tracks[i_track]
3686 i_track_skipping = 0;
3687 for( i_track = 0; i_track < tracks.size(); i_track++ )
3689 if( tk->fmt.i_cat == VIDEO_ES )
3691 tk->b_search_keyframe = VLC_TRUE;
3694 es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3698 while( i_track_skipping > 0 )
3700 if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3702 msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3707 for( i_track = 0; i_track < tracks.size(); i_track++ )
3709 if( tk->i_number == block->TrackNum() )
3715 sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3717 if( i_track < tracks.size() )
3719 if( sys.i_pts >= sys.i_start_pts )
3721 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3722 i_track_skipping = 0;
3724 else if( tk->fmt.i_cat == VIDEO_ES )
3726 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3728 tk->b_search_keyframe = VLC_FALSE;
3731 if( !tk->b_search_keyframe )
3733 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3743 void virtual_segment_t::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter )
3745 demux_sys_t *p_sys = demuxer.p_sys;
3748 // find the actual time for an ordered edition
3749 if ( psz_chapter == NULL )
3751 if ( EditionIsOrdered() )
3753 /* 1st, we need to know in which chapter we are */
3754 psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3758 if ( psz_chapter != NULL )
3760 psz_current_chapter = psz_chapter;
3761 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3762 demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3763 demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3766 // find the best matching segment
3767 for ( i=0; i<linked_segments.size(); i++ )
3769 if ( i_date < linked_segments[i]->i_start_time )
3776 if ( i_current_segment != i )
3778 linked_segments[i_current_segment]->UnSelect();
3779 linked_segments[i]->Select( i_date );
3780 i_current_segment = i;
3783 linked_segments[i]->Seek( i_date, i_time_offset );