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 */
51 # include "../../src/extras/dirent.h"
54 /* libebml and matroska */
55 #include "ebml/EbmlHead.h"
56 #include "ebml/EbmlSubHead.h"
57 #include "ebml/EbmlStream.h"
58 #include "ebml/EbmlContexts.h"
59 #include "ebml/EbmlVoid.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
97 * What's between a directory and a filename?
100 #define DIRECTORY_SEPARATOR '\\'
102 #define DIRECTORY_SEPARATOR '/'
105 using namespace LIBMATROSKA_NAMESPACE;
108 /*****************************************************************************
110 *****************************************************************************/
111 static int Open ( vlc_object_t * );
112 static void Close( vlc_object_t * );
115 set_shortname( _("Matroska") );
116 set_description( _("Matroska stream demuxer" ) );
117 set_capability( "demux2", 50 );
118 set_callbacks( Open, Close );
119 set_category( CAT_INPUT );
120 set_subcategory( SUBCAT_INPUT_DEMUX );
122 add_bool( "mkv-seek-percent", 1, NULL,
123 N_("Seek based on percent not time"),
124 N_("Seek based on percent not time"), VLC_TRUE );
126 add_shortcut( "mka" );
127 add_shortcut( "mkv" );
130 /*****************************************************************************
132 *****************************************************************************/
133 static int Demux ( demux_t * );
134 static int Control( demux_t *, int, va_list );
135 static void Seek ( demux_t *, mtime_t i_date, double f_percent );
138 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
139 int result, dstsize, n;
144 d_stream.zalloc = (alloc_func)0;
145 d_stream.zfree = (free_func)0;
146 d_stream.opaque = (voidpf)0;
147 result = inflateInit(&d_stream);
150 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
154 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
155 d_stream.avail_in = p_in_block->i_buffer;
157 p_block = block_New( p_this, 0 );
162 p_block = block_Realloc( p_block, 0, n * 1000 );
163 dst = (unsigned char *)p_block->p_buffer;
164 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
165 d_stream.avail_out = 1000;
166 result = inflate(&d_stream, Z_NO_FLUSH);
167 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
169 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
173 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
174 ( result != Z_STREAM_END ) );
176 dstsize = d_stream.total_out;
177 inflateEnd( &d_stream );
179 p_block = block_Realloc( p_block, 0, dstsize );
180 p_block->i_buffer = dstsize;
181 block_Release( p_in_block );
188 * Helper function to print the mkv parse tree
190 static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )
195 msg_Err( p_this, "too deep tree" );
198 va_start( args, psz_format );
199 static char *psz_foo = "| | | | | | | | | |";
200 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
201 strncpy( psz_foo2, psz_foo, 4 * i_level );
202 psz_foo2[ 4 * i_level ] = '+';
203 psz_foo2[ 4 * i_level + 1 ] = ' ';
204 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
205 __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );
210 /*****************************************************************************
212 *****************************************************************************/
213 class vlc_stream_io_callback: public IOCallback
220 vlc_stream_io_callback( stream_t * );
222 virtual uint32 read ( void *p_buffer, size_t i_size);
223 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
224 virtual size_t write ( const void *p_buffer, size_t i_size);
225 virtual uint64 getFilePointer ( void );
226 virtual void close ( void );
229 /*****************************************************************************
231 *****************************************************************************/
235 EbmlParser( EbmlStream *es, EbmlElement *el_start );
240 EbmlElement *Get( void );
243 int GetLevel( void );
248 EbmlElement *m_el[10];
257 /*****************************************************************************
258 * Some functions to manipulate memory
259 *****************************************************************************/
260 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
261 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
263 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
266 /*****************************************************************************
267 * definitions of structures and functions used by this plugins
268 *****************************************************************************/
271 vlc_bool_t b_default;
272 vlc_bool_t b_enabled;
276 uint8_t *p_extra_data;
280 uint64_t i_default_duration;
281 float f_timecodescale;
289 /* data to be send first */
291 uint8_t *p_data_init;
293 /* hack : it's for seek */
294 vlc_bool_t b_search_keyframe;
297 char *psz_codec_name;
298 char *psz_codec_settings;
299 char *psz_codec_info_url;
300 char *psz_codec_download_url;
302 /* encryption/compression */
303 int i_compression_type;
321 int64_t i_start_time, i_end_time;
322 int64_t i_absolute_start_time; /* the time in the stream when an edition is ordered */
323 std::vector<chapter_item_t> sub_chapters;
324 int i_current_sub_chapter;
328 class chapter_edition_t
336 std::vector<chapter_item_t> chapters;
353 ,i_chapters_position(0)
363 ,psz_muxing_application(NULL)
364 ,psz_writing_application(NULL)
365 ,psz_segment_filename(NULL)
370 ,i_current_edition(0)
373 vlc_stream_io_callback *in;
378 uint64_t i_timescale;
380 /* duration of the segment */
388 int64_t i_cues_position;
389 int64_t i_chapters_position;
390 int64_t i_tags_position;
395 KaxSegmentUID segment_uid;
406 char *psz_muxing_application;
407 char *psz_writing_application;
408 char *psz_segment_filename;
414 input_title_t *title;
416 std::vector<KaxSegmentFamily> families;
417 std::vector<KaxSegment*> family_members;
419 std::vector<chapter_edition_t> editions;
420 int i_current_edition;
423 #define MKVD_TIMECODESCALE 1000000
425 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
427 static void IndexAppendCluster ( demux_t *p_demux, KaxCluster *cluster );
428 static char *UTF8ToStr ( const UTFstring &u );
429 static void LoadCues ( demux_t * );
430 static void InformationCreate ( demux_t * );
432 static void ParseInfo( demux_t *, EbmlElement *info );
433 static void ParseTracks( demux_t *, EbmlElement *tracks );
434 static void ParseSeekHead( demux_t *, EbmlElement *seekhead );
435 static void ParseChapters( demux_t *, EbmlElement *chapters );
437 /*****************************************************************************
438 * Open: initializes matroska demux structures
439 *****************************************************************************/
440 static int Open( vlc_object_t * p_this )
442 demux_t *p_demux = (demux_t*)p_this;
445 std::string s_path, s_filename;
451 EbmlElement *el = NULL, *el1 = NULL;
453 /* peek the begining */
454 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
456 msg_Warn( p_demux, "cannot peek" );
460 /* is a valid file */
461 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
462 p_peek[2] != 0xdf || p_peek[3] != 0xa3 )
464 msg_Warn( p_demux, "matroska module discarded "
465 "(invalid header 0x%.2x%.2x%.2x%.2x)",
466 p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
470 /* Set the demux function */
471 p_demux->pf_demux = Demux;
472 p_demux->pf_control = Control;
473 p_demux->p_sys = p_sys = new demux_sys_t;
475 p_sys->in = new vlc_stream_io_callback( p_demux->s );
476 p_sys->es = new EbmlStream( *p_sys->in );
477 p_sys->f_duration = -1;
478 p_sys->i_timescale = MKVD_TIMECODESCALE;
480 p_sys->track = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
482 p_sys->i_cues_position = -1;
483 p_sys->i_chapters_position = -1;
484 p_sys->i_tags_position = -1;
486 p_sys->b_cues = VLC_FALSE;
488 p_sys->i_index_max = 1024;
489 p_sys->index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *
490 p_sys->i_index_max );
492 p_sys->psz_muxing_application = NULL;
493 p_sys->psz_writing_application = NULL;
494 p_sys->psz_segment_filename = NULL;
495 p_sys->psz_title = NULL;
496 p_sys->psz_date_utc = NULL;;
500 if( p_sys->es == NULL )
502 msg_Err( p_demux, "failed to create EbmlStream" );
507 /* Find the EbmlHead element */
508 el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
511 msg_Err( p_demux, "cannot find EbmlHead" );
514 msg_Dbg( p_demux, "EbmlHead" );
516 el->SkipData( *p_sys->es, el->Generic().Context );
520 el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
523 msg_Err( p_demux, "cannot find KaxSegment" );
526 MkvTree( p_demux, 0, "Segment" );
527 p_sys->segment = (KaxSegment*)el;
528 p_sys->cluster = NULL;
530 p_sys->ep = new EbmlParser( p_sys->es, el );
532 while( ( el1 = p_sys->ep->Get() ) != NULL )
534 if( MKV_IS_ID( el1, KaxInfo ) )
536 ParseInfo( p_demux, el1 );
538 else if( MKV_IS_ID( el1, KaxTracks ) )
540 ParseTracks( p_demux, el1 );
542 else if( MKV_IS_ID( el1, KaxSeekHead ) )
544 ParseSeekHead( p_demux, el1 );
546 else if( MKV_IS_ID( el1, KaxCues ) )
548 msg_Dbg( p_demux, "| + Cues" );
550 else if( MKV_IS_ID( el1, KaxCluster ) )
552 msg_Dbg( p_demux, "| + Cluster" );
554 p_sys->cluster = (KaxCluster*)el1;
557 /* stop parsing the stream */
560 else if( MKV_IS_ID( el1, KaxAttachments ) )
562 msg_Dbg( p_demux, "| + Attachments FIXME TODO (but probably never supported)" );
564 else if( MKV_IS_ID( el1, KaxChapters ) )
566 msg_Dbg( p_demux, "| + Chapters" );
567 ParseChapters( p_demux, el1 );
569 else if( MKV_IS_ID( el1, KaxTag ) )
571 msg_Dbg( p_demux, "| + Tags FIXME TODO" );
575 msg_Dbg( p_demux, "| + Unknown (%s)", typeid(*el1).name() );
579 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
580 /* _todo_ handle multi-segment files */
581 if (p_demux->psz_path[0] != '\0' && (!strcmp(p_demux->psz_access, "") || !strcmp(p_demux->psz_access, "")))
583 // assume it's a regular file
584 // get the directory path
585 s_path = p_demux->psz_path;
586 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
588 s_path = s_path.substr(0,s_path.length()-1);
592 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
594 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
598 struct dirent *p_file_item;
599 DIR *p_src_dir = opendir(s_path.c_str());
601 if (p_src_dir != NULL)
603 while ((p_file_item = readdir(p_src_dir)))
605 if (strlen(p_file_item->d_name) > 4)
607 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
609 if (!s_filename.compare(p_demux->psz_path))
612 #if defined(__GNUC__) && (__GNUC__ < 3)
613 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
614 !s_filename.compare("mka", s_filename.length() - 3, 3))
616 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
617 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
620 // test wether this file belongs to the our family
621 bool b_keep_file_opened = false;
622 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
623 EbmlStream *p_stream = new EbmlStream(*p_file_io);
624 EbmlElement *p_l0, *p_l1, *p_l2;
626 // verify the EBML Header
627 p_l0 = p_stream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
635 p_l0->SkipData(*p_stream, EbmlHead_Context);
638 // find all segments in this file
639 p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
651 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
654 KaxSegmentUID *p_uid = NULL;
656 ep = new EbmlParser(p_stream, p_l0);
657 bool b_this_segment_matches = false;
658 while ((p_l1 = ep->Get()))
660 if (MKV_IS_ID(p_l1, KaxInfo))
662 // find the families of this segment
663 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
665 p_info->Read(*p_stream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
666 for( i = 0; i < p_info->ListSize() && !b_this_segment_matches; i++ )
668 EbmlElement *l = (*p_info)[i];
670 if( MKV_IS_ID( l, KaxSegmentUID ) )
672 p_uid = static_cast<KaxSegmentUID*>(l);
673 if (p_sys->segment_uid == *p_uid)
676 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
678 KaxSegmentFamily *p_fam = static_cast<KaxSegmentFamily*>(l);
679 std::vector<KaxSegmentFamily>::iterator iter;
680 for( iter = p_sys->families.begin();
681 iter != p_sys->families.end();
684 if( *iter == *p_fam )
686 b_this_segment_matches = true;
696 if (b_this_segment_matches)
698 b_keep_file_opened = true;
702 p_l0->SkipData(*p_stream, EbmlHead_Context);
704 p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
707 if (!b_keep_file_opened)
715 closedir( p_src_dir );
720 if( p_sys->cluster == NULL )
722 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
726 /* *** Load the cue if found *** */
727 if( p_sys->i_cues_position >= 0 )
729 vlc_bool_t b_seekable;
731 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
738 if( !p_sys->b_cues || p_sys->i_index <= 0 )
740 msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
742 IndexAppendCluster( p_demux, p_sys->cluster );
744 p_sys->b_cues = VLC_FALSE;
748 msg_Dbg( p_demux, "found %d es", p_sys->i_track );
749 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
751 #define tk p_sys->track[i_track]
752 if( tk.fmt.i_cat == UNKNOWN_ES )
754 msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );
759 if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
761 if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
763 msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );
764 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
768 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
770 tk.fmt.video.i_width = GetDWLE( &p_bih->biWidth );
771 tk.fmt.video.i_height= GetDWLE( &p_bih->biHeight );
772 tk.fmt.i_codec = GetFOURCC( &p_bih->biCompression );
774 tk.fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
775 if( tk.fmt.i_extra > 0 )
777 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
778 memcpy( tk.fmt.p_extra, &p_bih[1], tk.fmt.i_extra );
782 else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||
783 !strcmp( tk.psz_codec, "V_MPEG2" ) )
785 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
787 else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )
789 if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )
791 tk.fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
793 else if( !strcmp( tk.psz_codec, "V_MPEG4/ISO/AVC" ) )
795 tk.fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
796 tk.fmt.b_packetized = VLC_FALSE;
797 tk.fmt.i_extra = tk.i_extra_data;
798 tk.fmt.p_extra = malloc( tk.i_extra_data );
799 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
803 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
806 else if( !strcmp( tk.psz_codec, "V_QUICKTIME" ) )
808 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
809 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),
812 MP4_ReadBoxCommon( p_mp4_stream, p_box );
813 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
814 tk.fmt.i_codec = p_box->i_type;
815 tk.fmt.video.i_width = p_box->data.p_sample_vide->i_width;
816 tk.fmt.video.i_height = p_box->data.p_sample_vide->i_height;
817 tk.fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
818 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
819 memcpy( tk.fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk.fmt.i_extra );
820 MP4_FreeBox_sample_vide( p_box );
821 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
823 else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )
825 if( tk.i_extra_data < (int)sizeof( WAVEFORMATEX ) )
827 msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );
828 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
832 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;
834 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk.fmt.i_codec, NULL );
836 tk.fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
837 tk.fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
838 tk.fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
839 tk.fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
840 tk.fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
842 tk.fmt.i_extra = GetWLE( &p_wf->cbSize );
843 if( tk.fmt.i_extra > 0 )
845 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
846 memcpy( tk.fmt.p_extra, &p_wf[1], tk.fmt.i_extra );
850 else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||
851 !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||
852 !strcmp( tk.psz_codec, "A_MPEG/L1" ) )
854 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
856 else if( !strcmp( tk.psz_codec, "A_AC3" ) )
858 tk.fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
860 else if( !strcmp( tk.psz_codec, "A_DTS" ) )
862 tk.fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
864 else if( !strcmp( tk.psz_codec, "A_FLAC" ) )
866 tk.fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
867 tk.fmt.i_extra = tk.i_extra_data;
868 tk.fmt.p_extra = malloc( tk.i_extra_data );
869 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
871 else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )
873 int i, i_offset = 1, i_size[3], i_extra;
876 tk.fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
878 /* Split the 3 headers */
879 if( tk.p_extra_data[0] != 0x02 )
880 msg_Err( p_demux, "invalid vorbis header" );
882 for( i = 0; i < 2; i++ )
885 while( i_offset < tk.i_extra_data )
887 i_size[i] += tk.p_extra_data[i_offset];
888 if( tk.p_extra_data[i_offset++] != 0xff ) break;
892 i_size[0] = __MIN(i_size[0], tk.i_extra_data - i_offset);
893 i_size[1] = __MIN(i_size[1], tk.i_extra_data -i_offset -i_size[0]);
894 i_size[2] = tk.i_extra_data - i_offset - i_size[0] - i_size[1];
896 tk.fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
897 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
898 p_extra = (uint8_t *)tk.fmt.p_extra; i_extra = 0;
899 for( i = 0; i < 3; i++ )
901 *(p_extra++) = i_size[i] >> 8;
902 *(p_extra++) = i_size[i] & 0xFF;
903 memcpy( p_extra, tk.p_extra_data + i_offset + i_extra,
905 p_extra += i_size[i];
906 i_extra += i_size[i];
909 else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
910 !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
912 int i_profile, i_srate;
913 static unsigned int i_sample_rates[] =
915 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
916 16000, 12000, 11025, 8000, 7350, 0, 0, 0
919 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
920 /* create data for faad (MP4DecSpecificDescrTag)*/
922 if( !strcmp( &tk.psz_codec[12], "MAIN" ) )
926 else if( !strcmp( &tk.psz_codec[12], "LC" ) )
930 else if( !strcmp( &tk.psz_codec[12], "SSR" ) )
939 for( i_srate = 0; i_srate < 13; i_srate++ )
941 if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )
946 msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );
949 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
950 ((uint8_t*)tk.fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
951 ((uint8_t*)tk.fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk.fmt.audio.i_channels << 3);
953 else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||
954 !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||
955 !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )
957 if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )
959 tk.fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
963 tk.fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
965 tk.fmt.audio.i_blockalign = ( tk.fmt.audio.i_bitspersample + 7 ) / 8 * tk.fmt.audio.i_channels;
967 else if( !strcmp( tk.psz_codec, "A_TTA1" ) )
969 /* FIXME: support this codec */
970 msg_Err( p_demux, "TTA not supported yet[%d, n=%d]", i_track, tk.i_number );
971 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
973 else if( !strcmp( tk.psz_codec, "A_WAVPACK4" ) )
975 /* FIXME: support this codec */
976 msg_Err( p_demux, "Wavpack not supported yet[%d, n=%d]", i_track, tk.i_number );
977 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
979 else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )
981 tk.fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
982 tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
984 else if( !strcmp( tk.psz_codec, "S_TEXT/SSA" ) ||
985 !strcmp( tk.psz_codec, "S_TEXT/ASS" ) ||
986 !strcmp( tk.psz_codec, "S_SSA" ) ||
987 !strcmp( tk.psz_codec, "S_ASS" ))
989 tk.fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
990 tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
992 else if( !strcmp( tk.psz_codec, "S_VOBSUB" ) )
994 tk.fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
995 if( tk.i_extra_data )
998 char *p_buf = (char *)malloc( tk.i_extra_data + 1);
999 memcpy( p_buf, tk.p_extra_data , tk.i_extra_data );
1000 p_buf[tk.i_extra_data] = '\0';
1002 p_start = strstr( p_buf, "size:" );
1003 if( sscanf( p_start, "size: %dx%d",
1004 &tk.fmt.subs.spu.i_original_frame_width, &tk.fmt.subs.spu.i_original_frame_height ) == 2 )
1006 msg_Dbg( p_demux, "original frame size vobsubs: %dx%d", tk.fmt.subs.spu.i_original_frame_width, tk.fmt.subs.spu.i_original_frame_height );
1010 msg_Warn( p_demux, "reading original frame size for vobsub failed" );
1015 else if( !strcmp( tk.psz_codec, "B_VOBBTN" ) )
1017 /* FIXME: support this codec */
1018 msg_Err( p_demux, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk.i_number );
1019 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1023 msg_Err( p_demux, "unknow codec id=`%s'", tk.psz_codec );
1024 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1028 tk.fmt.i_priority = 1000;
1031 tk.p_es = es_out_Add( p_demux->out, &tk.fmt );
1035 /* add information */
1036 InformationCreate( p_demux );
1044 return VLC_EGENERIC;
1047 /*****************************************************************************
1048 * Close: frees unused data
1049 *****************************************************************************/
1050 static void Close( vlc_object_t *p_this )
1052 demux_t *p_demux = (demux_t*)p_this;
1053 demux_sys_t *p_sys = p_demux->p_sys;
1056 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1058 #define tk p_sys->track[i_track]
1059 if( tk.fmt.psz_description )
1061 free( tk.fmt.psz_description );
1065 free( tk.psz_codec );
1067 if( tk.fmt.psz_language )
1069 free( tk.fmt.psz_language );
1073 free( p_sys->track );
1075 if( p_sys->psz_writing_application )
1077 free( p_sys->psz_writing_application );
1079 if( p_sys->psz_muxing_application )
1081 free( p_sys->psz_muxing_application );
1084 delete p_sys->segment;
1092 /*****************************************************************************
1094 *****************************************************************************/
1095 static int Control( demux_t *p_demux, int i_query, va_list args )
1097 demux_sys_t *p_sys = p_demux->p_sys;
1102 vlc_meta_t **pp_meta;
1106 case DEMUX_GET_META:
1107 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1108 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1111 case DEMUX_GET_LENGTH:
1112 pi64 = (int64_t*)va_arg( args, int64_t * );
1113 if( p_sys->f_duration > 0.0 )
1115 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1118 return VLC_EGENERIC;
1120 case DEMUX_GET_POSITION:
1121 pf = (double*)va_arg( args, double * );
1122 /* if (p_sys->i_pts < p_sys->i_start_pts)
1123 *pf = (double)p_sys->i_start_pts / (1000.0 * p_sys->f_duration);
1125 *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
1128 case DEMUX_SET_POSITION:
1129 f = (double)va_arg( args, double );
1130 Seek( p_demux, -1, f );
1133 case DEMUX_GET_TIME:
1134 pi64 = (int64_t*)va_arg( args, int64_t * );
1135 /* if (p_sys->i_pts < p_sys->i_start_pts)
1136 *pi64 = p_sys->i_start_pts;
1138 *pi64 = p_sys->i_pts;
1141 case DEMUX_GET_TITLE_INFO:
1142 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1144 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1145 int *pi_int = (int*)va_arg( args, int* );
1148 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1150 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1154 return VLC_EGENERIC;
1156 case DEMUX_SET_TITLE:
1157 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1161 return VLC_EGENERIC;
1163 case DEMUX_SET_SEEKPOINT:
1164 /* FIXME do a better implementation */
1165 i_skp = (int)va_arg( args, int );
1167 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1169 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1);
1170 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1171 p_demux->info.i_seekpoint = i_skp;
1172 /* p_sys->i_current_chapter = i_skp;*/
1175 return VLC_EGENERIC;
1178 case DEMUX_SET_TIME:
1181 return VLC_EGENERIC;
1185 static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1187 demux_sys_t *p_sys = p_demux->p_sys;
1198 if( p_demux->b_die )
1200 return VLC_EGENERIC;
1203 el = p_sys->ep->Get();
1204 i_level = p_sys->ep->GetLevel();
1206 if( el == NULL && *pp_block != NULL )
1208 /* update the index */
1209 #define idx p_sys->index[p_sys->i_index - 1]
1210 if( p_sys->i_index > 0 && idx.i_time == -1 )
1212 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1213 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1221 if( p_sys->ep->GetLevel() > 1 )
1226 msg_Warn( p_demux, "EOF" );
1227 return VLC_EGENERIC;
1233 if( MKV_IS_ID( el, KaxCluster ) )
1235 p_sys->cluster = (KaxCluster*)el;
1237 /* add it to the index */
1238 if( p_sys->i_index == 0 ||
1239 ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
1241 IndexAppendCluster( p_demux, p_sys->cluster );
1246 else if( MKV_IS_ID( el, KaxCues ) )
1248 msg_Warn( p_demux, "find KaxCues FIXME" );
1249 return VLC_EGENERIC;
1253 msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
1256 else if( i_level == 2 )
1258 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1260 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1262 ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
1263 p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
1265 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1270 else if( i_level == 3 )
1272 if( MKV_IS_ID( el, KaxBlock ) )
1274 *pp_block = (KaxBlock*)el;
1276 (*pp_block)->ReadData( p_sys->es->I_O() );
1277 (*pp_block)->SetParent( *p_sys->cluster );
1281 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1283 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1285 dur.ReadData( p_sys->es->I_O() );
1286 *pi_duration = uint64( dur );
1288 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1290 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1292 ref.ReadData( p_sys->es->I_O() );
1293 if( *pi_ref1 == -1 )
1295 *pi_ref1 = int64( ref );
1299 *pi_ref2 = int64( ref );
1305 msg_Err( p_demux, "invalid level = %d", i_level );
1306 return VLC_EGENERIC;
1311 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1314 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1315 memcpy( p_block->p_buffer, p_mem, i_mem );
1316 //p_block->i_rate = p_input->stream.control.i_rate;
1320 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1321 mtime_t i_duration )
1323 demux_sys_t *p_sys = p_demux->p_sys;
1329 #define tk p_sys->track[i_track]
1330 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1332 if( tk.i_number == block->TrackNum() )
1338 if( i_track >= p_sys->i_track )
1340 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1343 if( tk.p_es == NULL )
1345 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1348 if( i_pts < p_sys->i_start_pts && tk.fmt.i_cat == AUDIO_ES )
1350 return; /* discard audio packets that shouldn't be rendered */
1353 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );
1356 tk.b_inited = VLC_FALSE;
1360 /* First send init data */
1361 if( !tk.b_inited && tk.i_data_init > 0 )
1365 msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );
1366 p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );
1367 if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );
1369 tk.b_inited = VLC_TRUE;
1372 for( i = 0; i < block->NumberFrames(); i++ )
1375 DataBuffer &data = block->GetBuffer(i);
1377 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1379 if( p_block == NULL )
1384 #if defined(HAVE_ZLIB_H)
1385 if( tk.i_compression_type )
1387 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1391 if (p_sys->i_start_pts > i_pts)
1394 p_block->i_pts = -1;
1397 if( tk.fmt.i_cat != VIDEO_ES )
1399 p_block->i_dts = p_block->i_pts = i_pts;
1403 p_block->i_dts = i_pts;
1407 if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )
1409 p_block->i_length = i_duration * 1000;
1411 es_out_Send( p_demux->out, tk.p_es, p_block );
1413 /* use time stamp only for first block */
1420 static void UpdateCurrentChapter()
1422 /* update current chapter/seekpoint */
1425 if (p_sys->title->seekpoint[i_skp]->i_time_offset)
1427 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1428 p_demux->info.i_seekpoint = i_chapter;
1433 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent)
1435 demux_sys_t *p_sys = p_demux->p_sys;
1438 int64_t i_block_duration;
1439 int64_t i_block_ref1;
1440 int64_t i_block_ref2;
1443 int i_track_skipping;
1446 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1447 if( i_date < 0 && f_percent < 0 )
1449 msg_Warn( p_demux, "cannot seek nowhere !" );
1452 if( f_percent > 1.0 )
1454 msg_Warn( p_demux, "cannot seek so far !" );
1459 p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1460 p_sys->cluster = NULL;
1462 /* seek without index or without date */
1463 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
1465 if (p_sys->f_duration >= 0)
1467 i_date = f_percent * p_sys->f_duration * 1000;
1471 int64_t i_pos = f_percent * stream_Size( p_demux->s );
1473 msg_Dbg( p_demux, "inacurate way of seeking" );
1474 for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1476 if( p_sys->index[i_index].i_position >= i_pos)
1481 if( i_index == p_sys->i_index )
1486 i_date = p_sys->index[i_index].i_time;
1489 if( p_sys->index[i_index].i_position < i_pos )
1493 msg_Warn( p_demux, "searching for cluster, could take some time" );
1495 /* search a cluster */
1496 while( ( el = p_sys->ep->Get() ) != NULL )
1498 if( MKV_IS_ID( el, KaxCluster ) )
1500 KaxCluster *cluster = (KaxCluster*)el;
1502 /* add it to the index */
1503 IndexAppendCluster( p_demux, cluster );
1505 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1507 p_sys->cluster = cluster;
1518 for( ; i_index < p_sys->i_index; i_index++ )
1520 if( p_sys->index[i_index].i_time > i_date )
1531 msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1532 p_sys->index[i_index].i_time,
1533 (int)( 100 * p_sys->index[i_index].i_position /
1534 stream_Size( p_demux->s ) ) );
1536 p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1540 /* now parse until key frame */
1541 #define tk p_sys->track[i_track]
1542 i_track_skipping = 0;
1543 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1545 if( tk.fmt.i_cat == VIDEO_ES )
1547 tk.b_search_keyframe = VLC_TRUE;
1552 p_sys->i_start_pts = i_date;
1554 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1556 while( i_track_skipping > 0 )
1558 if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1560 msg_Warn( p_demux, "cannot get block EOF?" );
1565 p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
1567 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1569 if( tk.i_number == block->TrackNum() )
1575 if( i_track < p_sys->i_track )
1577 if( tk.fmt.i_cat == VIDEO_ES )
1579 if( i_block_ref1 == -1 && tk.b_search_keyframe )
1581 tk.b_search_keyframe = VLC_FALSE;
1584 if( !tk.b_search_keyframe )
1586 BlockDecode( p_demux, block, 0, 0 );
1596 /*****************************************************************************
1597 * Demux: reads and demuxes data packets
1598 *****************************************************************************
1599 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1600 *****************************************************************************/
1601 static int Demux( demux_t *p_demux)
1603 demux_sys_t *p_sys = p_demux->p_sys;
1604 mtime_t i_start_pts;
1605 int i_block_count = 0;
1609 int64_t i_block_duration;
1610 int64_t i_block_ref1;
1611 int64_t i_block_ref2;
1617 if ( p_sys->editions[p_sys->i_current_edition].b_ordered )
1619 /* 1st, we need to know in which chapter we are */
1621 /* check if we need to silently seek to a new location in the stream */
1622 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1623 /* only seek after each duration >= end timecode of the current chapter */
1626 if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1628 msg_Warn( p_demux, "cannot get block EOF?" );
1633 p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
1635 if( p_sys->i_pts >= p_sys->i_start_pts )
1637 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1640 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1642 UpdateCurrentChapter();
1647 if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )
1656 /*****************************************************************************
1658 *****************************************************************************/
1659 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1665 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1667 if( i_size <= 0 || mb_eof )
1672 return stream_Read( s, p_buffer, i_size );
1674 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1680 case seek_beginning:
1684 i_pos = stream_Size( s ) - i_offset;
1687 i_pos= stream_Tell( s ) + i_offset;
1691 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1698 if( stream_Seek( s, i_pos ) )
1704 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1708 uint64 vlc_stream_io_callback::getFilePointer( void )
1710 return stream_Tell( s );
1712 void vlc_stream_io_callback::close( void )
1718 /*****************************************************************************
1719 * Ebml Stream parser
1720 *****************************************************************************/
1721 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1729 for( i = 1; i < 6; i++ )
1735 mb_keep = VLC_FALSE;
1738 EbmlParser::~EbmlParser( void )
1742 for( i = 1; i < mi_level; i++ )
1748 mb_keep = VLC_FALSE;
1752 void EbmlParser::Up( void )
1754 if( mi_user_level == mi_level )
1756 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1762 void EbmlParser::Down( void )
1768 void EbmlParser::Keep( void )
1773 int EbmlParser::GetLevel( void )
1775 return mi_user_level;
1778 EbmlElement *EbmlParser::Get( void )
1782 if( mi_user_level != mi_level )
1788 EbmlElement *ret = m_got;
1794 if( m_el[mi_level] )
1796 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1799 delete m_el[mi_level];
1801 mb_keep = VLC_FALSE;
1804 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1815 delete m_el[mi_level - 1];
1816 m_got = m_el[mi_level -1] = m_el[mi_level];
1817 m_el[mi_level] = NULL;
1824 else if( m_el[mi_level] == NULL )
1826 fprintf( stderr," m_el[mi_level] == NULL\n" );
1829 return m_el[mi_level];
1833 /*****************************************************************************
1835 * * LoadCues : load the cues element and update index
1837 * * LoadTags : load ... the tags element
1839 * * InformationCreate : create all information, load tags if present
1841 *****************************************************************************/
1842 static void LoadCues( demux_t *p_demux )
1844 demux_sys_t *p_sys = p_demux->p_sys;
1845 int64_t i_sav_position = p_sys->in->getFilePointer();
1847 EbmlElement *el, *cues;
1849 msg_Dbg( p_demux, "loading cues" );
1850 p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1851 cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1855 msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1856 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1860 ep = new EbmlParser( p_sys->es, cues );
1861 while( ( el = ep->Get() ) != NULL )
1863 if( MKV_IS_ID( el, KaxCuePoint ) )
1865 #define idx p_sys->index[p_sys->i_index]
1868 idx.i_block_number= -1;
1869 idx.i_position = -1;
1871 idx.b_key = VLC_TRUE;
1874 while( ( el = ep->Get() ) != NULL )
1876 if( MKV_IS_ID( el, KaxCueTime ) )
1878 KaxCueTime &ctime = *(KaxCueTime*)el;
1880 ctime.ReadData( p_sys->es->I_O() );
1882 idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1884 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1887 while( ( el = ep->Get() ) != NULL )
1889 if( MKV_IS_ID( el, KaxCueTrack ) )
1891 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1893 ctrack.ReadData( p_sys->es->I_O() );
1894 idx.i_track = uint16( ctrack );
1896 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1898 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1900 ccpos.ReadData( p_sys->es->I_O() );
1901 idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1903 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1905 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1907 cbnum.ReadData( p_sys->es->I_O() );
1908 idx.i_block_number = uint32( cbnum );
1912 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1919 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1925 msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
1926 " track=%d bnum=%d", idx.i_time, idx.i_position,
1927 idx.i_track, idx.i_block_number );
1931 if( p_sys->i_index >= p_sys->i_index_max )
1933 p_sys->i_index_max += 1024;
1934 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
1940 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1946 p_sys->b_cues = VLC_TRUE;
1948 msg_Dbg( p_demux, "loading cues done." );
1949 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1952 static void LoadTags( demux_t *p_demux )
1954 demux_sys_t *p_sys = p_demux->p_sys;
1955 int64_t i_sav_position = p_sys->in->getFilePointer();
1957 EbmlElement *el, *tags;
1959 msg_Dbg( p_demux, "loading tags" );
1960 p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
1961 tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
1965 msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
1966 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1970 msg_Dbg( p_demux, "Tags" );
1971 ep = new EbmlParser( p_sys->es, tags );
1972 while( ( el = ep->Get() ) != NULL )
1974 if( MKV_IS_ID( el, KaxTag ) )
1976 msg_Dbg( p_demux, "+ Tag" );
1978 while( ( el = ep->Get() ) != NULL )
1980 if( MKV_IS_ID( el, KaxTagTargets ) )
1982 msg_Dbg( p_demux, "| + Targets" );
1984 while( ( el = ep->Get() ) != NULL )
1986 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
1990 else if( MKV_IS_ID( el, KaxTagGeneral ) )
1992 msg_Dbg( p_demux, "| + General" );
1994 while( ( el = ep->Get() ) != NULL )
1996 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2000 else if( MKV_IS_ID( el, KaxTagGenres ) )
2002 msg_Dbg( p_demux, "| + Genres" );
2004 while( ( el = ep->Get() ) != NULL )
2006 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2010 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2012 msg_Dbg( p_demux, "| + Audio Specific" );
2014 while( ( el = ep->Get() ) != NULL )
2016 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2020 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2022 msg_Dbg( p_demux, "| + Images Specific" );
2024 while( ( el = ep->Get() ) != NULL )
2026 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2030 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2032 msg_Dbg( p_demux, "| + Multi Comment" );
2034 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2036 msg_Dbg( p_demux, "| + Multi Commercial" );
2038 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2040 msg_Dbg( p_demux, "| + Multi Date" );
2042 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2044 msg_Dbg( p_demux, "| + Multi Entity" );
2046 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2048 msg_Dbg( p_demux, "| + Multi Identifier" );
2050 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2052 msg_Dbg( p_demux, "| + Multi Legal" );
2054 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2056 msg_Dbg( p_demux, "| + Multi Title" );
2060 msg_Dbg( p_demux, "| + Unknown (%s)", typeid( *el ).name() );
2067 msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
2073 msg_Dbg( p_demux, "loading tags done." );
2074 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2077 /*****************************************************************************
2079 *****************************************************************************/
2080 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
2082 demux_sys_t *p_sys = p_demux->p_sys;
2086 int i_upper_level = 0;
2088 msg_Dbg( p_demux, "| + Seek head" );
2090 /* Master elements */
2091 m = static_cast<EbmlMaster *>(seekhead);
2092 m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
2094 for( i = 0; i < m->ListSize(); i++ )
2096 EbmlElement *l = (*m)[i];
2098 if( MKV_IS_ID( l, KaxSeek ) )
2100 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2101 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2106 for( j = 0; j < sk->ListSize(); j++ )
2108 EbmlElement *l = (*sk)[j];
2110 if( MKV_IS_ID( l, KaxSeekID ) )
2112 KaxSeekID &sid = *(KaxSeekID*)l;
2113 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2115 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2117 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2118 i_pos = uint64( spos );
2122 msg_Dbg( p_demux, "| | | + Unknown (%s)", typeid(*l).name() );
2128 if( id == KaxCues::ClassInfos.GlobalId )
2130 msg_Dbg( p_demux, "| | | = cues at "I64Fd, i_pos );
2131 p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
2133 else if( id == KaxChapters::ClassInfos.GlobalId )
2135 msg_Dbg( p_demux, "| | | = chapters at "I64Fd, i_pos );
2136 p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
2138 else if( id == KaxTags::ClassInfos.GlobalId )
2140 msg_Dbg( p_demux, "| | | = tags at "I64Fd, i_pos );
2141 p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
2147 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2152 /*****************************************************************************
2154 *****************************************************************************/
2155 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
2157 demux_sys_t *p_sys = p_demux->p_sys;
2162 msg_Dbg( p_demux, "| | + Track Entry" );
2165 p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
2167 /* Init the track */
2168 tk = &p_sys->track[p_sys->i_track - 1];
2170 memset( tk, 0, sizeof( mkv_track_t ) );
2172 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2173 tk->fmt.psz_language = strdup("English");
2174 tk->fmt.psz_description = NULL;
2176 tk->b_default = VLC_TRUE;
2177 tk->b_enabled = VLC_TRUE;
2178 tk->i_number = p_sys->i_track - 1;
2179 tk->i_extra_data = 0;
2180 tk->p_extra_data = NULL;
2181 tk->psz_codec = NULL;
2182 tk->i_default_duration = 0;
2183 tk->f_timecodescale = 1.0;
2185 tk->b_inited = VLC_FALSE;
2186 tk->i_data_init = 0;
2187 tk->p_data_init = NULL;
2189 tk->psz_codec_name = NULL;
2190 tk->psz_codec_settings = NULL;
2191 tk->psz_codec_info_url = NULL;
2192 tk->psz_codec_download_url = NULL;
2194 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2196 for( i = 0; i < m->ListSize(); i++ )
2198 EbmlElement *l = (*m)[i];
2200 if( MKV_IS_ID( l, KaxTrackNumber ) )
2202 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2204 tk->i_number = uint32( tnum );
2205 msg_Dbg( p_demux, "| | | + Track Number=%u", uint32( tnum ) );
2207 else if( MKV_IS_ID( l, KaxTrackUID ) )
2209 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2211 msg_Dbg( p_demux, "| | | + Track UID=%u", uint32( tuid ) );
2213 else if( MKV_IS_ID( l, KaxTrackType ) )
2216 KaxTrackType &ttype = *(KaxTrackType*)l;
2218 switch( uint8(ttype) )
2222 tk->fmt.i_cat = AUDIO_ES;
2226 tk->fmt.i_cat = VIDEO_ES;
2228 case track_subtitle:
2229 psz_type = "subtitle";
2230 tk->fmt.i_cat = SPU_ES;
2233 psz_type = "unknown";
2234 tk->fmt.i_cat = UNKNOWN_ES;
2238 msg_Dbg( p_demux, "| | | + Track Type=%s", psz_type );
2240 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2242 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2244 // tk->b_enabled = uint32( fenb );
2245 // msg_Dbg( p_demux, "| | | + Track Enabled=%u",
2246 // uint32( fenb ) );
2248 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2250 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2252 tk->b_default = uint32( fdef );
2253 msg_Dbg( p_demux, "| | | + Track Default=%u", uint32( fdef ) );
2255 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2257 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2259 msg_Dbg( p_demux, "| | | + Track Lacing=%d", uint32( lac ) );
2261 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2263 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2265 msg_Dbg( p_demux, "| | | + Track MinCache=%d", uint32( cmin ) );
2267 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2269 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2271 msg_Dbg( p_demux, "| | | + Track MaxCache=%d", uint32( cmax ) );
2273 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2275 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2277 tk->i_default_duration = uint64(defd);
2278 msg_Dbg( p_demux, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2280 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2282 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2284 tk->f_timecodescale = float( ttcs );
2285 msg_Dbg( p_demux, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2287 else if( MKV_IS_ID( l, KaxTrackName ) )
2289 KaxTrackName &tname = *(KaxTrackName*)l;
2291 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2292 msg_Dbg( p_demux, "| | | + Track Name=%s", tk->fmt.psz_description );
2294 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2296 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2298 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2300 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2302 else if( MKV_IS_ID( l, KaxCodecID ) )
2304 KaxCodecID &codecid = *(KaxCodecID*)l;
2306 tk->psz_codec = strdup( string( codecid ).c_str() );
2307 msg_Dbg( p_demux, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2309 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2311 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2313 tk->i_extra_data = cpriv.GetSize();
2314 if( tk->i_extra_data > 0 )
2316 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2317 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2319 msg_Dbg( p_demux, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2321 else if( MKV_IS_ID( l, KaxCodecName ) )
2323 KaxCodecName &cname = *(KaxCodecName*)l;
2325 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2326 msg_Dbg( p_demux, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2328 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2330 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2331 MkvTree( p_demux, 3, "Content Encodings" );
2332 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2334 EbmlElement *l2 = (*cencs)[i];
2335 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2337 MkvTree( p_demux, 4, "Content Encoding" );
2338 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2339 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2341 EbmlElement *l3 = (*cenc)[i];
2342 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2344 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2345 MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2347 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2349 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2350 MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2352 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2354 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2355 MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2357 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2359 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2360 MkvTree( p_demux, 5, "Content Compression" );
2361 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2363 EbmlElement *l4 = (*compr)[i];
2364 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2366 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2367 MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2368 if( uint32( compalg ) == 0 )
2370 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2375 MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2382 MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2389 MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2394 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2396 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2398 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2399 // msg_Dbg( p_demux, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2401 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2403 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2405 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2406 // msg_Dbg( p_demux, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2408 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2410 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2412 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2413 // msg_Dbg( p_demux, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2415 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2417 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2419 // msg_Dbg( p_demux, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2421 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2423 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2425 // msg_Dbg( p_demux, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2427 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2429 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2432 msg_Dbg( p_demux, "| | | + Track Video" );
2435 for( j = 0; j < tkv->ListSize(); j++ )
2437 EbmlElement *l = (*tkv)[j];
2438 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2440 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2442 // msg_Dbg( p_demux, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2444 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2446 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2448 // msg_Dbg( p_demux, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2451 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2453 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2455 tk->fmt.video.i_width = uint16( vwidth );
2456 msg_Dbg( p_demux, "| | | | + width=%d", uint16( vwidth ) );
2458 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2460 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2462 tk->fmt.video.i_height = uint16( vheight );
2463 msg_Dbg( p_demux, "| | | | + height=%d", uint16( vheight ) );
2465 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2467 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2469 tk->fmt.video.i_visible_width = uint16( vwidth );
2470 msg_Dbg( p_demux, "| | | | + display width=%d", uint16( vwidth ) );
2472 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2474 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2476 tk->fmt.video.i_visible_height = uint16( vheight );
2477 msg_Dbg( p_demux, "| | | | + display height=%d", uint16( vheight ) );
2479 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2481 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2483 tk->f_fps = float( vfps );
2484 msg_Dbg( p_demux, " | | | + fps=%f", float( vfps ) );
2486 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2488 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2490 // msg_Dbg( p_demux, "| | | | + Track Video Display Unit=%s",
2491 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2493 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2495 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2497 // msg_Dbg( p_demux, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2499 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2501 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2503 // msg_Dbg( p_demux, " | | | + fps=%f", float( gamma ) );
2507 msg_Dbg( p_demux, "| | | | + Unknown (%s)", typeid(*l).name() );
2511 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2513 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2516 msg_Dbg( p_demux, "| | | + Track Audio" );
2518 for( j = 0; j < tka->ListSize(); j++ )
2520 EbmlElement *l = (*tka)[j];
2522 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2524 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2526 tk->fmt.audio.i_rate = (int)float( afreq );
2527 msg_Dbg( p_demux, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2529 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2531 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2533 tk->fmt.audio.i_channels = uint8( achan );
2534 msg_Dbg( p_demux, "| | | | + achan=%u", uint8( achan ) );
2536 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2538 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2540 tk->fmt.audio.i_bitspersample = uint8( abits );
2541 msg_Dbg( p_demux, "| | | | + abits=%u", uint8( abits ) );
2545 msg_Dbg( p_demux, "| | | | + Unknown (%s)", typeid(*l).name() );
2551 msg_Dbg( p_demux, "| | | + Unknown (%s)",
2552 typeid(*l).name() );
2557 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2559 demux_sys_t *p_sys = p_demux->p_sys;
2563 int i_upper_level = 0;
2565 msg_Dbg( p_demux, "| + Tracks" );
2567 /* Master elements */
2568 m = static_cast<EbmlMaster *>(tracks);
2569 m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2571 for( i = 0; i < m->ListSize(); i++ )
2573 EbmlElement *l = (*m)[i];
2575 if( MKV_IS_ID( l, KaxTrackEntry ) )
2577 ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2581 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2586 /*****************************************************************************
2588 *****************************************************************************/
2589 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2591 demux_sys_t *p_sys = p_demux->p_sys;
2595 int i_upper_level = 0;
2597 msg_Dbg( p_demux, "| + Information" );
2599 /* Master elements */
2600 m = static_cast<EbmlMaster *>(info);
2601 m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2603 for( i = 0; i < m->ListSize(); i++ )
2605 EbmlElement *l = (*m)[i];
2607 if( MKV_IS_ID( l, KaxSegmentUID ) )
2609 p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2611 msg_Dbg( p_demux, "| | + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
2613 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2615 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2617 p_sys->i_timescale = uint64(tcs);
2619 msg_Dbg( p_demux, "| | + TimecodeScale="I64Fd,
2620 p_sys->i_timescale );
2622 else if( MKV_IS_ID( l, KaxDuration ) )
2624 KaxDuration &dur = *(KaxDuration*)l;
2626 p_sys->f_duration = float(dur);
2628 msg_Dbg( p_demux, "| | + Duration=%f",
2629 p_sys->f_duration );
2631 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2633 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2635 p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2637 msg_Dbg( p_demux, "| | + Muxing Application=%s",
2638 p_sys->psz_muxing_application );
2640 else if( MKV_IS_ID( l, KaxWritingApp ) )
2642 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2644 p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2646 msg_Dbg( p_demux, "| | + Writing Application=%s",
2647 p_sys->psz_writing_application );
2649 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2651 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2653 p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2655 msg_Dbg( p_demux, "| | + Segment Filename=%s",
2656 p_sys->psz_segment_filename );
2658 else if( MKV_IS_ID( l, KaxTitle ) )
2660 KaxTitle &title = *(KaxTitle*)l;
2662 p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2664 msg_Dbg( p_demux, "| | + Title=%s", p_sys->psz_title );
2666 if( MKV_IS_ID( l, KaxSegmentFamily ) )
2668 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2670 p_sys->families.push_back(*uid);
2672 msg_Dbg( p_demux, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2674 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2675 else if( MKV_IS_ID( l, KaxDateUTC ) )
2677 KaxDateUTC &date = *(KaxDateUTC*)l;
2682 i_date = date.GetEpochDate();
2683 memset( buffer, 0, 256 );
2684 if( gmtime_r( &i_date, &tmres ) &&
2685 asctime_r( &tmres, buffer ) )
2687 buffer[strlen( buffer)-1]= '\0';
2688 p_sys->psz_date_utc = strdup( buffer );
2689 msg_Dbg( p_demux, "| | + Date=%s", p_sys->psz_date_utc );
2695 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2699 p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
2703 /*****************************************************************************
2705 *****************************************************************************/
2706 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2708 demux_sys_t *p_sys = p_demux->p_sys;
2711 bool b_display_seekpoint = true;
2713 if( p_sys->title == NULL )
2715 p_sys->title = vlc_input_title_New();
2717 sk = vlc_seekpoint_New();
2719 sk->i_level = i_level;
2721 msg_Dbg( p_demux, "| | | + ChapterAtom (level=%d)", i_level );
2722 for( i = 0; i < ca->ListSize(); i++ )
2724 EbmlElement *l = (*ca)[i];
2726 if( MKV_IS_ID( l, KaxChapterUID ) )
2728 KaxChapterUID &uid = *(KaxChapterUID*)l;
2729 uint32_t i_uid = uint32( uid );
2730 msg_Dbg( p_demux, "| | | | + ChapterUID: 0x%x", i_uid );
2732 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2734 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2735 b_display_seekpoint = uint8( flag ) == 0;
2737 msg_Dbg( p_demux, "| | | | + ChapterFlagHidden: %s", b_display_seekpoint ? "no":"yes" );
2739 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2741 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2742 sk->i_time_offset = uint64( start ) / I64C(1000);
2744 msg_Dbg( p_demux, "| | | | + ChapterTimeStart: %lld", sk->i_time_offset );
2746 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2748 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2749 int64_t i_end = uint64( end );
2751 msg_Dbg( p_demux, "| | | | + ChapterTimeEnd: %lld", i_end );
2753 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2755 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2758 msg_Dbg( p_demux, "| | | | + ChapterDisplay" );
2759 for( j = 0; j < cd->ListSize(); j++ )
2761 EbmlElement *l= (*cd)[j];
2763 if( MKV_IS_ID( l, KaxChapterString ) )
2768 KaxChapterString &name =*(KaxChapterString*)l;
2769 for (k = 0; k < i_level; k++)
2772 psz += UTF8ToStr( UTFstring( name ) );
2773 sk->psz_name = strdup( psz.c_str() );
2774 msg_Dbg( p_demux, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2776 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2778 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2779 const char *psz = string( lang ).c_str();
2781 msg_Dbg( p_demux, "| | | | | + ChapterLanguage '%s'", psz );
2783 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2785 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2786 const char *psz = string( ct ).c_str();
2788 msg_Dbg( p_demux, "| | | | | + ChapterCountry '%s'", psz );
2792 else if( MKV_IS_ID( l, KaxChapterAtom ) )
2794 chapter_item_t new_sub_chapter;
2795 ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
2796 chapters.sub_chapters.push_back( new_sub_chapter );
2800 if (b_display_seekpoint)
2802 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2803 p_sys->title->i_seekpoint++;
2804 p_sys->title->seekpoint = (seekpoint_t**)realloc( p_sys->title->seekpoint, p_sys->title->i_seekpoint * sizeof( seekpoint_t* ) );
2805 p_sys->title->seekpoint[p_sys->title->i_seekpoint-1] = sk;
2809 vlc_seekpoint_Delete(sk);
2813 /*****************************************************************************
2815 *****************************************************************************/
2816 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2818 demux_sys_t *p_sys = p_demux->p_sys;
2822 int i_upper_level = 0;
2823 int i_default_edition = 0;
2825 /* Master elements */
2826 m = static_cast<EbmlMaster *>(chapters);
2827 m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2829 for( i = 0; i < m->ListSize(); i++ )
2831 EbmlElement *l = (*m)[i];
2833 if( MKV_IS_ID( l, KaxEditionEntry ) )
2835 chapter_edition_t edition;
2837 EbmlMaster *E = static_cast<EbmlMaster *>(l );
2839 msg_Dbg( p_demux, "| | + EditionEntry" );
2840 for( j = 0; j < E->ListSize(); j++ )
2842 EbmlElement *l = (*E)[j];
2844 if( MKV_IS_ID( l, KaxChapterAtom ) )
2846 chapter_item_t new_sub_chapter;
2847 ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
2848 edition.chapters.push_back( new_sub_chapter );
2850 else if( MKV_IS_ID( l, KaxEditionUID ) )
2852 edition.i_uid = uint64(*static_cast<KaxEditionUID *>(l));
2854 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
2856 edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>(l)) != 0;
2858 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
2860 if (uint8(*static_cast<KaxEditionFlagDefault *>(l)) != 0)
2861 p_sys->i_current_edition = p_sys->editions.size();
2865 msg_Dbg( p_demux, "| | | + Unknown (%s)", typeid(*l).name() );
2868 p_sys->editions.push_back( edition );
2872 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2876 p_sys->i_current_edition = i_default_edition;
2878 if ( p_sys->editions[i_default_edition].b_ordered )
2880 /* update the duration of the segment according to the sum of all sub chapters */
2884 /*****************************************************************************
2885 * InformationCreate:
2886 *****************************************************************************/
2887 static void InformationCreate( demux_t *p_demux )
2889 demux_sys_t *p_sys = p_demux->p_sys;
2892 p_sys->meta = vlc_meta_New();
2894 if( p_sys->psz_title )
2896 vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2898 if( p_sys->psz_date_utc )
2900 vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2902 if( p_sys->psz_segment_filename )
2904 vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2906 if( p_sys->psz_muxing_application )
2908 vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2910 if( p_sys->psz_writing_application )
2912 vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2915 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2917 mkv_track_t *tk = &p_sys->track[i_track];
2918 vlc_meta_t *mtk = vlc_meta_New();
2920 p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2921 sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2922 p_sys->meta->track[p_sys->meta->i_track++] = mtk;
2924 if( tk->fmt.psz_description )
2926 vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
2928 if( tk->psz_codec_name )
2930 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
2932 if( tk->psz_codec_settings )
2934 vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
2936 if( tk->psz_codec_info_url )
2938 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
2940 if( tk->psz_codec_download_url )
2942 vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
2946 if( p_sys->i_tags_position >= 0 )
2948 vlc_bool_t b_seekable;
2950 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
2953 LoadTags( p_demux );
2959 /*****************************************************************************
2961 *****************************************************************************/
2963 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
2965 demux_sys_t *p_sys = p_demux->p_sys;
2967 #define idx p_sys->index[p_sys->i_index]
2969 idx.i_block_number= -1;
2970 idx.i_position = cluster->GetElementPosition();
2972 idx.b_key = VLC_TRUE;
2975 if( p_sys->i_index >= p_sys->i_index_max )
2977 p_sys->i_index_max += 1024;
2978 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2983 static char * UTF8ToStr( const UTFstring &u )
2992 p = dst = (char*)malloc( i_src + 1);