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 */
52 /* libebml and matroska */
53 #include "ebml/EbmlHead.h"
54 #include "ebml/EbmlSubHead.h"
55 #include "ebml/EbmlStream.h"
56 #include "ebml/EbmlContexts.h"
57 #include "ebml/EbmlVoid.h"
58 #include "ebml/StdIOCallback.h"
60 #include "matroska/KaxAttachments.h"
61 #include "matroska/KaxBlock.h"
62 #include "matroska/KaxBlockData.h"
63 #include "matroska/KaxChapters.h"
64 #include "matroska/KaxCluster.h"
65 #include "matroska/KaxClusterData.h"
66 #include "matroska/KaxContexts.h"
67 #include "matroska/KaxCues.h"
68 #include "matroska/KaxCuesData.h"
69 #include "matroska/KaxInfo.h"
70 #include "matroska/KaxInfoData.h"
71 #include "matroska/KaxSeekHead.h"
72 #include "matroska/KaxSegment.h"
73 #include "matroska/KaxTag.h"
74 #include "matroska/KaxTags.h"
75 #include "matroska/KaxTagMulti.h"
76 #include "matroska/KaxTracks.h"
77 #include "matroska/KaxTrackAudio.h"
78 #include "matroska/KaxTrackVideo.h"
79 #include "matroska/KaxTrackEntryData.h"
80 #include "matroska/KaxContentEncoding.h"
82 #include "ebml/StdIOCallback.h"
85 #include "mp4/libmp4.h"
91 #define MATROSKA_COMPRESSION_NONE 0
92 #define MATROSKA_COMPRESSION_ZLIB 1
95 * What's between a directory and a filename?
98 #define DIRECTORY_SEPARATOR '\\'
100 #define DIRECTORY_SEPARATOR '/'
103 using namespace LIBMATROSKA_NAMESPACE;
106 /*****************************************************************************
108 *****************************************************************************/
109 static int Open ( vlc_object_t * );
110 static void Close( vlc_object_t * );
113 set_shortname( _("Matroska") );
114 set_description( _("Matroska stream demuxer" ) );
115 set_capability( "demux2", 50 );
116 set_callbacks( Open, Close );
117 set_category( CAT_INPUT );
118 set_subcategory( SUBCAT_INPUT_DEMUX );
120 add_bool( "mkv-seek-percent", 1, NULL,
121 N_("Seek based on percent not time"),
122 N_("Seek based on percent not time"), VLC_TRUE );
124 add_shortcut( "mka" );
125 add_shortcut( "mkv" );
128 /*****************************************************************************
130 *****************************************************************************/
131 static int Demux ( demux_t * );
132 static int Control( demux_t *, int, va_list );
133 static void Seek ( demux_t *, mtime_t i_date, double f_percent );
136 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
137 int result, dstsize, n;
142 d_stream.zalloc = (alloc_func)0;
143 d_stream.zfree = (free_func)0;
144 d_stream.opaque = (voidpf)0;
145 result = inflateInit(&d_stream);
148 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
152 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
153 d_stream.avail_in = p_in_block->i_buffer;
155 p_block = block_New( p_this, 0 );
160 p_block = block_Realloc( p_block, 0, n * 1000 );
161 dst = (unsigned char *)p_block->p_buffer;
162 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
163 d_stream.avail_out = 1000;
164 result = inflate(&d_stream, Z_NO_FLUSH);
165 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
167 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
171 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
172 ( result != Z_STREAM_END ) );
174 dstsize = d_stream.total_out;
175 inflateEnd( &d_stream );
177 p_block = block_Realloc( p_block, 0, dstsize );
178 p_block->i_buffer = dstsize;
179 block_Release( p_in_block );
186 * Helper function to print the mkv parse tree
188 static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )
193 msg_Err( p_this, "too deep tree" );
196 va_start( args, psz_format );
197 static char *psz_foo = "| | | | | | | | | |";
198 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
199 strncpy( psz_foo2, psz_foo, 4 * i_level );
200 psz_foo2[ 4 * i_level ] = '+';
201 psz_foo2[ 4 * i_level + 1 ] = ' ';
202 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
203 __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );
208 /*****************************************************************************
210 *****************************************************************************/
211 class vlc_stream_io_callback: public IOCallback
218 vlc_stream_io_callback( stream_t * );
220 virtual uint32 read ( void *p_buffer, size_t i_size);
221 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
222 virtual size_t write ( const void *p_buffer, size_t i_size);
223 virtual uint64 getFilePointer ( void );
224 virtual void close ( void );
227 /*****************************************************************************
229 *****************************************************************************/
233 EbmlParser( EbmlStream *es, EbmlElement *el_start );
238 EbmlElement *Get( void );
241 int GetLevel( void );
246 EbmlElement *m_el[10];
255 /*****************************************************************************
256 * Some functions to manipulate memory
257 *****************************************************************************/
258 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
259 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
261 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
264 /*****************************************************************************
265 * definitions of structures and functions used by this plugins
266 *****************************************************************************/
269 vlc_bool_t b_default;
270 vlc_bool_t b_enabled;
274 uint8_t *p_extra_data;
278 uint64_t i_default_duration;
279 float f_timecodescale;
287 /* data to be send first */
289 uint8_t *p_data_init;
291 /* hack : it's for seek */
292 vlc_bool_t b_search_keyframe;
295 char *psz_codec_name;
296 char *psz_codec_settings;
297 char *psz_codec_info_url;
298 char *psz_codec_download_url;
300 /* encryption/compression */
301 int i_compression_type;
319 int64_t i_start_time, i_end_time;
320 int64_t i_absolute_start_time; /* the time in the stream when an edition is ordered */
321 std::vector<chapter_item_t> sub_chapters;
322 int i_current_sub_chapter;
326 class chapter_edition_t
334 std::vector<chapter_item_t> chapters;
351 ,i_chapters_position(0)
361 ,psz_muxing_application(NULL)
362 ,psz_writing_application(NULL)
363 ,psz_segment_filename(NULL)
368 ,i_current_edition(0)
371 vlc_stream_io_callback *in;
376 uint64_t i_timescale;
378 /* duration of the segment */
386 int64_t i_cues_position;
387 int64_t i_chapters_position;
388 int64_t i_tags_position;
393 KaxSegmentUID segment_uid;
404 char *psz_muxing_application;
405 char *psz_writing_application;
406 char *psz_segment_filename;
412 input_title_t *title;
414 std::vector<KaxSegmentFamily> families;
415 std::vector<KaxSegment*> family_members;
417 std::vector<chapter_edition_t> editions;
418 int i_current_edition;
421 #define MKVD_TIMECODESCALE 1000000
423 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
425 static void IndexAppendCluster ( demux_t *p_demux, KaxCluster *cluster );
426 static char *UTF8ToStr ( const UTFstring &u );
427 static void LoadCues ( demux_t * );
428 static void InformationCreate ( demux_t * );
430 static void ParseInfo( demux_t *, EbmlElement *info );
431 static void ParseTracks( demux_t *, EbmlElement *tracks );
432 static void ParseSeekHead( demux_t *, EbmlElement *seekhead );
433 static void ParseChapters( demux_t *, EbmlElement *chapters );
435 /*****************************************************************************
436 * Open: initializes matroska demux structures
437 *****************************************************************************/
438 static int Open( vlc_object_t * p_this )
440 demux_t *p_demux = (demux_t*)p_this;
443 std::string s_path, s_filename;
449 EbmlElement *el = NULL, *el1 = NULL;
451 /* peek the begining */
452 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
454 msg_Warn( p_demux, "cannot peek" );
458 /* is a valid file */
459 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
460 p_peek[2] != 0xdf || p_peek[3] != 0xa3 )
462 msg_Warn( p_demux, "matroska module discarded "
463 "(invalid header 0x%.2x%.2x%.2x%.2x)",
464 p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
468 /* Set the demux function */
469 p_demux->pf_demux = Demux;
470 p_demux->pf_control = Control;
471 p_demux->p_sys = p_sys = new demux_sys_t;
473 p_sys->in = new vlc_stream_io_callback( p_demux->s );
474 p_sys->es = new EbmlStream( *p_sys->in );
475 p_sys->f_duration = -1;
476 p_sys->i_timescale = MKVD_TIMECODESCALE;
478 p_sys->track = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
480 p_sys->i_cues_position = -1;
481 p_sys->i_chapters_position = -1;
482 p_sys->i_tags_position = -1;
484 p_sys->b_cues = VLC_FALSE;
486 p_sys->i_index_max = 1024;
487 p_sys->index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *
488 p_sys->i_index_max );
490 p_sys->psz_muxing_application = NULL;
491 p_sys->psz_writing_application = NULL;
492 p_sys->psz_segment_filename = NULL;
493 p_sys->psz_title = NULL;
494 p_sys->psz_date_utc = NULL;;
498 if( p_sys->es == NULL )
500 msg_Err( p_demux, "failed to create EbmlStream" );
505 /* Find the EbmlHead element */
506 el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
509 msg_Err( p_demux, "cannot find EbmlHead" );
512 msg_Dbg( p_demux, "EbmlHead" );
514 el->SkipData( *p_sys->es, el->Generic().Context );
518 el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
521 msg_Err( p_demux, "cannot find KaxSegment" );
524 MkvTree( p_demux, 0, "Segment" );
525 p_sys->segment = (KaxSegment*)el;
526 p_sys->cluster = NULL;
528 p_sys->ep = new EbmlParser( p_sys->es, el );
530 while( ( el1 = p_sys->ep->Get() ) != NULL )
532 if( MKV_IS_ID( el1, KaxInfo ) )
534 ParseInfo( p_demux, el1 );
536 else if( MKV_IS_ID( el1, KaxTracks ) )
538 ParseTracks( p_demux, el1 );
540 else if( MKV_IS_ID( el1, KaxSeekHead ) )
542 ParseSeekHead( p_demux, el1 );
544 else if( MKV_IS_ID( el1, KaxCues ) )
546 msg_Dbg( p_demux, "| + Cues" );
548 else if( MKV_IS_ID( el1, KaxCluster ) )
550 msg_Dbg( p_demux, "| + Cluster" );
552 p_sys->cluster = (KaxCluster*)el1;
555 /* stop parsing the stream */
558 else if( MKV_IS_ID( el1, KaxAttachments ) )
560 msg_Dbg( p_demux, "| + Attachments FIXME TODO (but probably never supported)" );
562 else if( MKV_IS_ID( el1, KaxChapters ) )
564 msg_Dbg( p_demux, "| + Chapters" );
565 ParseChapters( p_demux, el1 );
567 else if( MKV_IS_ID( el1, KaxTag ) )
569 msg_Dbg( p_demux, "| + Tags FIXME TODO" );
573 msg_Dbg( p_demux, "| + Unknown (%s)", typeid(*el1).name() );
577 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
578 /* _todo_ handle multi-segment files */
579 if (p_demux->psz_path[0] != '\0' && (!strcmp(p_demux->psz_access, "") || !strcmp(p_demux->psz_access, "")))
581 // assume it's a regular file
582 // get the directory path
583 s_path = p_demux->psz_path;
584 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
586 s_path = s_path.substr(0,s_path.length()-1);
590 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
592 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
596 struct dirent *p_file_item;
597 DIR *p_src_dir = opendir(s_path.c_str());
599 if (p_src_dir != NULL)
601 while ((p_file_item = (dirent *) readdir(p_src_dir)))
603 if (strlen(p_file_item->d_name) > 4)
605 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
607 if (!s_filename.compare(p_demux->psz_path))
610 #if defined(__GNUC__) && (__GNUC__ < 3)
611 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
612 !s_filename.compare("mka", s_filename.length() - 3, 3))
614 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
615 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
618 // test wether this file belongs to the our family
619 bool b_keep_file_opened = false;
620 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
621 EbmlStream *p_stream = new EbmlStream(*p_file_io);
622 EbmlElement *p_l0, *p_l1, *p_l2;
624 // verify the EBML Header
625 p_l0 = p_stream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
633 p_l0->SkipData(*p_stream, EbmlHead_Context);
636 // find all segments in this file
637 p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
649 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
652 KaxSegmentUID *p_uid = NULL;
654 ep = new EbmlParser(p_stream, p_l0);
655 bool b_this_segment_matches = false;
656 while ((p_l1 = ep->Get()))
658 if (MKV_IS_ID(p_l1, KaxInfo))
660 // find the families of this segment
661 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
663 p_info->Read(*p_stream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
664 for( i = 0; i < p_info->ListSize() && !b_this_segment_matches; i++ )
666 EbmlElement *l = (*p_info)[i];
668 if( MKV_IS_ID( l, KaxSegmentUID ) )
670 p_uid = static_cast<KaxSegmentUID*>(l);
671 if (p_sys->segment_uid == *p_uid)
674 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
676 KaxSegmentFamily *p_fam = static_cast<KaxSegmentFamily*>(l);
677 std::vector<KaxSegmentFamily>::iterator iter;
678 for( iter = p_sys->families.begin();
679 iter != p_sys->families.end();
682 if( *iter == *p_fam )
684 b_this_segment_matches = true;
694 if (b_this_segment_matches)
696 b_keep_file_opened = true;
700 p_l0->SkipData(*p_stream, EbmlHead_Context);
702 p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
705 if (!b_keep_file_opened)
713 closedir( p_src_dir );
718 if( p_sys->cluster == NULL )
720 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
724 /* *** Load the cue if found *** */
725 if( p_sys->i_cues_position >= 0 )
727 vlc_bool_t b_seekable;
729 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
736 if( !p_sys->b_cues || p_sys->i_index <= 0 )
738 msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
740 IndexAppendCluster( p_demux, p_sys->cluster );
742 p_sys->b_cues = VLC_FALSE;
746 msg_Dbg( p_demux, "found %d es", p_sys->i_track );
747 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
749 #define tk p_sys->track[i_track]
750 if( tk.fmt.i_cat == UNKNOWN_ES )
752 msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );
757 if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
759 if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
761 msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );
762 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
766 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
768 tk.fmt.video.i_width = GetDWLE( &p_bih->biWidth );
769 tk.fmt.video.i_height= GetDWLE( &p_bih->biHeight );
770 tk.fmt.i_codec = GetFOURCC( &p_bih->biCompression );
772 tk.fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
773 if( tk.fmt.i_extra > 0 )
775 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
776 memcpy( tk.fmt.p_extra, &p_bih[1], tk.fmt.i_extra );
780 else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||
781 !strcmp( tk.psz_codec, "V_MPEG2" ) )
783 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
785 else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )
787 if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )
789 tk.fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
791 else if( !strcmp( tk.psz_codec, "V_MPEG4/ISO/AVC" ) )
793 tk.fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
794 tk.fmt.b_packetized = VLC_FALSE;
795 tk.fmt.i_extra = tk.i_extra_data;
796 tk.fmt.p_extra = malloc( tk.i_extra_data );
797 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
801 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
804 else if( !strcmp( tk.psz_codec, "V_QUICKTIME" ) )
806 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
807 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),
810 MP4_ReadBoxCommon( p_mp4_stream, p_box );
811 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
812 tk.fmt.i_codec = p_box->i_type;
813 tk.fmt.video.i_width = p_box->data.p_sample_vide->i_width;
814 tk.fmt.video.i_height = p_box->data.p_sample_vide->i_height;
815 tk.fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
816 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
817 memcpy( tk.fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk.fmt.i_extra );
818 MP4_FreeBox_sample_vide( p_box );
819 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
821 else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )
823 if( tk.i_extra_data < (int)sizeof( WAVEFORMATEX ) )
825 msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );
826 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
830 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;
832 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk.fmt.i_codec, NULL );
834 tk.fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
835 tk.fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
836 tk.fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
837 tk.fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
838 tk.fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
840 tk.fmt.i_extra = GetWLE( &p_wf->cbSize );
841 if( tk.fmt.i_extra > 0 )
843 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
844 memcpy( tk.fmt.p_extra, &p_wf[1], tk.fmt.i_extra );
848 else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||
849 !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||
850 !strcmp( tk.psz_codec, "A_MPEG/L1" ) )
852 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
854 else if( !strcmp( tk.psz_codec, "A_AC3" ) )
856 tk.fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
858 else if( !strcmp( tk.psz_codec, "A_DTS" ) )
860 tk.fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
862 else if( !strcmp( tk.psz_codec, "A_FLAC" ) )
864 tk.fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
865 tk.fmt.i_extra = tk.i_extra_data;
866 tk.fmt.p_extra = malloc( tk.i_extra_data );
867 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
869 else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )
871 int i, i_offset = 1, i_size[3], i_extra;
874 tk.fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
876 /* Split the 3 headers */
877 if( tk.p_extra_data[0] != 0x02 )
878 msg_Err( p_demux, "invalid vorbis header" );
880 for( i = 0; i < 2; i++ )
883 while( i_offset < tk.i_extra_data )
885 i_size[i] += tk.p_extra_data[i_offset];
886 if( tk.p_extra_data[i_offset++] != 0xff ) break;
890 i_size[0] = __MIN(i_size[0], tk.i_extra_data - i_offset);
891 i_size[1] = __MIN(i_size[1], tk.i_extra_data -i_offset -i_size[0]);
892 i_size[2] = tk.i_extra_data - i_offset - i_size[0] - i_size[1];
894 tk.fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
895 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
896 p_extra = (uint8_t *)tk.fmt.p_extra; i_extra = 0;
897 for( i = 0; i < 3; i++ )
899 *(p_extra++) = i_size[i] >> 8;
900 *(p_extra++) = i_size[i] & 0xFF;
901 memcpy( p_extra, tk.p_extra_data + i_offset + i_extra,
903 p_extra += i_size[i];
904 i_extra += i_size[i];
907 else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
908 !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
910 int i_profile, i_srate;
911 static unsigned int i_sample_rates[] =
913 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
914 16000, 12000, 11025, 8000, 7350, 0, 0, 0
917 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
918 /* create data for faad (MP4DecSpecificDescrTag)*/
920 if( !strcmp( &tk.psz_codec[12], "MAIN" ) )
924 else if( !strcmp( &tk.psz_codec[12], "LC" ) )
928 else if( !strcmp( &tk.psz_codec[12], "SSR" ) )
937 for( i_srate = 0; i_srate < 13; i_srate++ )
939 if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )
944 msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );
947 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
948 ((uint8_t*)tk.fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
949 ((uint8_t*)tk.fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk.fmt.audio.i_channels << 3);
951 else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||
952 !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||
953 !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )
955 if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )
957 tk.fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
961 tk.fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
963 tk.fmt.audio.i_blockalign = ( tk.fmt.audio.i_bitspersample + 7 ) / 8 * tk.fmt.audio.i_channels;
965 else if( !strcmp( tk.psz_codec, "A_TTA1" ) )
967 /* FIXME: support this codec */
968 msg_Err( p_demux, "TTA not supported yet[%d, n=%d]", i_track, tk.i_number );
969 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
971 else if( !strcmp( tk.psz_codec, "A_WAVPACK4" ) )
973 /* FIXME: support this codec */
974 msg_Err( p_demux, "Wavpack not supported yet[%d, n=%d]", i_track, tk.i_number );
975 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
977 else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )
979 tk.fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
980 tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
982 else if( !strcmp( tk.psz_codec, "S_TEXT/SSA" ) ||
983 !strcmp( tk.psz_codec, "S_TEXT/ASS" ) ||
984 !strcmp( tk.psz_codec, "S_SSA" ) ||
985 !strcmp( tk.psz_codec, "S_ASS" ))
987 tk.fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
988 tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
990 else if( !strcmp( tk.psz_codec, "S_VOBSUB" ) )
992 tk.fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
993 if( tk.i_extra_data )
996 char *p_buf = (char *)malloc( tk.i_extra_data + 1);
997 memcpy( p_buf, tk.p_extra_data , tk.i_extra_data );
998 p_buf[tk.i_extra_data] = '\0';
1000 p_start = strstr( p_buf, "size:" );
1001 if( sscanf( p_start, "size: %dx%d",
1002 &tk.fmt.subs.spu.i_original_frame_width, &tk.fmt.subs.spu.i_original_frame_height ) == 2 )
1004 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 );
1008 msg_Warn( p_demux, "reading original frame size for vobsub failed" );
1013 else if( !strcmp( tk.psz_codec, "B_VOBBTN" ) )
1015 /* FIXME: support this codec */
1016 msg_Err( p_demux, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk.i_number );
1017 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1021 msg_Err( p_demux, "unknow codec id=`%s'", tk.psz_codec );
1022 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1026 tk.fmt.i_priority = 1000;
1029 tk.p_es = es_out_Add( p_demux->out, &tk.fmt );
1033 /* add information */
1034 InformationCreate( p_demux );
1042 return VLC_EGENERIC;
1045 /*****************************************************************************
1046 * Close: frees unused data
1047 *****************************************************************************/
1048 static void Close( vlc_object_t *p_this )
1050 demux_t *p_demux = (demux_t*)p_this;
1051 demux_sys_t *p_sys = p_demux->p_sys;
1054 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1056 #define tk p_sys->track[i_track]
1057 if( tk.fmt.psz_description )
1059 free( tk.fmt.psz_description );
1063 free( tk.psz_codec );
1065 if( tk.fmt.psz_language )
1067 free( tk.fmt.psz_language );
1071 free( p_sys->track );
1073 if( p_sys->psz_writing_application )
1075 free( p_sys->psz_writing_application );
1077 if( p_sys->psz_muxing_application )
1079 free( p_sys->psz_muxing_application );
1082 delete p_sys->segment;
1090 /*****************************************************************************
1092 *****************************************************************************/
1093 static int Control( demux_t *p_demux, int i_query, va_list args )
1095 demux_sys_t *p_sys = p_demux->p_sys;
1100 vlc_meta_t **pp_meta;
1104 case DEMUX_GET_META:
1105 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1106 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1109 case DEMUX_GET_LENGTH:
1110 pi64 = (int64_t*)va_arg( args, int64_t * );
1111 if( p_sys->f_duration > 0.0 )
1113 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1116 return VLC_EGENERIC;
1118 case DEMUX_GET_POSITION:
1119 pf = (double*)va_arg( args, double * );
1120 /* if (p_sys->i_pts < p_sys->i_start_pts)
1121 *pf = (double)p_sys->i_start_pts / (1000.0 * p_sys->f_duration);
1123 *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
1126 case DEMUX_SET_POSITION:
1127 f = (double)va_arg( args, double );
1128 Seek( p_demux, -1, f );
1131 case DEMUX_GET_TIME:
1132 pi64 = (int64_t*)va_arg( args, int64_t * );
1133 /* if (p_sys->i_pts < p_sys->i_start_pts)
1134 *pi64 = p_sys->i_start_pts;
1136 *pi64 = p_sys->i_pts;
1139 case DEMUX_GET_TITLE_INFO:
1140 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1142 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1143 int *pi_int = (int*)va_arg( args, int* );
1146 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1148 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1152 return VLC_EGENERIC;
1154 case DEMUX_SET_TITLE:
1155 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1159 return VLC_EGENERIC;
1161 case DEMUX_SET_SEEKPOINT:
1162 /* FIXME do a better implementation */
1163 i_skp = (int)va_arg( args, int );
1165 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1167 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1);
1168 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1169 p_demux->info.i_seekpoint = i_skp;
1170 /* p_sys->i_current_chapter = i_skp;*/
1173 return VLC_EGENERIC;
1176 case DEMUX_SET_TIME:
1179 return VLC_EGENERIC;
1183 static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1185 demux_sys_t *p_sys = p_demux->p_sys;
1196 if( p_demux->b_die )
1198 return VLC_EGENERIC;
1201 el = p_sys->ep->Get();
1202 i_level = p_sys->ep->GetLevel();
1204 if( el == NULL && *pp_block != NULL )
1206 /* update the index */
1207 #define idx p_sys->index[p_sys->i_index - 1]
1208 if( p_sys->i_index > 0 && idx.i_time == -1 )
1210 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1211 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1219 if( p_sys->ep->GetLevel() > 1 )
1224 msg_Warn( p_demux, "EOF" );
1225 return VLC_EGENERIC;
1231 if( MKV_IS_ID( el, KaxCluster ) )
1233 p_sys->cluster = (KaxCluster*)el;
1235 /* add it to the index */
1236 if( p_sys->i_index == 0 ||
1237 ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
1239 IndexAppendCluster( p_demux, p_sys->cluster );
1244 else if( MKV_IS_ID( el, KaxCues ) )
1246 msg_Warn( p_demux, "find KaxCues FIXME" );
1247 return VLC_EGENERIC;
1251 msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
1254 else if( i_level == 2 )
1256 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1258 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1260 ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
1261 p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
1263 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1268 else if( i_level == 3 )
1270 if( MKV_IS_ID( el, KaxBlock ) )
1272 *pp_block = (KaxBlock*)el;
1274 (*pp_block)->ReadData( p_sys->es->I_O() );
1275 (*pp_block)->SetParent( *p_sys->cluster );
1279 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1281 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1283 dur.ReadData( p_sys->es->I_O() );
1284 *pi_duration = uint64( dur );
1286 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1288 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1290 ref.ReadData( p_sys->es->I_O() );
1291 if( *pi_ref1 == -1 )
1293 *pi_ref1 = int64( ref );
1297 *pi_ref2 = int64( ref );
1303 msg_Err( p_demux, "invalid level = %d", i_level );
1304 return VLC_EGENERIC;
1309 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1312 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1313 memcpy( p_block->p_buffer, p_mem, i_mem );
1314 //p_block->i_rate = p_input->stream.control.i_rate;
1318 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1319 mtime_t i_duration )
1321 demux_sys_t *p_sys = p_demux->p_sys;
1327 #define tk p_sys->track[i_track]
1328 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1330 if( tk.i_number == block->TrackNum() )
1336 if( i_track >= p_sys->i_track )
1338 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1341 if( tk.p_es == NULL )
1343 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1346 if( i_pts < p_sys->i_start_pts && tk.fmt.i_cat == AUDIO_ES )
1348 return; /* discard audio packets that shouldn't be rendered */
1351 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );
1354 tk.b_inited = VLC_FALSE;
1358 /* First send init data */
1359 if( !tk.b_inited && tk.i_data_init > 0 )
1363 msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );
1364 p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );
1365 if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );
1367 tk.b_inited = VLC_TRUE;
1370 for( i = 0; i < block->NumberFrames(); i++ )
1373 DataBuffer &data = block->GetBuffer(i);
1375 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1377 if( p_block == NULL )
1382 #if defined(HAVE_ZLIB_H)
1383 if( tk.i_compression_type )
1385 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1389 if (p_sys->i_start_pts > i_pts)
1392 p_block->i_pts = -1;
1395 if( tk.fmt.i_cat != VIDEO_ES )
1397 p_block->i_dts = p_block->i_pts = i_pts;
1401 p_block->i_dts = i_pts;
1405 if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )
1407 p_block->i_length = i_duration * 1000;
1409 es_out_Send( p_demux->out, tk.p_es, p_block );
1411 /* use time stamp only for first block */
1418 static void UpdateCurrentChapter()
1420 /* update current chapter/seekpoint */
1423 if (p_sys->title->seekpoint[i_skp]->i_time_offset)
1425 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1426 p_demux->info.i_seekpoint = i_chapter;
1431 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent)
1433 demux_sys_t *p_sys = p_demux->p_sys;
1436 int64_t i_block_duration;
1437 int64_t i_block_ref1;
1438 int64_t i_block_ref2;
1441 int i_track_skipping;
1444 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1445 if( i_date < 0 && f_percent < 0 )
1447 msg_Warn( p_demux, "cannot seek nowhere !" );
1450 if( f_percent > 1.0 )
1452 msg_Warn( p_demux, "cannot seek so far !" );
1457 p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1458 p_sys->cluster = NULL;
1460 /* seek without index or without date */
1461 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
1463 if (p_sys->f_duration >= 0)
1465 i_date = f_percent * p_sys->f_duration * 1000;
1469 int64_t i_pos = f_percent * stream_Size( p_demux->s );
1471 msg_Dbg( p_demux, "inacurate way of seeking" );
1472 for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1474 if( p_sys->index[i_index].i_position >= i_pos)
1479 if( i_index == p_sys->i_index )
1484 i_date = p_sys->index[i_index].i_time;
1487 if( p_sys->index[i_index].i_position < i_pos )
1491 msg_Warn( p_demux, "searching for cluster, could take some time" );
1493 /* search a cluster */
1494 while( ( el = p_sys->ep->Get() ) != NULL )
1496 if( MKV_IS_ID( el, KaxCluster ) )
1498 KaxCluster *cluster = (KaxCluster*)el;
1500 /* add it to the index */
1501 IndexAppendCluster( p_demux, cluster );
1503 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1505 p_sys->cluster = cluster;
1516 for( ; i_index < p_sys->i_index; i_index++ )
1518 if( p_sys->index[i_index].i_time > i_date )
1529 msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1530 p_sys->index[i_index].i_time,
1531 (int)( 100 * p_sys->index[i_index].i_position /
1532 stream_Size( p_demux->s ) ) );
1534 p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1538 /* now parse until key frame */
1539 #define tk p_sys->track[i_track]
1540 i_track_skipping = 0;
1541 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1543 if( tk.fmt.i_cat == VIDEO_ES )
1545 tk.b_search_keyframe = VLC_TRUE;
1550 p_sys->i_start_pts = i_date;
1552 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1554 while( i_track_skipping > 0 )
1556 if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1558 msg_Warn( p_demux, "cannot get block EOF?" );
1563 p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
1565 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1567 if( tk.i_number == block->TrackNum() )
1573 if( i_track < p_sys->i_track )
1575 if( tk.fmt.i_cat == VIDEO_ES )
1577 if( i_block_ref1 == -1 && tk.b_search_keyframe )
1579 tk.b_search_keyframe = VLC_FALSE;
1582 if( !tk.b_search_keyframe )
1584 BlockDecode( p_demux, block, 0, 0 );
1594 /*****************************************************************************
1595 * Demux: reads and demuxes data packets
1596 *****************************************************************************
1597 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1598 *****************************************************************************/
1599 static int Demux( demux_t *p_demux)
1601 demux_sys_t *p_sys = p_demux->p_sys;
1602 mtime_t i_start_pts;
1603 int i_block_count = 0;
1607 int64_t i_block_duration;
1608 int64_t i_block_ref1;
1609 int64_t i_block_ref2;
1615 if ( p_sys->editions[p_sys->i_current_edition].b_ordered )
1617 /* 1st, we need to know in which chapter we are */
1619 /* check if we need to silently seek to a new location in the stream */
1620 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1621 /* only seek after each duration >= end timecode of the current chapter */
1624 if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1626 msg_Warn( p_demux, "cannot get block EOF?" );
1631 p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
1633 if( p_sys->i_pts >= p_sys->i_start_pts )
1635 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1638 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1640 UpdateCurrentChapter();
1645 if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )
1654 /*****************************************************************************
1656 *****************************************************************************/
1657 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1663 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1665 if( i_size <= 0 || mb_eof )
1670 return stream_Read( s, p_buffer, i_size );
1672 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1678 case seek_beginning:
1682 i_pos = stream_Size( s ) - i_offset;
1685 i_pos= stream_Tell( s ) + i_offset;
1689 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1696 if( stream_Seek( s, i_pos ) )
1702 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1706 uint64 vlc_stream_io_callback::getFilePointer( void )
1708 return stream_Tell( s );
1710 void vlc_stream_io_callback::close( void )
1716 /*****************************************************************************
1717 * Ebml Stream parser
1718 *****************************************************************************/
1719 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1727 for( i = 1; i < 6; i++ )
1733 mb_keep = VLC_FALSE;
1736 EbmlParser::~EbmlParser( void )
1740 for( i = 1; i < mi_level; i++ )
1746 mb_keep = VLC_FALSE;
1750 void EbmlParser::Up( void )
1752 if( mi_user_level == mi_level )
1754 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1760 void EbmlParser::Down( void )
1766 void EbmlParser::Keep( void )
1771 int EbmlParser::GetLevel( void )
1773 return mi_user_level;
1776 EbmlElement *EbmlParser::Get( void )
1780 if( mi_user_level != mi_level )
1786 EbmlElement *ret = m_got;
1792 if( m_el[mi_level] )
1794 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1797 delete m_el[mi_level];
1799 mb_keep = VLC_FALSE;
1802 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1813 delete m_el[mi_level - 1];
1814 m_got = m_el[mi_level -1] = m_el[mi_level];
1815 m_el[mi_level] = NULL;
1822 else if( m_el[mi_level] == NULL )
1824 fprintf( stderr," m_el[mi_level] == NULL\n" );
1827 return m_el[mi_level];
1831 /*****************************************************************************
1833 * * LoadCues : load the cues element and update index
1835 * * LoadTags : load ... the tags element
1837 * * InformationCreate : create all information, load tags if present
1839 *****************************************************************************/
1840 static void LoadCues( demux_t *p_demux )
1842 demux_sys_t *p_sys = p_demux->p_sys;
1843 int64_t i_sav_position = p_sys->in->getFilePointer();
1845 EbmlElement *el, *cues;
1847 msg_Dbg( p_demux, "loading cues" );
1848 p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1849 cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1853 msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1854 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1858 ep = new EbmlParser( p_sys->es, cues );
1859 while( ( el = ep->Get() ) != NULL )
1861 if( MKV_IS_ID( el, KaxCuePoint ) )
1863 #define idx p_sys->index[p_sys->i_index]
1866 idx.i_block_number= -1;
1867 idx.i_position = -1;
1869 idx.b_key = VLC_TRUE;
1872 while( ( el = ep->Get() ) != NULL )
1874 if( MKV_IS_ID( el, KaxCueTime ) )
1876 KaxCueTime &ctime = *(KaxCueTime*)el;
1878 ctime.ReadData( p_sys->es->I_O() );
1880 idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1882 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1885 while( ( el = ep->Get() ) != NULL )
1887 if( MKV_IS_ID( el, KaxCueTrack ) )
1889 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1891 ctrack.ReadData( p_sys->es->I_O() );
1892 idx.i_track = uint16( ctrack );
1894 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1896 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1898 ccpos.ReadData( p_sys->es->I_O() );
1899 idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1901 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1903 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1905 cbnum.ReadData( p_sys->es->I_O() );
1906 idx.i_block_number = uint32( cbnum );
1910 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1917 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1923 msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
1924 " track=%d bnum=%d", idx.i_time, idx.i_position,
1925 idx.i_track, idx.i_block_number );
1929 if( p_sys->i_index >= p_sys->i_index_max )
1931 p_sys->i_index_max += 1024;
1932 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
1938 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1944 p_sys->b_cues = VLC_TRUE;
1946 msg_Dbg( p_demux, "loading cues done." );
1947 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1950 static void LoadTags( demux_t *p_demux )
1952 demux_sys_t *p_sys = p_demux->p_sys;
1953 int64_t i_sav_position = p_sys->in->getFilePointer();
1955 EbmlElement *el, *tags;
1957 msg_Dbg( p_demux, "loading tags" );
1958 p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
1959 tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
1963 msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
1964 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1968 msg_Dbg( p_demux, "Tags" );
1969 ep = new EbmlParser( p_sys->es, tags );
1970 while( ( el = ep->Get() ) != NULL )
1972 if( MKV_IS_ID( el, KaxTag ) )
1974 msg_Dbg( p_demux, "+ Tag" );
1976 while( ( el = ep->Get() ) != NULL )
1978 if( MKV_IS_ID( el, KaxTagTargets ) )
1980 msg_Dbg( p_demux, "| + Targets" );
1982 while( ( el = ep->Get() ) != NULL )
1984 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
1988 else if( MKV_IS_ID( el, KaxTagGeneral ) )
1990 msg_Dbg( p_demux, "| + General" );
1992 while( ( el = ep->Get() ) != NULL )
1994 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
1998 else if( MKV_IS_ID( el, KaxTagGenres ) )
2000 msg_Dbg( p_demux, "| + Genres" );
2002 while( ( el = ep->Get() ) != NULL )
2004 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2008 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2010 msg_Dbg( p_demux, "| + Audio Specific" );
2012 while( ( el = ep->Get() ) != NULL )
2014 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2018 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2020 msg_Dbg( p_demux, "| + Images Specific" );
2022 while( ( el = ep->Get() ) != NULL )
2024 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2028 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2030 msg_Dbg( p_demux, "| + Multi Comment" );
2032 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2034 msg_Dbg( p_demux, "| + Multi Commercial" );
2036 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2038 msg_Dbg( p_demux, "| + Multi Date" );
2040 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2042 msg_Dbg( p_demux, "| + Multi Entity" );
2044 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2046 msg_Dbg( p_demux, "| + Multi Identifier" );
2048 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2050 msg_Dbg( p_demux, "| + Multi Legal" );
2052 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2054 msg_Dbg( p_demux, "| + Multi Title" );
2058 msg_Dbg( p_demux, "| + Unknown (%s)", typeid( *el ).name() );
2065 msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
2071 msg_Dbg( p_demux, "loading tags done." );
2072 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2075 /*****************************************************************************
2077 *****************************************************************************/
2078 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
2080 demux_sys_t *p_sys = p_demux->p_sys;
2084 int i_upper_level = 0;
2086 msg_Dbg( p_demux, "| + Seek head" );
2088 /* Master elements */
2089 m = static_cast<EbmlMaster *>(seekhead);
2090 m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
2092 for( i = 0; i < m->ListSize(); i++ )
2094 EbmlElement *l = (*m)[i];
2096 if( MKV_IS_ID( l, KaxSeek ) )
2098 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2099 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2104 for( j = 0; j < sk->ListSize(); j++ )
2106 EbmlElement *l = (*sk)[j];
2108 if( MKV_IS_ID( l, KaxSeekID ) )
2110 KaxSeekID &sid = *(KaxSeekID*)l;
2111 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2113 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2115 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2116 i_pos = uint64( spos );
2120 msg_Dbg( p_demux, "| | | + Unknown (%s)", typeid(*l).name() );
2126 if( id == KaxCues::ClassInfos.GlobalId )
2128 msg_Dbg( p_demux, "| | | = cues at "I64Fd, i_pos );
2129 p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
2131 else if( id == KaxChapters::ClassInfos.GlobalId )
2133 msg_Dbg( p_demux, "| | | = chapters at "I64Fd, i_pos );
2134 p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
2136 else if( id == KaxTags::ClassInfos.GlobalId )
2138 msg_Dbg( p_demux, "| | | = tags at "I64Fd, i_pos );
2139 p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
2145 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2150 /*****************************************************************************
2152 *****************************************************************************/
2153 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
2155 demux_sys_t *p_sys = p_demux->p_sys;
2160 msg_Dbg( p_demux, "| | + Track Entry" );
2163 p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
2165 /* Init the track */
2166 tk = &p_sys->track[p_sys->i_track - 1];
2168 memset( tk, 0, sizeof( mkv_track_t ) );
2170 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2171 tk->fmt.psz_language = strdup("English");
2172 tk->fmt.psz_description = NULL;
2174 tk->b_default = VLC_TRUE;
2175 tk->b_enabled = VLC_TRUE;
2176 tk->i_number = p_sys->i_track - 1;
2177 tk->i_extra_data = 0;
2178 tk->p_extra_data = NULL;
2179 tk->psz_codec = NULL;
2180 tk->i_default_duration = 0;
2181 tk->f_timecodescale = 1.0;
2183 tk->b_inited = VLC_FALSE;
2184 tk->i_data_init = 0;
2185 tk->p_data_init = NULL;
2187 tk->psz_codec_name = NULL;
2188 tk->psz_codec_settings = NULL;
2189 tk->psz_codec_info_url = NULL;
2190 tk->psz_codec_download_url = NULL;
2192 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2194 for( i = 0; i < m->ListSize(); i++ )
2196 EbmlElement *l = (*m)[i];
2198 if( MKV_IS_ID( l, KaxTrackNumber ) )
2200 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2202 tk->i_number = uint32( tnum );
2203 msg_Dbg( p_demux, "| | | + Track Number=%u", uint32( tnum ) );
2205 else if( MKV_IS_ID( l, KaxTrackUID ) )
2207 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2209 msg_Dbg( p_demux, "| | | + Track UID=%u", uint32( tuid ) );
2211 else if( MKV_IS_ID( l, KaxTrackType ) )
2214 KaxTrackType &ttype = *(KaxTrackType*)l;
2216 switch( uint8(ttype) )
2220 tk->fmt.i_cat = AUDIO_ES;
2224 tk->fmt.i_cat = VIDEO_ES;
2226 case track_subtitle:
2227 psz_type = "subtitle";
2228 tk->fmt.i_cat = SPU_ES;
2231 psz_type = "unknown";
2232 tk->fmt.i_cat = UNKNOWN_ES;
2236 msg_Dbg( p_demux, "| | | + Track Type=%s", psz_type );
2238 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2240 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2242 // tk->b_enabled = uint32( fenb );
2243 // msg_Dbg( p_demux, "| | | + Track Enabled=%u",
2244 // uint32( fenb ) );
2246 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2248 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2250 tk->b_default = uint32( fdef );
2251 msg_Dbg( p_demux, "| | | + Track Default=%u", uint32( fdef ) );
2253 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2255 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2257 msg_Dbg( p_demux, "| | | + Track Lacing=%d", uint32( lac ) );
2259 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2261 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2263 msg_Dbg( p_demux, "| | | + Track MinCache=%d", uint32( cmin ) );
2265 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2267 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2269 msg_Dbg( p_demux, "| | | + Track MaxCache=%d", uint32( cmax ) );
2271 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2273 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2275 tk->i_default_duration = uint64(defd);
2276 msg_Dbg( p_demux, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2278 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2280 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2282 tk->f_timecodescale = float( ttcs );
2283 msg_Dbg( p_demux, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2285 else if( MKV_IS_ID( l, KaxTrackName ) )
2287 KaxTrackName &tname = *(KaxTrackName*)l;
2289 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2290 msg_Dbg( p_demux, "| | | + Track Name=%s", tk->fmt.psz_description );
2292 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2294 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2296 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2298 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2300 else if( MKV_IS_ID( l, KaxCodecID ) )
2302 KaxCodecID &codecid = *(KaxCodecID*)l;
2304 tk->psz_codec = strdup( string( codecid ).c_str() );
2305 msg_Dbg( p_demux, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2307 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2309 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2311 tk->i_extra_data = cpriv.GetSize();
2312 if( tk->i_extra_data > 0 )
2314 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2315 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2317 msg_Dbg( p_demux, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2319 else if( MKV_IS_ID( l, KaxCodecName ) )
2321 KaxCodecName &cname = *(KaxCodecName*)l;
2323 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2324 msg_Dbg( p_demux, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2326 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2328 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2329 MkvTree( p_demux, 3, "Content Encodings" );
2330 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2332 EbmlElement *l2 = (*cencs)[i];
2333 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2335 MkvTree( p_demux, 4, "Content Encoding" );
2336 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2337 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2339 EbmlElement *l3 = (*cenc)[i];
2340 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2342 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2343 MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2345 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2347 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2348 MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2350 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2352 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2353 MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2355 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2357 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2358 MkvTree( p_demux, 5, "Content Compression" );
2359 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2361 EbmlElement *l4 = (*compr)[i];
2362 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2364 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2365 MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2366 if( uint32( compalg ) == 0 )
2368 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2373 MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2380 MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2387 MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2392 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2394 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2396 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2397 // msg_Dbg( p_demux, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2399 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2401 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2403 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2404 // msg_Dbg( p_demux, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2406 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2408 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2410 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2411 // msg_Dbg( p_demux, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2413 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2415 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2417 // msg_Dbg( p_demux, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2419 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2421 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2423 // msg_Dbg( p_demux, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2425 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2427 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2430 msg_Dbg( p_demux, "| | | + Track Video" );
2433 for( j = 0; j < tkv->ListSize(); j++ )
2435 EbmlElement *l = (*tkv)[j];
2436 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2438 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2440 // msg_Dbg( p_demux, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2442 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2444 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2446 // msg_Dbg( p_demux, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2449 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2451 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2453 tk->fmt.video.i_width = uint16( vwidth );
2454 msg_Dbg( p_demux, "| | | | + width=%d", uint16( vwidth ) );
2456 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2458 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2460 tk->fmt.video.i_height = uint16( vheight );
2461 msg_Dbg( p_demux, "| | | | + height=%d", uint16( vheight ) );
2463 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2465 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2467 tk->fmt.video.i_visible_width = uint16( vwidth );
2468 msg_Dbg( p_demux, "| | | | + display width=%d", uint16( vwidth ) );
2470 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2472 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2474 tk->fmt.video.i_visible_height = uint16( vheight );
2475 msg_Dbg( p_demux, "| | | | + display height=%d", uint16( vheight ) );
2477 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2479 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2481 tk->f_fps = float( vfps );
2482 msg_Dbg( p_demux, " | | | + fps=%f", float( vfps ) );
2484 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2486 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2488 // msg_Dbg( p_demux, "| | | | + Track Video Display Unit=%s",
2489 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2491 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2493 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2495 // msg_Dbg( p_demux, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2497 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2499 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2501 // msg_Dbg( p_demux, " | | | + fps=%f", float( gamma ) );
2505 msg_Dbg( p_demux, "| | | | + Unknown (%s)", typeid(*l).name() );
2509 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2511 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2514 msg_Dbg( p_demux, "| | | + Track Audio" );
2516 for( j = 0; j < tka->ListSize(); j++ )
2518 EbmlElement *l = (*tka)[j];
2520 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2522 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2524 tk->fmt.audio.i_rate = (int)float( afreq );
2525 msg_Dbg( p_demux, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2527 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2529 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2531 tk->fmt.audio.i_channels = uint8( achan );
2532 msg_Dbg( p_demux, "| | | | + achan=%u", uint8( achan ) );
2534 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2536 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2538 tk->fmt.audio.i_bitspersample = uint8( abits );
2539 msg_Dbg( p_demux, "| | | | + abits=%u", uint8( abits ) );
2543 msg_Dbg( p_demux, "| | | | + Unknown (%s)", typeid(*l).name() );
2549 msg_Dbg( p_demux, "| | | + Unknown (%s)",
2550 typeid(*l).name() );
2555 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2557 demux_sys_t *p_sys = p_demux->p_sys;
2561 int i_upper_level = 0;
2563 msg_Dbg( p_demux, "| + Tracks" );
2565 /* Master elements */
2566 m = static_cast<EbmlMaster *>(tracks);
2567 m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2569 for( i = 0; i < m->ListSize(); i++ )
2571 EbmlElement *l = (*m)[i];
2573 if( MKV_IS_ID( l, KaxTrackEntry ) )
2575 ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2579 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2584 /*****************************************************************************
2586 *****************************************************************************/
2587 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2589 demux_sys_t *p_sys = p_demux->p_sys;
2593 int i_upper_level = 0;
2595 msg_Dbg( p_demux, "| + Information" );
2597 /* Master elements */
2598 m = static_cast<EbmlMaster *>(info);
2599 m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2601 for( i = 0; i < m->ListSize(); i++ )
2603 EbmlElement *l = (*m)[i];
2605 if( MKV_IS_ID( l, KaxSegmentUID ) )
2607 p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2609 msg_Dbg( p_demux, "| | + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
2611 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2613 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2615 p_sys->i_timescale = uint64(tcs);
2617 msg_Dbg( p_demux, "| | + TimecodeScale="I64Fd,
2618 p_sys->i_timescale );
2620 else if( MKV_IS_ID( l, KaxDuration ) )
2622 KaxDuration &dur = *(KaxDuration*)l;
2624 p_sys->f_duration = float(dur);
2626 msg_Dbg( p_demux, "| | + Duration=%f",
2627 p_sys->f_duration );
2629 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2631 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2633 p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2635 msg_Dbg( p_demux, "| | + Muxing Application=%s",
2636 p_sys->psz_muxing_application );
2638 else if( MKV_IS_ID( l, KaxWritingApp ) )
2640 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2642 p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2644 msg_Dbg( p_demux, "| | + Writing Application=%s",
2645 p_sys->psz_writing_application );
2647 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2649 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2651 p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2653 msg_Dbg( p_demux, "| | + Segment Filename=%s",
2654 p_sys->psz_segment_filename );
2656 else if( MKV_IS_ID( l, KaxTitle ) )
2658 KaxTitle &title = *(KaxTitle*)l;
2660 p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2662 msg_Dbg( p_demux, "| | + Title=%s", p_sys->psz_title );
2664 if( MKV_IS_ID( l, KaxSegmentFamily ) )
2666 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2668 p_sys->families.push_back(*uid);
2670 msg_Dbg( p_demux, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2672 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2673 else if( MKV_IS_ID( l, KaxDateUTC ) )
2675 KaxDateUTC &date = *(KaxDateUTC*)l;
2680 i_date = date.GetEpochDate();
2681 memset( buffer, 0, 256 );
2682 if( gmtime_r( &i_date, &tmres ) &&
2683 asctime_r( &tmres, buffer ) )
2685 buffer[strlen( buffer)-1]= '\0';
2686 p_sys->psz_date_utc = strdup( buffer );
2687 msg_Dbg( p_demux, "| | + Date=%s", p_sys->psz_date_utc );
2693 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2697 p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
2701 /*****************************************************************************
2703 *****************************************************************************/
2704 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2706 demux_sys_t *p_sys = p_demux->p_sys;
2709 bool b_display_seekpoint = true;
2711 if( p_sys->title == NULL )
2713 p_sys->title = vlc_input_title_New();
2715 sk = vlc_seekpoint_New();
2717 sk->i_level = i_level;
2719 msg_Dbg( p_demux, "| | | + ChapterAtom (level=%d)", i_level );
2720 for( i = 0; i < ca->ListSize(); i++ )
2722 EbmlElement *l = (*ca)[i];
2724 if( MKV_IS_ID( l, KaxChapterUID ) )
2726 KaxChapterUID &uid = *(KaxChapterUID*)l;
2727 uint32_t i_uid = uint32( uid );
2728 msg_Dbg( p_demux, "| | | | + ChapterUID: 0x%x", i_uid );
2730 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2732 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2733 b_display_seekpoint = uint8( flag ) == 0;
2735 msg_Dbg( p_demux, "| | | | + ChapterFlagHidden: %s", b_display_seekpoint ? "no":"yes" );
2737 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2739 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2740 sk->i_time_offset = uint64( start ) / I64C(1000);
2742 msg_Dbg( p_demux, "| | | | + ChapterTimeStart: %lld", sk->i_time_offset );
2744 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2746 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2747 int64_t i_end = uint64( end );
2749 msg_Dbg( p_demux, "| | | | + ChapterTimeEnd: %lld", i_end );
2751 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2753 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2756 msg_Dbg( p_demux, "| | | | + ChapterDisplay" );
2757 for( j = 0; j < cd->ListSize(); j++ )
2759 EbmlElement *l= (*cd)[j];
2761 if( MKV_IS_ID( l, KaxChapterString ) )
2766 KaxChapterString &name =*(KaxChapterString*)l;
2767 for (k = 0; k < i_level; k++)
2770 psz += UTF8ToStr( UTFstring( name ) );
2771 sk->psz_name = strdup( psz.c_str() );
2772 msg_Dbg( p_demux, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2774 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2776 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2777 const char *psz = string( lang ).c_str();
2779 msg_Dbg( p_demux, "| | | | | + ChapterLanguage '%s'", psz );
2781 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2783 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2784 const char *psz = string( ct ).c_str();
2786 msg_Dbg( p_demux, "| | | | | + ChapterCountry '%s'", psz );
2790 else if( MKV_IS_ID( l, KaxChapterAtom ) )
2792 chapter_item_t new_sub_chapter;
2793 ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
2794 chapters.sub_chapters.push_back( new_sub_chapter );
2798 if (b_display_seekpoint)
2800 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2801 p_sys->title->i_seekpoint++;
2802 p_sys->title->seekpoint = (seekpoint_t**)realloc( p_sys->title->seekpoint, p_sys->title->i_seekpoint * sizeof( seekpoint_t* ) );
2803 p_sys->title->seekpoint[p_sys->title->i_seekpoint-1] = sk;
2807 vlc_seekpoint_Delete(sk);
2811 /*****************************************************************************
2813 *****************************************************************************/
2814 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2816 demux_sys_t *p_sys = p_demux->p_sys;
2820 int i_upper_level = 0;
2821 int i_default_edition = 0;
2823 /* Master elements */
2824 m = static_cast<EbmlMaster *>(chapters);
2825 m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2827 for( i = 0; i < m->ListSize(); i++ )
2829 EbmlElement *l = (*m)[i];
2831 if( MKV_IS_ID( l, KaxEditionEntry ) )
2833 chapter_edition_t edition;
2835 EbmlMaster *E = static_cast<EbmlMaster *>(l );
2837 msg_Dbg( p_demux, "| | + EditionEntry" );
2838 for( j = 0; j < E->ListSize(); j++ )
2840 EbmlElement *l = (*E)[j];
2842 if( MKV_IS_ID( l, KaxChapterAtom ) )
2844 chapter_item_t new_sub_chapter;
2845 ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
2846 edition.chapters.push_back( new_sub_chapter );
2848 else if( MKV_IS_ID( l, KaxEditionUID ) )
2850 edition.i_uid = uint64(*static_cast<KaxEditionUID *>(l));
2852 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
2854 edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>(l)) != 0;
2856 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
2858 if (uint8(*static_cast<KaxEditionFlagDefault *>(l)) != 0)
2859 p_sys->i_current_edition = p_sys->editions.size();
2863 msg_Dbg( p_demux, "| | | + Unknown (%s)", typeid(*l).name() );
2866 p_sys->editions.push_back( edition );
2870 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2874 p_sys->i_current_edition = i_default_edition;
2876 if ( p_sys->editions[i_default_edition].b_ordered )
2878 /* update the duration of the segment according to the sum of all sub chapters */
2882 /*****************************************************************************
2883 * InformationCreate:
2884 *****************************************************************************/
2885 static void InformationCreate( demux_t *p_demux )
2887 demux_sys_t *p_sys = p_demux->p_sys;
2890 p_sys->meta = vlc_meta_New();
2892 if( p_sys->psz_title )
2894 vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2896 if( p_sys->psz_date_utc )
2898 vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2900 if( p_sys->psz_segment_filename )
2902 vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2904 if( p_sys->psz_muxing_application )
2906 vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2908 if( p_sys->psz_writing_application )
2910 vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2913 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2915 mkv_track_t *tk = &p_sys->track[i_track];
2916 vlc_meta_t *mtk = vlc_meta_New();
2918 p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2919 sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2920 p_sys->meta->track[p_sys->meta->i_track++] = mtk;
2922 if( tk->fmt.psz_description )
2924 vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
2926 if( tk->psz_codec_name )
2928 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
2930 if( tk->psz_codec_settings )
2932 vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
2934 if( tk->psz_codec_info_url )
2936 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
2938 if( tk->psz_codec_download_url )
2940 vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
2944 if( p_sys->i_tags_position >= 0 )
2946 vlc_bool_t b_seekable;
2948 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
2951 LoadTags( p_demux );
2957 /*****************************************************************************
2959 *****************************************************************************/
2961 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
2963 demux_sys_t *p_sys = p_demux->p_sys;
2965 #define idx p_sys->index[p_sys->i_index]
2967 idx.i_block_number= -1;
2968 idx.i_position = cluster->GetElementPosition();
2970 idx.b_key = VLC_TRUE;
2973 if( p_sys->i_index >= p_sys->i_index_max )
2975 p_sys->i_index_max += 1024;
2976 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2981 static char * UTF8ToStr( const UTFstring &u )
2990 p = dst = (char*)malloc( i_src + 1);