1 /*****************************************************************************
2 * mkv.cpp : matroska demuxer
3 *****************************************************************************
4 * Copyright (C) 2003-2004 VideoLAN
7 * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8 * Steve Lhomme <steve.lhomme@free.fr>
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111, USA.
23 *****************************************************************************/
25 /*****************************************************************************
27 *****************************************************************************/
28 #include <stdlib.h> /* malloc(), free() */
33 # include <time.h> /* time() */
36 #include <vlc/input.h>
38 #include <codecs.h> /* BITMAPINFOHEADER, WAVEFORMATEX */
53 /* libebml and matroska */
54 #include "ebml/EbmlHead.h"
55 #include "ebml/EbmlSubHead.h"
56 #include "ebml/EbmlStream.h"
57 #include "ebml/EbmlContexts.h"
58 #include "ebml/EbmlVoid.h"
59 #include "ebml/StdIOCallback.h"
61 #include "matroska/KaxAttachments.h"
62 #include "matroska/KaxBlock.h"
63 #include "matroska/KaxBlockData.h"
64 #include "matroska/KaxChapters.h"
65 #include "matroska/KaxCluster.h"
66 #include "matroska/KaxClusterData.h"
67 #include "matroska/KaxContexts.h"
68 #include "matroska/KaxCues.h"
69 #include "matroska/KaxCuesData.h"
70 #include "matroska/KaxInfo.h"
71 #include "matroska/KaxInfoData.h"
72 #include "matroska/KaxSeekHead.h"
73 #include "matroska/KaxSegment.h"
74 #include "matroska/KaxTag.h"
75 #include "matroska/KaxTags.h"
76 #include "matroska/KaxTagMulti.h"
77 #include "matroska/KaxTracks.h"
78 #include "matroska/KaxTrackAudio.h"
79 #include "matroska/KaxTrackVideo.h"
80 #include "matroska/KaxTrackEntryData.h"
81 #include "matroska/KaxContentEncoding.h"
83 #include "ebml/StdIOCallback.h"
86 #include "mp4/libmp4.h"
92 #define MATROSKA_COMPRESSION_NONE 0
93 #define MATROSKA_COMPRESSION_ZLIB 1
96 * What's between a directory and a filename?
99 #define DIRECTORY_SEPARATOR '\\'
101 #define DIRECTORY_SEPARATOR '/'
104 using namespace LIBMATROSKA_NAMESPACE;
107 /*****************************************************************************
109 *****************************************************************************/
110 static int Open ( vlc_object_t * );
111 static void Close( vlc_object_t * );
114 set_shortname( _("Matroska") );
115 set_description( _("Matroska stream demuxer" ) );
116 set_capability( "demux2", 50 );
117 set_callbacks( Open, Close );
118 set_category( CAT_INPUT );
119 set_subcategory( SUBCAT_INPUT_DEMUX );
121 add_bool( "mkv-seek-percent", 1, NULL,
122 N_("Seek based on percent not time"),
123 N_("Seek based on percent not time"), VLC_TRUE );
125 add_shortcut( "mka" );
126 add_shortcut( "mkv" );
129 /*****************************************************************************
131 *****************************************************************************/
133 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
134 int result, dstsize, n;
139 d_stream.zalloc = (alloc_func)0;
140 d_stream.zfree = (free_func)0;
141 d_stream.opaque = (voidpf)0;
142 result = inflateInit(&d_stream);
145 msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
149 d_stream.next_in = (Bytef *)p_in_block->p_buffer;
150 d_stream.avail_in = p_in_block->i_buffer;
152 p_block = block_New( p_this, 0 );
157 p_block = block_Realloc( p_block, 0, n * 1000 );
158 dst = (unsigned char *)p_block->p_buffer;
159 d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
160 d_stream.avail_out = 1000;
161 result = inflate(&d_stream, Z_NO_FLUSH);
162 if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
164 msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
168 while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
169 ( result != Z_STREAM_END ) );
171 dstsize = d_stream.total_out;
172 inflateEnd( &d_stream );
174 p_block = block_Realloc( p_block, 0, dstsize );
175 p_block->i_buffer = dstsize;
176 block_Release( p_in_block );
183 * Helper function to print the mkv parse tree
185 static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )
190 msg_Err( p_this, "too deep tree" );
193 va_start( args, psz_format );
194 static char *psz_foo = "| | | | | | | | | |";
195 char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
196 strncpy( psz_foo2, psz_foo, 4 * i_level );
197 psz_foo2[ 4 * i_level ] = '+';
198 psz_foo2[ 4 * i_level + 1 ] = ' ';
199 strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
200 __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );
205 /*****************************************************************************
207 *****************************************************************************/
208 class vlc_stream_io_callback: public IOCallback
215 vlc_stream_io_callback( stream_t * );
217 virtual uint32 read ( void *p_buffer, size_t i_size);
218 virtual void setFilePointer ( int64_t i_offset, seek_mode mode = seek_beginning );
219 virtual size_t write ( const void *p_buffer, size_t i_size);
220 virtual uint64 getFilePointer ( void );
221 virtual void close ( void );
224 /*****************************************************************************
226 *****************************************************************************/
230 EbmlParser( EbmlStream *es, EbmlElement *el_start );
235 EbmlElement *Get( void );
238 int GetLevel( void );
243 EbmlElement *m_el[10];
252 /*****************************************************************************
253 * Some functions to manipulate memory
254 *****************************************************************************/
255 #define GetFOURCC( p ) __GetFOURCC( (uint8_t*)p )
256 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
258 return VLC_FOURCC( p[0], p[1], p[2], p[3] );
261 /*****************************************************************************
262 * definitions of structures and functions used by this plugins
263 *****************************************************************************/
266 vlc_bool_t b_default;
267 vlc_bool_t b_enabled;
271 uint8_t *p_extra_data;
275 uint64_t i_default_duration;
276 float f_timecodescale;
284 /* data to be send first */
286 uint8_t *p_data_init;
288 /* hack : it's for seek */
289 vlc_bool_t b_search_keyframe;
292 char *psz_codec_name;
293 char *psz_codec_settings;
294 char *psz_codec_info_url;
295 char *psz_codec_download_url;
297 /* encryption/compression */
298 int i_compression_type;
319 ,i_user_start_time(-1)
322 ,b_display_seekpoint(true)
326 int64_t RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title );
327 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
329 int64_t i_start_time, i_end_time;
330 int64_t i_user_start_time, i_user_end_time; /* the time in the stream when an edition is ordered */
331 std::vector<chapter_item_t> sub_chapters;
334 bool b_display_seekpoint;
335 std::string psz_name;
336 chapter_item_t *psz_parent;
338 bool operator<( const chapter_item_t & item ) const
340 return ( i_user_start_time < item.i_user_start_time || (i_user_start_time == item.i_user_start_time && i_user_end_time < item.i_user_end_time) );
348 class chapter_edition_t
356 void RefreshChapters( input_title_t & title );
357 double Duration() const;
358 const chapter_item_t * FindTimecode( mtime_t i_timecode ) const;
360 std::vector<chapter_item_t> chapters;
377 ,i_chapters_position(0)
388 ,psz_muxing_application(NULL)
389 ,psz_writing_application(NULL)
390 ,psz_segment_filename(NULL)
395 ,i_current_edition(0)
396 ,psz_current_chapter(NULL)
399 vlc_stream_io_callback *in;
404 uint64_t i_timescale;
406 /* duration of the segment */
414 int64_t i_cues_position;
415 int64_t i_chapters_position;
416 int64_t i_tags_position;
421 KaxSegmentUID segment_uid;
425 mtime_t i_chapter_time;
433 char *psz_muxing_application;
434 char *psz_writing_application;
435 char *psz_segment_filename;
441 input_title_t *title;
443 std::vector<KaxSegmentFamily> families;
444 std::vector<KaxSegment*> family_members;
446 std::vector<chapter_edition_t> editions;
447 int i_current_edition;
448 const chapter_item_t *psz_current_chapter;
451 static int Demux ( demux_t * );
452 static int Control( demux_t *, int, va_list );
453 static void Seek ( demux_t *, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter );
455 #define MKVD_TIMECODESCALE 1000000
457 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
459 static void IndexAppendCluster ( demux_t *p_demux, KaxCluster *cluster );
460 static char *UTF8ToStr ( const UTFstring &u );
461 static void LoadCues ( demux_t * );
462 static void InformationCreate ( demux_t * );
464 static void ParseInfo( demux_t *, EbmlElement *info );
465 static void ParseTracks( demux_t *, EbmlElement *tracks );
466 static void ParseSeekHead( demux_t *, EbmlElement *seekhead );
467 static void ParseChapters( demux_t *, EbmlElement *chapters );
469 /*****************************************************************************
470 * Open: initializes matroska demux structures
471 *****************************************************************************/
472 static int Open( vlc_object_t * p_this )
474 demux_t *p_demux = (demux_t*)p_this;
477 std::string s_path, s_filename;
483 EbmlElement *el = NULL, *el1 = NULL;
485 /* peek the begining */
486 if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 ) return VLC_EGENERIC;
488 /* is a valid file */
489 if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
490 p_peek[2] != 0xdf || p_peek[3] != 0xa3 ) return VLC_EGENERIC;
492 /* Set the demux function */
493 p_demux->pf_demux = Demux;
494 p_demux->pf_control = Control;
495 p_demux->p_sys = p_sys = new demux_sys_t;
497 p_sys->in = new vlc_stream_io_callback( p_demux->s );
498 p_sys->es = new EbmlStream( *p_sys->in );
499 p_sys->f_duration = -1;
500 p_sys->i_timescale = MKVD_TIMECODESCALE;
502 p_sys->track = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
504 p_sys->i_cues_position = -1;
505 p_sys->i_chapters_position = -1;
506 p_sys->i_tags_position = -1;
508 p_sys->b_cues = VLC_FALSE;
510 p_sys->i_index_max = 1024;
511 p_sys->index = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *
512 p_sys->i_index_max );
514 p_sys->psz_muxing_application = NULL;
515 p_sys->psz_writing_application = NULL;
516 p_sys->psz_segment_filename = NULL;
517 p_sys->psz_title = NULL;
518 p_sys->psz_date_utc = NULL;;
522 if( p_sys->es == NULL )
524 msg_Err( p_demux, "failed to create EbmlStream" );
529 /* Find the EbmlHead element */
530 el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
533 msg_Err( p_demux, "cannot find EbmlHead" );
536 msg_Dbg( p_demux, "EbmlHead" );
538 el->SkipData( *p_sys->es, el->Generic().Context );
542 el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
545 msg_Err( p_demux, "cannot find KaxSegment" );
548 MkvTree( p_demux, 0, "Segment" );
549 p_sys->segment = (KaxSegment*)el;
550 p_sys->cluster = NULL;
552 p_sys->ep = new EbmlParser( p_sys->es, el );
554 while( ( el1 = p_sys->ep->Get() ) != NULL )
556 if( MKV_IS_ID( el1, KaxInfo ) )
558 ParseInfo( p_demux, el1 );
560 else if( MKV_IS_ID( el1, KaxTracks ) )
562 ParseTracks( p_demux, el1 );
564 else if( MKV_IS_ID( el1, KaxSeekHead ) )
566 ParseSeekHead( p_demux, el1 );
568 else if( MKV_IS_ID( el1, KaxCues ) )
570 msg_Dbg( p_demux, "| + Cues" );
572 else if( MKV_IS_ID( el1, KaxCluster ) )
574 msg_Dbg( p_demux, "| + Cluster" );
576 p_sys->cluster = (KaxCluster*)el1;
579 /* stop parsing the stream */
582 else if( MKV_IS_ID( el1, KaxAttachments ) )
584 msg_Dbg( p_demux, "| + Attachments FIXME TODO (but probably never supported)" );
586 else if( MKV_IS_ID( el1, KaxChapters ) )
588 msg_Dbg( p_demux, "| + Chapters" );
589 ParseChapters( p_demux, el1 );
591 else if( MKV_IS_ID( el1, KaxTag ) )
593 msg_Dbg( p_demux, "| + Tags FIXME TODO" );
597 msg_Dbg( p_demux, "| + Unknown (%s)", typeid(*el1).name() );
601 /* get the files from the same dir from the same family (based on p_demux->psz_path) */
602 /* _todo_ handle multi-segment files */
603 if (p_demux->psz_path[0] != '\0' && (!strcmp(p_demux->psz_access, "") || !strcmp(p_demux->psz_access, "")))
605 // assume it's a regular file
606 // get the directory path
607 s_path = p_demux->psz_path;
608 if (s_path.at(s_path.length() - 1) == DIRECTORY_SEPARATOR)
610 s_path = s_path.substr(0,s_path.length()-1);
614 if (s_path.find_last_of(DIRECTORY_SEPARATOR) > 0)
616 s_path = s_path.substr(0,s_path.find_last_of(DIRECTORY_SEPARATOR));
620 struct dirent *p_file_item;
621 DIR *p_src_dir = opendir(s_path.c_str());
623 if (p_src_dir != NULL)
625 while ((p_file_item = (dirent *) readdir(p_src_dir)))
627 if (strlen(p_file_item->d_name) > 4)
629 s_filename = s_path + DIRECTORY_SEPARATOR + p_file_item->d_name;
631 if (!s_filename.compare(p_demux->psz_path))
634 #if defined(__GNUC__) && (__GNUC__ < 3)
635 if (!s_filename.compare("mkv", s_filename.length() - 3, 3) ||
636 !s_filename.compare("mka", s_filename.length() - 3, 3))
638 if (!s_filename.compare(s_filename.length() - 3, 3, "mkv") ||
639 !s_filename.compare(s_filename.length() - 3, 3, "mka"))
642 // test wether this file belongs to the our family
643 bool b_keep_file_opened = false;
644 StdIOCallback *p_file_io = new StdIOCallback(s_filename.c_str(), MODE_READ);
645 EbmlStream *p_stream = new EbmlStream(*p_file_io);
646 EbmlElement *p_l0, *p_l1, *p_l2;
648 // verify the EBML Header
649 p_l0 = p_stream->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
657 p_l0->SkipData(*p_stream, EbmlHead_Context);
660 // find all segments in this file
661 p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
673 if (EbmlId(*p_l0) == KaxSegment::ClassInfos.GlobalId)
676 KaxSegmentUID *p_uid = NULL;
678 ep = new EbmlParser(p_stream, p_l0);
679 bool b_this_segment_matches = false;
680 while ((p_l1 = ep->Get()))
682 if (MKV_IS_ID(p_l1, KaxInfo))
684 // find the families of this segment
685 KaxInfo *p_info = static_cast<KaxInfo*>(p_l1);
687 p_info->Read(*p_stream, KaxInfo::ClassInfos.Context, i_upper_lvl, p_l2, true);
688 for( i = 0; i < p_info->ListSize() && !b_this_segment_matches; i++ )
690 EbmlElement *l = (*p_info)[i];
692 if( MKV_IS_ID( l, KaxSegmentUID ) )
694 p_uid = static_cast<KaxSegmentUID*>(l);
695 if (p_sys->segment_uid == *p_uid)
698 else if( MKV_IS_ID( l, KaxSegmentFamily ) )
700 KaxSegmentFamily *p_fam = static_cast<KaxSegmentFamily*>(l);
701 std::vector<KaxSegmentFamily>::iterator iter;
702 for( iter = p_sys->families.begin();
703 iter != p_sys->families.end();
706 if( *iter == *p_fam )
708 b_this_segment_matches = true;
718 if (b_this_segment_matches)
720 b_keep_file_opened = true;
724 p_l0->SkipData(*p_stream, EbmlHead_Context);
726 p_l0 = p_stream->FindNextID(KaxSegment::ClassInfos, 0xFFFFFFFFL);
729 if (!b_keep_file_opened)
737 closedir( p_src_dir );
742 if( p_sys->cluster == NULL )
744 msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
748 /* *** Load the cue if found *** */
749 if( p_sys->i_cues_position >= 0 )
751 vlc_bool_t b_seekable;
753 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
760 if( !p_sys->b_cues || p_sys->i_index <= 0 )
762 msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
764 IndexAppendCluster( p_demux, p_sys->cluster );
766 p_sys->b_cues = VLC_FALSE;
770 msg_Dbg( p_demux, "found %d es", p_sys->i_track );
771 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
773 #define tk p_sys->track[i_track]
774 if( tk.fmt.i_cat == UNKNOWN_ES )
776 msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );
781 if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
783 if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
785 msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );
786 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
790 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
792 tk.fmt.video.i_width = GetDWLE( &p_bih->biWidth );
793 tk.fmt.video.i_height= GetDWLE( &p_bih->biHeight );
794 tk.fmt.i_codec = GetFOURCC( &p_bih->biCompression );
796 tk.fmt.i_extra = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
797 if( tk.fmt.i_extra > 0 )
799 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
800 memcpy( tk.fmt.p_extra, &p_bih[1], tk.fmt.i_extra );
804 else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||
805 !strcmp( tk.psz_codec, "V_MPEG2" ) )
807 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
809 else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )
811 if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )
813 tk.fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
815 else if( !strcmp( tk.psz_codec, "V_MPEG4/ISO/AVC" ) )
817 tk.fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
818 tk.fmt.b_packetized = VLC_FALSE;
819 tk.fmt.i_extra = tk.i_extra_data;
820 tk.fmt.p_extra = malloc( tk.i_extra_data );
821 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
825 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
828 else if( !strcmp( tk.psz_codec, "V_QUICKTIME" ) )
830 MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
831 stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),
834 MP4_ReadBoxCommon( p_mp4_stream, p_box );
835 MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
836 tk.fmt.i_codec = p_box->i_type;
837 tk.fmt.video.i_width = p_box->data.p_sample_vide->i_width;
838 tk.fmt.video.i_height = p_box->data.p_sample_vide->i_height;
839 tk.fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
840 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
841 memcpy( tk.fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk.fmt.i_extra );
842 MP4_FreeBox_sample_vide( p_box );
843 stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
845 else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )
847 if( tk.i_extra_data < (int)sizeof( WAVEFORMATEX ) )
849 msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );
850 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
854 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;
856 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk.fmt.i_codec, NULL );
858 tk.fmt.audio.i_channels = GetWLE( &p_wf->nChannels );
859 tk.fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
860 tk.fmt.i_bitrate = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
861 tk.fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
862 tk.fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
864 tk.fmt.i_extra = GetWLE( &p_wf->cbSize );
865 if( tk.fmt.i_extra > 0 )
867 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
868 memcpy( tk.fmt.p_extra, &p_wf[1], tk.fmt.i_extra );
872 else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||
873 !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||
874 !strcmp( tk.psz_codec, "A_MPEG/L1" ) )
876 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
878 else if( !strcmp( tk.psz_codec, "A_AC3" ) )
880 tk.fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
882 else if( !strcmp( tk.psz_codec, "A_DTS" ) )
884 tk.fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
886 else if( !strcmp( tk.psz_codec, "A_FLAC" ) )
888 tk.fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
889 tk.fmt.i_extra = tk.i_extra_data;
890 tk.fmt.p_extra = malloc( tk.i_extra_data );
891 memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
893 else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )
895 int i, i_offset = 1, i_size[3], i_extra;
898 tk.fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
900 /* Split the 3 headers */
901 if( tk.p_extra_data[0] != 0x02 )
902 msg_Err( p_demux, "invalid vorbis header" );
904 for( i = 0; i < 2; i++ )
907 while( i_offset < tk.i_extra_data )
909 i_size[i] += tk.p_extra_data[i_offset];
910 if( tk.p_extra_data[i_offset++] != 0xff ) break;
914 i_size[0] = __MIN(i_size[0], tk.i_extra_data - i_offset);
915 i_size[1] = __MIN(i_size[1], tk.i_extra_data -i_offset -i_size[0]);
916 i_size[2] = tk.i_extra_data - i_offset - i_size[0] - i_size[1];
918 tk.fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
919 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
920 p_extra = (uint8_t *)tk.fmt.p_extra; i_extra = 0;
921 for( i = 0; i < 3; i++ )
923 *(p_extra++) = i_size[i] >> 8;
924 *(p_extra++) = i_size[i] & 0xFF;
925 memcpy( p_extra, tk.p_extra_data + i_offset + i_extra,
927 p_extra += i_size[i];
928 i_extra += i_size[i];
931 else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
932 !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
934 int i_profile, i_srate;
935 static unsigned int i_sample_rates[] =
937 96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
938 16000, 12000, 11025, 8000, 7350, 0, 0, 0
941 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
942 /* create data for faad (MP4DecSpecificDescrTag)*/
944 if( !strcmp( &tk.psz_codec[12], "MAIN" ) )
948 else if( !strcmp( &tk.psz_codec[12], "LC" ) )
952 else if( !strcmp( &tk.psz_codec[12], "SSR" ) )
961 for( i_srate = 0; i_srate < 13; i_srate++ )
963 if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )
968 msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );
971 tk.fmt.p_extra = malloc( tk.fmt.i_extra );
972 ((uint8_t*)tk.fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
973 ((uint8_t*)tk.fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk.fmt.audio.i_channels << 3);
975 else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||
976 !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||
977 !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )
979 if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )
981 tk.fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
985 tk.fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
987 tk.fmt.audio.i_blockalign = ( tk.fmt.audio.i_bitspersample + 7 ) / 8 * tk.fmt.audio.i_channels;
989 else if( !strcmp( tk.psz_codec, "A_TTA1" ) )
991 /* FIXME: support this codec */
992 msg_Err( p_demux, "TTA not supported yet[%d, n=%d]", i_track, tk.i_number );
993 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
995 else if( !strcmp( tk.psz_codec, "A_WAVPACK4" ) )
997 /* FIXME: support this codec */
998 msg_Err( p_demux, "Wavpack not supported yet[%d, n=%d]", i_track, tk.i_number );
999 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1001 else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )
1003 tk.fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1004 tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
1006 else if( !strcmp( tk.psz_codec, "S_TEXT/SSA" ) ||
1007 !strcmp( tk.psz_codec, "S_TEXT/ASS" ) ||
1008 !strcmp( tk.psz_codec, "S_SSA" ) ||
1009 !strcmp( tk.psz_codec, "S_ASS" ))
1011 tk.fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1012 tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
1014 else if( !strcmp( tk.psz_codec, "S_VOBSUB" ) )
1016 tk.fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1017 if( tk.i_extra_data )
1020 char *p_buf = (char *)malloc( tk.i_extra_data + 1);
1021 memcpy( p_buf, tk.p_extra_data , tk.i_extra_data );
1022 p_buf[tk.i_extra_data] = '\0';
1024 p_start = strstr( p_buf, "size:" );
1025 if( sscanf( p_start, "size: %dx%d",
1026 &tk.fmt.subs.spu.i_original_frame_width, &tk.fmt.subs.spu.i_original_frame_height ) == 2 )
1028 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 );
1032 msg_Warn( p_demux, "reading original frame size for vobsub failed" );
1037 else if( !strcmp( tk.psz_codec, "B_VOBBTN" ) )
1039 /* FIXME: support this codec */
1040 msg_Err( p_demux, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk.i_number );
1041 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1045 msg_Err( p_demux, "unknow codec id=`%s'", tk.psz_codec );
1046 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1050 tk.fmt.i_priority = 1000;
1053 tk.p_es = es_out_Add( p_demux->out, &tk.fmt );
1057 /* add information */
1058 InformationCreate( p_demux );
1066 return VLC_EGENERIC;
1069 /*****************************************************************************
1070 * Close: frees unused data
1071 *****************************************************************************/
1072 static void Close( vlc_object_t *p_this )
1074 demux_t *p_demux = (demux_t*)p_this;
1075 demux_sys_t *p_sys = p_demux->p_sys;
1078 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1080 #define tk p_sys->track[i_track]
1081 if( tk.fmt.psz_description )
1083 free( tk.fmt.psz_description );
1087 free( tk.psz_codec );
1089 if( tk.fmt.psz_language )
1091 free( tk.fmt.psz_language );
1095 free( p_sys->track );
1097 if( p_sys->psz_writing_application )
1099 free( p_sys->psz_writing_application );
1101 if( p_sys->psz_muxing_application )
1103 free( p_sys->psz_muxing_application );
1106 delete p_sys->segment;
1114 /*****************************************************************************
1116 *****************************************************************************/
1117 static int Control( demux_t *p_demux, int i_query, va_list args )
1119 demux_sys_t *p_sys = p_demux->p_sys;
1125 vlc_meta_t **pp_meta;
1129 case DEMUX_GET_META:
1130 pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
1131 *pp_meta = vlc_meta_Duplicate( p_sys->meta );
1134 case DEMUX_GET_LENGTH:
1135 pi64 = (int64_t*)va_arg( args, int64_t * );
1136 if( p_sys->f_duration > 0.0 )
1138 *pi64 = (int64_t)(p_sys->f_duration * 1000);
1141 return VLC_EGENERIC;
1143 case DEMUX_GET_POSITION:
1144 pf = (double*)va_arg( args, double * );
1145 /* if (p_sys->i_pts < p_sys->i_start_pts)
1146 *pf = (double)p_sys->i_start_pts / (1000.0 * p_sys->f_duration);
1148 *pf = (double)p_sys->i_pts / (1000.0 * p_sys->f_duration);
1151 case DEMUX_SET_POSITION:
1152 f = (double)va_arg( args, double );
1153 Seek( p_demux, -1, f, NULL );
1156 case DEMUX_GET_TIME:
1157 pi64 = (int64_t*)va_arg( args, int64_t * );
1158 /* if (p_sys->i_pts < p_sys->i_start_pts)
1159 *pi64 = p_sys->i_start_pts;
1161 *pi64 = p_sys->i_pts;
1164 case DEMUX_GET_TITLE_INFO:
1165 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1167 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
1168 int *pi_int = (int*)va_arg( args, int* );
1171 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
1173 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
1177 return VLC_EGENERIC;
1179 case DEMUX_SET_TITLE:
1180 /* TODO handle editions as titles & DVD titles as well */
1181 if( p_sys->title && p_sys->title->i_seekpoint > 0 )
1185 return VLC_EGENERIC;
1187 case DEMUX_SET_SEEKPOINT:
1188 /* FIXME do a better implementation */
1189 i_skp = (int)va_arg( args, int );
1191 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1193 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1, NULL);
1194 p_demux->info.i_seekpoint |= INPUT_UPDATE_SEEKPOINT;
1195 p_demux->info.i_seekpoint = i_skp;
1198 return VLC_EGENERIC;
1200 case DEMUX_GET_SEEKPOINT_TIME:
1201 i_skp = (int)va_arg( args, int );
1202 i_sk_time = (mtime_t *)va_arg( args, mtime_t * );
1203 if( p_sys->title && i_skp < p_sys->title->i_seekpoint)
1205 *i_sk_time = p_sys->title->seekpoint[i_skp]->i_time_offset;
1208 return VLC_EGENERIC;
1210 case DEMUX_SET_TIME:
1213 return VLC_EGENERIC;
1217 static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
1219 demux_sys_t *p_sys = p_demux->p_sys;
1230 if( p_demux->b_die )
1232 return VLC_EGENERIC;
1235 el = p_sys->ep->Get();
1236 i_level = p_sys->ep->GetLevel();
1238 if( el == NULL && *pp_block != NULL )
1240 /* update the index */
1241 #define idx p_sys->index[p_sys->i_index - 1]
1242 if( p_sys->i_index > 0 && idx.i_time == -1 )
1244 idx.i_time = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
1245 idx.b_key = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
1253 if( p_sys->ep->GetLevel() > 1 )
1258 msg_Warn( p_demux, "EOF" );
1259 return VLC_EGENERIC;
1265 if( MKV_IS_ID( el, KaxCluster ) )
1267 p_sys->cluster = (KaxCluster*)el;
1269 /* add it to the index */
1270 if( p_sys->i_index == 0 ||
1271 ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
1273 IndexAppendCluster( p_demux, p_sys->cluster );
1278 else if( MKV_IS_ID( el, KaxCues ) )
1280 msg_Warn( p_demux, "find KaxCues FIXME" );
1281 return VLC_EGENERIC;
1285 msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
1288 else if( i_level == 2 )
1290 if( MKV_IS_ID( el, KaxClusterTimecode ) )
1292 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1294 ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
1295 p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
1297 else if( MKV_IS_ID( el, KaxBlockGroup ) )
1302 else if( i_level == 3 )
1304 if( MKV_IS_ID( el, KaxBlock ) )
1306 *pp_block = (KaxBlock*)el;
1308 (*pp_block)->ReadData( p_sys->es->I_O() );
1309 (*pp_block)->SetParent( *p_sys->cluster );
1313 else if( MKV_IS_ID( el, KaxBlockDuration ) )
1315 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1317 dur.ReadData( p_sys->es->I_O() );
1318 *pi_duration = uint64( dur );
1320 else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1322 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1324 ref.ReadData( p_sys->es->I_O() );
1325 if( *pi_ref1 == -1 )
1327 *pi_ref1 = int64( ref );
1331 *pi_ref2 = int64( ref );
1337 msg_Err( p_demux, "invalid level = %d", i_level );
1338 return VLC_EGENERIC;
1343 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1346 if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1347 memcpy( p_block->p_buffer, p_mem, i_mem );
1348 //p_block->i_rate = p_input->stream.control.i_rate;
1352 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1353 mtime_t i_duration )
1355 demux_sys_t *p_sys = p_demux->p_sys;
1361 #define tk p_sys->track[i_track]
1362 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1364 if( tk.i_number == block->TrackNum() )
1370 if( i_track >= p_sys->i_track )
1372 msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1375 if( tk.p_es == NULL )
1377 msg_Err( p_demux, "unknown track number=%d", block->TrackNum() );
1380 if( i_pts < p_sys->i_start_pts && tk.fmt.i_cat == AUDIO_ES )
1382 return; /* discard audio packets that shouldn't be rendered */
1385 es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );
1388 tk.b_inited = VLC_FALSE;
1392 /* First send init data */
1393 if( !tk.b_inited && tk.i_data_init > 0 )
1397 msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );
1398 p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );
1399 if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );
1401 tk.b_inited = VLC_TRUE;
1404 for( i = 0; i < block->NumberFrames(); i++ )
1407 DataBuffer &data = block->GetBuffer(i);
1409 p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1411 if( p_block == NULL )
1416 #if defined(HAVE_ZLIB_H)
1417 if( tk.i_compression_type )
1419 p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1423 // TODO implement correct timestamping when B frames are used
1424 if( tk.fmt.i_cat != VIDEO_ES )
1426 p_block->i_dts = p_block->i_pts = i_pts;
1430 p_block->i_dts = i_pts;
1434 if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )
1436 p_block->i_length = i_duration * 1000;
1438 es_out_Send( p_demux->out, tk.p_es, p_block );
1440 /* use time stamp only for first block */
1447 static void UpdateCurrentToChapter( demux_t & demux )
1449 demux_sys_t & sys = *demux.p_sys;
1450 const chapter_item_t *psz_curr_chapter;
1452 /* update current chapter/seekpoint */
1453 if ( sys.editions.size())
1455 /* 1st, we need to know in which chapter we are */
1456 psz_curr_chapter = sys.editions[sys.i_current_edition].FindTimecode( sys.i_pts );
1458 /* we have moved to a new chapter */
1459 if (sys.psz_current_chapter != NULL && psz_curr_chapter != NULL && sys.psz_current_chapter != psz_curr_chapter)
1461 if (sys.psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1463 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1464 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1467 if (sys.editions[sys.i_current_edition].b_ordered )
1469 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1470 if (sys.psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1471 Seek(&demux, sys.i_pts, -1, psz_curr_chapter);
1472 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1473 /* only seek after each duration >= end timecode of the current chapter */
1476 // sys.i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1477 // sys.i_start_pts = psz_curr_chapter->i_user_start_time;
1479 sys.psz_current_chapter = psz_curr_chapter;
1483 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter)
1485 demux_sys_t *p_sys = p_demux->p_sys;
1486 mtime_t i_time_offset = 0;
1489 int64_t i_block_duration;
1490 int64_t i_block_ref1;
1491 int64_t i_block_ref2;
1494 int i_track_skipping;
1497 msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1498 if( i_date < 0 && f_percent < 0 )
1500 msg_Warn( p_demux, "cannot seek nowhere !" );
1503 if( f_percent > 1.0 )
1505 msg_Warn( p_demux, "cannot seek so far !" );
1510 p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1511 p_sys->cluster = NULL;
1513 /* seek without index or without date */
1514 if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
1516 if (p_sys->f_duration >= 0)
1518 i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1522 int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1524 msg_Dbg( p_demux, "inacurate way of seeking" );
1525 for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1527 if( p_sys->index[i_index].i_position >= i_pos)
1532 if( i_index == p_sys->i_index )
1537 i_date = p_sys->index[i_index].i_time;
1540 if( p_sys->index[i_index].i_position < i_pos )
1544 msg_Warn( p_demux, "searching for cluster, could take some time" );
1546 /* search a cluster */
1547 while( ( el = p_sys->ep->Get() ) != NULL )
1549 if( MKV_IS_ID( el, KaxCluster ) )
1551 KaxCluster *cluster = (KaxCluster*)el;
1553 /* add it to the index */
1554 IndexAppendCluster( p_demux, cluster );
1556 if( (int64_t)cluster->GetElementPosition() >= i_pos )
1558 p_sys->cluster = cluster;
1569 // find the actual time for an ordered edition
1570 if ( psz_chapter == NULL )
1572 if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
1574 /* 1st, we need to know in which chapter we are */
1575 psz_chapter = p_sys->editions[p_sys->i_current_edition].FindTimecode( i_date );
1579 if ( psz_chapter != NULL )
1581 p_sys->psz_current_chapter = psz_chapter;
1582 p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
1583 p_demux->info.i_update |= INPUT_UPDATE_SEEKPOINT;
1584 p_demux->info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
1587 for( ; i_index < p_sys->i_index; i_index++ )
1589 if( p_sys->index[i_index].i_time + i_time_offset > i_date )
1600 msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1601 p_sys->index[i_index].i_time,
1602 (int)( 100 * p_sys->index[i_index].i_position /
1603 stream_Size( p_demux->s ) ) );
1605 p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1608 p_sys->i_start_pts = i_date;
1610 es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1612 /* now parse until key frame */
1613 #define tk p_sys->track[i_track]
1614 i_track_skipping = 0;
1615 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1617 if( tk.fmt.i_cat == VIDEO_ES )
1619 tk.b_search_keyframe = VLC_TRUE;
1622 es_out_Control( p_demux->out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk.p_es, i_date );
1626 while( i_track_skipping > 0 )
1628 if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1630 msg_Warn( p_demux, "cannot get block EOF?" );
1635 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1637 if( tk.i_number == block->TrackNum() )
1643 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1645 if( i_track < p_sys->i_track )
1647 if( tk.fmt.i_cat == VIDEO_ES )
1649 if( i_block_ref1 == -1 && tk.b_search_keyframe )
1651 tk.b_search_keyframe = VLC_FALSE;
1654 if( !tk.b_search_keyframe )
1656 BlockDecode( p_demux, block, p_sys->i_pts, 0 );
1666 /*****************************************************************************
1667 * Demux: reads and demuxes data packets
1668 *****************************************************************************
1669 * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1670 *****************************************************************************/
1671 static int Demux( demux_t *p_demux)
1673 demux_sys_t *p_sys = p_demux->p_sys;
1674 int i_block_count = 0;
1677 int64_t i_block_duration;
1678 int64_t i_block_ref1;
1679 int64_t i_block_ref2;
1683 if( p_sys->i_pts >= p_sys->i_start_pts )
1684 UpdateCurrentToChapter( *p_demux );
1686 if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered && p_sys->psz_current_chapter == NULL )
1688 /* nothing left to read in this ordered edition */
1692 if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1694 if ( p_sys->editions.size() && p_sys->editions[p_sys->i_current_edition].b_ordered )
1696 // check if there are more chapters to read
1697 if ( p_sys->psz_current_chapter != NULL )
1699 p_sys->i_pts = p_sys->psz_current_chapter->i_user_end_time;
1705 msg_Warn( p_demux, "cannot get block EOF?" );
1710 p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1712 if( p_sys->i_pts >= p_sys->i_start_pts )
1714 es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1717 BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1722 // TODO optimize when there is need to leave or when seeking has been called
1723 if( i_block_count > 5 )
1732 /*****************************************************************************
1734 *****************************************************************************/
1735 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1741 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1743 if( i_size <= 0 || mb_eof )
1748 return stream_Read( s, p_buffer, i_size );
1750 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1756 case seek_beginning:
1760 i_pos = stream_Size( s ) - i_offset;
1763 i_pos= stream_Tell( s ) + i_offset;
1767 if( i_pos < 0 || i_pos >= stream_Size( s ) )
1774 if( stream_Seek( s, i_pos ) )
1780 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1784 uint64 vlc_stream_io_callback::getFilePointer( void )
1786 return stream_Tell( s );
1788 void vlc_stream_io_callback::close( void )
1794 /*****************************************************************************
1795 * Ebml Stream parser
1796 *****************************************************************************/
1797 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1805 for( i = 1; i < 6; i++ )
1811 mb_keep = VLC_FALSE;
1814 EbmlParser::~EbmlParser( void )
1818 for( i = 1; i < mi_level; i++ )
1824 mb_keep = VLC_FALSE;
1828 void EbmlParser::Up( void )
1830 if( mi_user_level == mi_level )
1832 fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1838 void EbmlParser::Down( void )
1844 void EbmlParser::Keep( void )
1849 int EbmlParser::GetLevel( void )
1851 return mi_user_level;
1854 EbmlElement *EbmlParser::Get( void )
1858 if( mi_user_level != mi_level )
1864 EbmlElement *ret = m_got;
1870 if( m_el[mi_level] )
1872 m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1875 delete m_el[mi_level];
1877 mb_keep = VLC_FALSE;
1880 m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1891 delete m_el[mi_level - 1];
1892 m_got = m_el[mi_level -1] = m_el[mi_level];
1893 m_el[mi_level] = NULL;
1900 else if( m_el[mi_level] == NULL )
1902 fprintf( stderr," m_el[mi_level] == NULL\n" );
1905 return m_el[mi_level];
1909 /*****************************************************************************
1911 * * LoadCues : load the cues element and update index
1913 * * LoadTags : load ... the tags element
1915 * * InformationCreate : create all information, load tags if present
1917 *****************************************************************************/
1918 static void LoadCues( demux_t *p_demux )
1920 demux_sys_t *p_sys = p_demux->p_sys;
1921 int64_t i_sav_position = p_sys->in->getFilePointer();
1923 EbmlElement *el, *cues;
1925 msg_Dbg( p_demux, "loading cues" );
1926 p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1927 cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1931 msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1932 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1936 ep = new EbmlParser( p_sys->es, cues );
1937 while( ( el = ep->Get() ) != NULL )
1939 if( MKV_IS_ID( el, KaxCuePoint ) )
1941 #define idx p_sys->index[p_sys->i_index]
1944 idx.i_block_number= -1;
1945 idx.i_position = -1;
1947 idx.b_key = VLC_TRUE;
1950 while( ( el = ep->Get() ) != NULL )
1952 if( MKV_IS_ID( el, KaxCueTime ) )
1954 KaxCueTime &ctime = *(KaxCueTime*)el;
1956 ctime.ReadData( p_sys->es->I_O() );
1958 idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1960 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1963 while( ( el = ep->Get() ) != NULL )
1965 if( MKV_IS_ID( el, KaxCueTrack ) )
1967 KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1969 ctrack.ReadData( p_sys->es->I_O() );
1970 idx.i_track = uint16( ctrack );
1972 else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1974 KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1976 ccpos.ReadData( p_sys->es->I_O() );
1977 idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1979 else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1981 KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1983 cbnum.ReadData( p_sys->es->I_O() );
1984 idx.i_block_number = uint32( cbnum );
1988 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1995 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2001 msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
2002 " track=%d bnum=%d", idx.i_time, idx.i_position,
2003 idx.i_track, idx.i_block_number );
2007 if( p_sys->i_index >= p_sys->i_index_max )
2009 p_sys->i_index_max += 1024;
2010 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2016 msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
2022 p_sys->b_cues = VLC_TRUE;
2024 msg_Dbg( p_demux, "loading cues done." );
2025 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2028 static void LoadTags( demux_t *p_demux )
2030 demux_sys_t *p_sys = p_demux->p_sys;
2031 int64_t i_sav_position = p_sys->in->getFilePointer();
2033 EbmlElement *el, *tags;
2035 msg_Dbg( p_demux, "loading tags" );
2036 p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
2037 tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2041 msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
2042 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2046 msg_Dbg( p_demux, "Tags" );
2047 ep = new EbmlParser( p_sys->es, tags );
2048 while( ( el = ep->Get() ) != NULL )
2050 if( MKV_IS_ID( el, KaxTag ) )
2052 msg_Dbg( p_demux, "+ Tag" );
2054 while( ( el = ep->Get() ) != NULL )
2056 if( MKV_IS_ID( el, KaxTagTargets ) )
2058 msg_Dbg( p_demux, "| + Targets" );
2060 while( ( el = ep->Get() ) != NULL )
2062 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2066 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2068 msg_Dbg( p_demux, "| + General" );
2070 while( ( el = ep->Get() ) != NULL )
2072 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2076 else if( MKV_IS_ID( el, KaxTagGenres ) )
2078 msg_Dbg( p_demux, "| + Genres" );
2080 while( ( el = ep->Get() ) != NULL )
2082 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2086 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2088 msg_Dbg( p_demux, "| + Audio Specific" );
2090 while( ( el = ep->Get() ) != NULL )
2092 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2096 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2098 msg_Dbg( p_demux, "| + Images Specific" );
2100 while( ( el = ep->Get() ) != NULL )
2102 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid( *el ).name() );
2106 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2108 msg_Dbg( p_demux, "| + Multi Comment" );
2110 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2112 msg_Dbg( p_demux, "| + Multi Commercial" );
2114 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2116 msg_Dbg( p_demux, "| + Multi Date" );
2118 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2120 msg_Dbg( p_demux, "| + Multi Entity" );
2122 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2124 msg_Dbg( p_demux, "| + Multi Identifier" );
2126 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2128 msg_Dbg( p_demux, "| + Multi Legal" );
2130 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2132 msg_Dbg( p_demux, "| + Multi Title" );
2136 msg_Dbg( p_demux, "| + Unknown (%s)", typeid( *el ).name() );
2143 msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
2149 msg_Dbg( p_demux, "loading tags done." );
2150 p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2153 /*****************************************************************************
2155 *****************************************************************************/
2156 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
2158 demux_sys_t *p_sys = p_demux->p_sys;
2162 int i_upper_level = 0;
2164 msg_Dbg( p_demux, "| + Seek head" );
2166 /* Master elements */
2167 m = static_cast<EbmlMaster *>(seekhead);
2168 m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
2170 for( i = 0; i < m->ListSize(); i++ )
2172 EbmlElement *l = (*m)[i];
2174 if( MKV_IS_ID( l, KaxSeek ) )
2176 EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2177 EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2182 for( j = 0; j < sk->ListSize(); j++ )
2184 EbmlElement *l = (*sk)[j];
2186 if( MKV_IS_ID( l, KaxSeekID ) )
2188 KaxSeekID &sid = *(KaxSeekID*)l;
2189 id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2191 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2193 KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2194 i_pos = uint64( spos );
2198 msg_Dbg( p_demux, "| | | + Unknown (%s)", typeid(*l).name() );
2204 if( id == KaxCues::ClassInfos.GlobalId )
2206 msg_Dbg( p_demux, "| | | = cues at "I64Fd, i_pos );
2207 p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
2209 else if( id == KaxChapters::ClassInfos.GlobalId )
2211 msg_Dbg( p_demux, "| | | = chapters at "I64Fd, i_pos );
2212 p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
2214 else if( id == KaxTags::ClassInfos.GlobalId )
2216 msg_Dbg( p_demux, "| | | = tags at "I64Fd, i_pos );
2217 p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
2223 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2228 /*****************************************************************************
2230 *****************************************************************************/
2231 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
2233 demux_sys_t *p_sys = p_demux->p_sys;
2238 msg_Dbg( p_demux, "| | + Track Entry" );
2241 p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
2243 /* Init the track */
2244 tk = &p_sys->track[p_sys->i_track - 1];
2246 memset( tk, 0, sizeof( mkv_track_t ) );
2248 es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2249 tk->fmt.psz_language = strdup("English");
2250 tk->fmt.psz_description = NULL;
2252 tk->b_default = VLC_TRUE;
2253 tk->b_enabled = VLC_TRUE;
2254 tk->i_number = p_sys->i_track - 1;
2255 tk->i_extra_data = 0;
2256 tk->p_extra_data = NULL;
2257 tk->psz_codec = NULL;
2258 tk->i_default_duration = 0;
2259 tk->f_timecodescale = 1.0;
2261 tk->b_inited = VLC_FALSE;
2262 tk->i_data_init = 0;
2263 tk->p_data_init = NULL;
2265 tk->psz_codec_name = NULL;
2266 tk->psz_codec_settings = NULL;
2267 tk->psz_codec_info_url = NULL;
2268 tk->psz_codec_download_url = NULL;
2270 tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2272 for( i = 0; i < m->ListSize(); i++ )
2274 EbmlElement *l = (*m)[i];
2276 if( MKV_IS_ID( l, KaxTrackNumber ) )
2278 KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2280 tk->i_number = uint32( tnum );
2281 msg_Dbg( p_demux, "| | | + Track Number=%u", uint32( tnum ) );
2283 else if( MKV_IS_ID( l, KaxTrackUID ) )
2285 KaxTrackUID &tuid = *(KaxTrackUID*)l;
2287 msg_Dbg( p_demux, "| | | + Track UID=%u", uint32( tuid ) );
2289 else if( MKV_IS_ID( l, KaxTrackType ) )
2292 KaxTrackType &ttype = *(KaxTrackType*)l;
2294 switch( uint8(ttype) )
2298 tk->fmt.i_cat = AUDIO_ES;
2302 tk->fmt.i_cat = VIDEO_ES;
2304 case track_subtitle:
2305 psz_type = "subtitle";
2306 tk->fmt.i_cat = SPU_ES;
2309 psz_type = "unknown";
2310 tk->fmt.i_cat = UNKNOWN_ES;
2314 msg_Dbg( p_demux, "| | | + Track Type=%s", psz_type );
2316 // else if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2318 // KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2320 // tk->b_enabled = uint32( fenb );
2321 // msg_Dbg( p_demux, "| | | + Track Enabled=%u",
2322 // uint32( fenb ) );
2324 else if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2326 KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2328 tk->b_default = uint32( fdef );
2329 msg_Dbg( p_demux, "| | | + Track Default=%u", uint32( fdef ) );
2331 else if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2333 KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2335 msg_Dbg( p_demux, "| | | + Track Lacing=%d", uint32( lac ) );
2337 else if( MKV_IS_ID( l, KaxTrackMinCache ) )
2339 KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2341 msg_Dbg( p_demux, "| | | + Track MinCache=%d", uint32( cmin ) );
2343 else if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2345 KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2347 msg_Dbg( p_demux, "| | | + Track MaxCache=%d", uint32( cmax ) );
2349 else if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2351 KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2353 tk->i_default_duration = uint64(defd);
2354 msg_Dbg( p_demux, "| | | + Track Default Duration="I64Fd, uint64(defd) );
2356 else if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2358 KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2360 tk->f_timecodescale = float( ttcs );
2361 msg_Dbg( p_demux, "| | | + Track TimeCodeScale=%f", tk->f_timecodescale );
2363 else if( MKV_IS_ID( l, KaxTrackName ) )
2365 KaxTrackName &tname = *(KaxTrackName*)l;
2367 tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2368 msg_Dbg( p_demux, "| | | + Track Name=%s", tk->fmt.psz_description );
2370 else if( MKV_IS_ID( l, KaxTrackLanguage ) )
2372 KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2374 tk->fmt.psz_language = strdup( string( lang ).c_str() );
2376 "| | | + Track Language=`%s'", tk->fmt.psz_language );
2378 else if( MKV_IS_ID( l, KaxCodecID ) )
2380 KaxCodecID &codecid = *(KaxCodecID*)l;
2382 tk->psz_codec = strdup( string( codecid ).c_str() );
2383 msg_Dbg( p_demux, "| | | + Track CodecId=%s", string( codecid ).c_str() );
2385 else if( MKV_IS_ID( l, KaxCodecPrivate ) )
2387 KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2389 tk->i_extra_data = cpriv.GetSize();
2390 if( tk->i_extra_data > 0 )
2392 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2393 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2395 msg_Dbg( p_demux, "| | | + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2397 else if( MKV_IS_ID( l, KaxCodecName ) )
2399 KaxCodecName &cname = *(KaxCodecName*)l;
2401 tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2402 msg_Dbg( p_demux, "| | | + Track Codec Name=%s", tk->psz_codec_name );
2404 else if( MKV_IS_ID( l, KaxContentEncodings ) )
2406 EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2407 MkvTree( p_demux, 3, "Content Encodings" );
2408 for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2410 EbmlElement *l2 = (*cencs)[i];
2411 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2413 MkvTree( p_demux, 4, "Content Encoding" );
2414 EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2415 for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2417 EbmlElement *l3 = (*cenc)[i];
2418 if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2420 KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2421 MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2423 else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2425 KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2426 MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2428 else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2430 KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2431 MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2433 else if( MKV_IS_ID( l3, KaxContentCompression ) )
2435 EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2436 MkvTree( p_demux, 5, "Content Compression" );
2437 for( unsigned int i = 0; i < compr->ListSize(); i++ )
2439 EbmlElement *l4 = (*compr)[i];
2440 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2442 KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2443 MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2444 if( uint32( compalg ) == 0 )
2446 tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2451 MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2458 MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2465 MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2470 // else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2472 // KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2474 // tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2475 // msg_Dbg( p_demux, "| | | + Track Codec Settings=%s", tk->psz_codec_settings );
2477 // else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2479 // KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2481 // tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2482 // msg_Dbg( p_demux, "| | | + Track Codec Info URL=%s", tk->psz_codec_info_url );
2484 // else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2486 // KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2488 // tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2489 // msg_Dbg( p_demux, "| | | + Track Codec Info URL=%s", tk->psz_codec_download_url );
2491 // else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2493 // KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2495 // msg_Dbg( p_demux, "| | | + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2497 // else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2499 // KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2501 // msg_Dbg( p_demux, "| | | + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2503 else if( MKV_IS_ID( l, KaxTrackVideo ) )
2505 EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2508 msg_Dbg( p_demux, "| | | + Track Video" );
2511 for( j = 0; j < tkv->ListSize(); j++ )
2513 EbmlElement *l = (*tkv)[j];
2514 // if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2516 // KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2518 // msg_Dbg( p_demux, "| | | | + Track Video Interlaced=%u", uint8( fint ) );
2520 // else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2522 // KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2524 // msg_Dbg( p_demux, "| | | | + Track Video Stereo Mode=%u", uint8( stereo ) );
2527 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2529 KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2531 tk->fmt.video.i_width = uint16( vwidth );
2532 msg_Dbg( p_demux, "| | | | + width=%d", uint16( vwidth ) );
2534 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2536 KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2538 tk->fmt.video.i_height = uint16( vheight );
2539 msg_Dbg( p_demux, "| | | | + height=%d", uint16( vheight ) );
2541 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2543 KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2545 tk->fmt.video.i_visible_width = uint16( vwidth );
2546 msg_Dbg( p_demux, "| | | | + display width=%d", uint16( vwidth ) );
2548 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2550 KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2552 tk->fmt.video.i_visible_height = uint16( vheight );
2553 msg_Dbg( p_demux, "| | | | + display height=%d", uint16( vheight ) );
2555 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2557 KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2559 tk->f_fps = float( vfps );
2560 msg_Dbg( p_demux, " | | | + fps=%f", float( vfps ) );
2562 // else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2564 // KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2566 // msg_Dbg( p_demux, "| | | | + Track Video Display Unit=%s",
2567 // uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2569 // else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2571 // KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2573 // msg_Dbg( p_demux, " | | | + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2575 // else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2577 // KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2579 // msg_Dbg( p_demux, " | | | + fps=%f", float( gamma ) );
2583 msg_Dbg( p_demux, "| | | | + Unknown (%s)", typeid(*l).name() );
2587 else if( MKV_IS_ID( l, KaxTrackAudio ) )
2589 EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2592 msg_Dbg( p_demux, "| | | + Track Audio" );
2594 for( j = 0; j < tka->ListSize(); j++ )
2596 EbmlElement *l = (*tka)[j];
2598 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2600 KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2602 tk->fmt.audio.i_rate = (int)float( afreq );
2603 msg_Dbg( p_demux, "| | | | + afreq=%d", tk->fmt.audio.i_rate );
2605 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2607 KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2609 tk->fmt.audio.i_channels = uint8( achan );
2610 msg_Dbg( p_demux, "| | | | + achan=%u", uint8( achan ) );
2612 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2614 KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2616 tk->fmt.audio.i_bitspersample = uint8( abits );
2617 msg_Dbg( p_demux, "| | | | + abits=%u", uint8( abits ) );
2621 msg_Dbg( p_demux, "| | | | + Unknown (%s)", typeid(*l).name() );
2627 msg_Dbg( p_demux, "| | | + Unknown (%s)",
2628 typeid(*l).name() );
2633 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2635 demux_sys_t *p_sys = p_demux->p_sys;
2639 int i_upper_level = 0;
2641 msg_Dbg( p_demux, "| + Tracks" );
2643 /* Master elements */
2644 m = static_cast<EbmlMaster *>(tracks);
2645 m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2647 for( i = 0; i < m->ListSize(); i++ )
2649 EbmlElement *l = (*m)[i];
2651 if( MKV_IS_ID( l, KaxTrackEntry ) )
2653 ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2657 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2662 /*****************************************************************************
2664 *****************************************************************************/
2665 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2667 demux_sys_t *p_sys = p_demux->p_sys;
2671 int i_upper_level = 0;
2673 msg_Dbg( p_demux, "| + Information" );
2675 /* Master elements */
2676 m = static_cast<EbmlMaster *>(info);
2677 m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2679 for( i = 0; i < m->ListSize(); i++ )
2681 EbmlElement *l = (*m)[i];
2683 if( MKV_IS_ID( l, KaxSegmentUID ) )
2685 p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2687 msg_Dbg( p_demux, "| | + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
2689 else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2691 KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2693 p_sys->i_timescale = uint64(tcs);
2695 msg_Dbg( p_demux, "| | + TimecodeScale="I64Fd,
2696 p_sys->i_timescale );
2698 else if( MKV_IS_ID( l, KaxDuration ) )
2700 KaxDuration &dur = *(KaxDuration*)l;
2702 p_sys->f_duration = float(dur);
2704 msg_Dbg( p_demux, "| | + Duration=%f",
2705 p_sys->f_duration );
2707 else if( MKV_IS_ID( l, KaxMuxingApp ) )
2709 KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2711 p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2713 msg_Dbg( p_demux, "| | + Muxing Application=%s",
2714 p_sys->psz_muxing_application );
2716 else if( MKV_IS_ID( l, KaxWritingApp ) )
2718 KaxWritingApp &wapp = *(KaxWritingApp*)l;
2720 p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2722 msg_Dbg( p_demux, "| | + Writing Application=%s",
2723 p_sys->psz_writing_application );
2725 else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2727 KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2729 p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2731 msg_Dbg( p_demux, "| | + Segment Filename=%s",
2732 p_sys->psz_segment_filename );
2734 else if( MKV_IS_ID( l, KaxTitle ) )
2736 KaxTitle &title = *(KaxTitle*)l;
2738 p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2740 msg_Dbg( p_demux, "| | + Title=%s", p_sys->psz_title );
2742 if( MKV_IS_ID( l, KaxSegmentFamily ) )
2744 KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2746 p_sys->families.push_back(*uid);
2748 msg_Dbg( p_demux, "| | + family=%d", *(uint32*)uid->GetBuffer() );
2750 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2751 else if( MKV_IS_ID( l, KaxDateUTC ) )
2753 KaxDateUTC &date = *(KaxDateUTC*)l;
2758 i_date = date.GetEpochDate();
2759 memset( buffer, 0, 256 );
2760 if( gmtime_r( &i_date, &tmres ) &&
2761 asctime_r( &tmres, buffer ) )
2763 buffer[strlen( buffer)-1]= '\0';
2764 p_sys->psz_date_utc = strdup( buffer );
2765 msg_Dbg( p_demux, "| | + Date=%s", p_sys->psz_date_utc );
2771 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2775 p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
2779 /*****************************************************************************
2781 *****************************************************************************/
2782 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2784 demux_sys_t *p_sys = p_demux->p_sys;
2787 if( p_sys->title == NULL )
2789 p_sys->title = vlc_input_title_New();
2792 msg_Dbg( p_demux, "| | | + ChapterAtom (level=%d)", i_level );
2793 for( i = 0; i < ca->ListSize(); i++ )
2795 EbmlElement *l = (*ca)[i];
2797 if( MKV_IS_ID( l, KaxChapterUID ) )
2799 chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
2800 msg_Dbg( p_demux, "| | | | + ChapterUID: %lld", chapters.i_uid );
2802 else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2804 KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2805 chapters.b_display_seekpoint = uint8( flag ) == 0;
2807 msg_Dbg( p_demux, "| | | | + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
2809 else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2811 KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2812 chapters.i_start_time = uint64( start ) / I64C(1000);
2814 msg_Dbg( p_demux, "| | | | + ChapterTimeStart: %lld", chapters.i_start_time );
2816 else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2818 KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2819 chapters.i_end_time = uint64( end ) / I64C(1000);
2821 msg_Dbg( p_demux, "| | | | + ChapterTimeEnd: %lld", chapters.i_end_time );
2823 else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2825 EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2828 msg_Dbg( p_demux, "| | | | + ChapterDisplay" );
2829 for( j = 0; j < cd->ListSize(); j++ )
2831 EbmlElement *l= (*cd)[j];
2833 if( MKV_IS_ID( l, KaxChapterString ) )
2837 KaxChapterString &name =*(KaxChapterString*)l;
2838 for (k = 0; k < i_level; k++)
2839 chapters.psz_name += '+';
2840 chapters.psz_name += ' ';
2841 chapters.psz_name += UTF8ToStr( UTFstring( name ) );
2843 msg_Dbg( p_demux, "| | | | | + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2845 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2847 KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2848 const char *psz = string( lang ).c_str();
2850 msg_Dbg( p_demux, "| | | | | + ChapterLanguage '%s'", psz );
2852 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2854 KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2855 const char *psz = string( ct ).c_str();
2857 msg_Dbg( p_demux, "| | | | | + ChapterCountry '%s'", psz );
2861 else if( MKV_IS_ID( l, KaxChapterAtom ) )
2863 chapter_item_t new_sub_chapter;
2864 ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
2865 new_sub_chapter.psz_parent = &chapters;
2866 chapters.sub_chapters.push_back( new_sub_chapter );
2871 /*****************************************************************************
2873 *****************************************************************************/
2874 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2876 demux_sys_t *p_sys = p_demux->p_sys;
2880 int i_upper_level = 0;
2881 int i_default_edition = 0;
2884 /* Master elements */
2885 m = static_cast<EbmlMaster *>(chapters);
2886 m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2888 for( i = 0; i < m->ListSize(); i++ )
2890 EbmlElement *l = (*m)[i];
2892 if( MKV_IS_ID( l, KaxEditionEntry ) )
2894 chapter_edition_t edition;
2896 EbmlMaster *E = static_cast<EbmlMaster *>(l );
2898 msg_Dbg( p_demux, "| | + EditionEntry" );
2899 for( j = 0; j < E->ListSize(); j++ )
2901 EbmlElement *l = (*E)[j];
2903 if( MKV_IS_ID( l, KaxChapterAtom ) )
2905 chapter_item_t new_sub_chapter;
2906 ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
2907 edition.chapters.push_back( new_sub_chapter );
2909 else if( MKV_IS_ID( l, KaxEditionUID ) )
2911 edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
2913 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
2915 edition.b_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0;
2917 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
2919 if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
2920 i_default_edition = p_sys->editions.size();
2924 msg_Dbg( p_demux, "| | | + Unknown (%s)", typeid(*l).name() );
2927 p_sys->editions.push_back( edition );
2931 msg_Dbg( p_demux, "| | + Unknown (%s)", typeid(*l).name() );
2935 for( i = 0; i < p_sys->editions.size(); i++ )
2937 p_sys->editions[i].RefreshChapters( *p_sys->title );
2940 p_sys->i_current_edition = i_default_edition;
2942 if ( p_sys->editions[i_default_edition].b_ordered )
2944 /* update the duration of the segment according to the sum of all sub chapters */
2945 f_duration = p_sys->editions[i_default_edition].Duration() / I64C(1000);
2946 if (f_duration > 0.0)
2947 p_sys->f_duration = f_duration;
2951 /*****************************************************************************
2952 * InformationCreate:
2953 *****************************************************************************/
2954 static void InformationCreate( demux_t *p_demux )
2956 demux_sys_t *p_sys = p_demux->p_sys;
2959 p_sys->meta = vlc_meta_New();
2961 if( p_sys->psz_title )
2963 vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2965 if( p_sys->psz_date_utc )
2967 vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2969 if( p_sys->psz_segment_filename )
2971 vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2973 if( p_sys->psz_muxing_application )
2975 vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2977 if( p_sys->psz_writing_application )
2979 vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2982 for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2984 mkv_track_t *tk = &p_sys->track[i_track];
2985 vlc_meta_t *mtk = vlc_meta_New();
2987 p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2988 sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2989 p_sys->meta->track[p_sys->meta->i_track++] = mtk;
2991 if( tk->fmt.psz_description )
2993 vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
2995 if( tk->psz_codec_name )
2997 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
2999 if( tk->psz_codec_settings )
3001 vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
3003 if( tk->psz_codec_info_url )
3005 vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3007 if( tk->psz_codec_download_url )
3009 vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
3013 if( p_sys->i_tags_position >= 0 )
3015 vlc_bool_t b_seekable;
3017 stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
3020 LoadTags( p_demux );
3026 /*****************************************************************************
3028 *****************************************************************************/
3030 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
3032 demux_sys_t *p_sys = p_demux->p_sys;
3034 #define idx p_sys->index[p_sys->i_index]
3036 idx.i_block_number= -1;
3037 idx.i_position = cluster->GetElementPosition();
3039 idx.b_key = VLC_TRUE;
3042 if( p_sys->i_index >= p_sys->i_index_max )
3044 p_sys->i_index_max += 1024;
3045 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
3050 static char * UTF8ToStr( const UTFstring &u )
3059 p = dst = (char*)malloc( i_src + 1);
3078 void chapter_edition_t::RefreshChapters( input_title_t & title )
3080 int64_t i_prev_user_time = 0;
3081 std::vector<chapter_item_t>::iterator index = chapters.begin();
3083 while ( index != chapters.end() )
3085 i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3090 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3092 int64_t i_user_time = i_prev_user_time;
3094 // first the sub-chapters, and then ourself
3095 std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3096 while ( index != sub_chapters.end() )
3098 i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3104 i_user_start_time = i_prev_user_time;
3105 if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3107 i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3111 i_user_end_time = i_user_time;
3116 std::sort( sub_chapters.begin(), sub_chapters.end() );
3117 i_user_start_time = i_start_time;
3118 i_user_end_time = i_end_time;
3121 if (b_display_seekpoint)
3123 seekpoint_t *sk = vlc_seekpoint_New();
3125 // sk->i_level = i_level;
3126 sk->i_time_offset = i_start_time;
3127 sk->psz_name = strdup( psz_name.c_str() );
3129 // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3130 title.i_seekpoint++;
3131 title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3132 title.seekpoint[title.i_seekpoint-1] = sk;
3135 i_seekpoint_num = title.i_seekpoint;
3137 return i_user_end_time;
3140 double chapter_edition_t::Duration() const
3142 double f_result = 0.0;
3144 if ( chapters.size() )
3146 std::vector<chapter_item_t>::const_iterator index = chapters.end();
3148 f_result = (*index).i_user_end_time;
3154 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3156 const chapter_item_t *psz_result = NULL;
3158 if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3160 std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3161 while ( index != sub_chapters.end() && psz_result == NULL )
3163 psz_result = (*index).FindTimecode( i_user_timecode );
3167 if ( psz_result == NULL )
3174 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3176 const chapter_item_t *psz_result = NULL;
3178 std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3179 while ( index != chapters.end() && psz_result == NULL )
3181 psz_result = (*index).FindTimecode( i_user_timecode );