]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
1624dafe88263e88a8f06a70b8dd0e15a735fb0f
[vlc] / modules / demux / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *
9  * This program is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU General Public License for more details.
18  *
19  * You should have received a copy of the GNU General Public License
20  * along with this program; if not, write to the Free Software
21  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
22  *****************************************************************************/
23
24 /*****************************************************************************
25  * Preamble
26  *****************************************************************************/
27 #include <stdlib.h>                                      /* malloc(), free() */
28
29 #include <vlc/vlc.h>
30
31 #ifdef HAVE_TIME_H
32 #   include <time.h>                                               /* time() */
33 #endif
34
35 #include <vlc/input.h>
36
37 #include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */
38 #include "iso_lang.h"
39 #include "vlc_meta.h"
40
41 #include <iostream>
42 #include <cassert>
43 #include <typeinfo>
44
45 /* libebml and matroska */
46 #include "ebml/EbmlHead.h"
47 #include "ebml/EbmlSubHead.h"
48 #include "ebml/EbmlStream.h"
49 #include "ebml/EbmlContexts.h"
50 #include "ebml/EbmlVersion.h"
51 #include "ebml/EbmlVoid.h"
52
53 #include "matroska/FileKax.h"
54 #include "matroska/KaxAttachments.h"
55 #include "matroska/KaxBlock.h"
56 #include "matroska/KaxBlockData.h"
57 #include "matroska/KaxChapters.h"
58 #include "matroska/KaxCluster.h"
59 #include "matroska/KaxClusterData.h"
60 #include "matroska/KaxContexts.h"
61 #include "matroska/KaxCues.h"
62 #include "matroska/KaxCuesData.h"
63 #include "matroska/KaxInfo.h"
64 #include "matroska/KaxInfoData.h"
65 #include "matroska/KaxSeekHead.h"
66 #include "matroska/KaxSegment.h"
67 #include "matroska/KaxTag.h"
68 #include "matroska/KaxTags.h"
69 #include "matroska/KaxTagMulti.h"
70 #include "matroska/KaxTracks.h"
71 #include "matroska/KaxTrackAudio.h"
72 #include "matroska/KaxTrackVideo.h"
73 #include "matroska/KaxTrackEntryData.h"
74 #include "matroska/KaxContentEncoding.h"
75
76 #include "ebml/StdIOCallback.h"
77
78 extern "C" {
79    #include "mp4/libmp4.h"
80 }
81 #ifdef HAVE_ZLIB_H
82 #   include <zlib.h>
83 #endif
84
85 #define MATROSKA_COMPRESSION_NONE 0
86 #define MATROSKA_COMPRESSION_ZLIB 1
87
88 using namespace LIBMATROSKA_NAMESPACE;
89 using namespace std;
90
91 /*****************************************************************************
92  * Module descriptor
93  *****************************************************************************/
94 static int  Open ( vlc_object_t * );
95 static void Close( vlc_object_t * );
96
97 vlc_module_begin();
98     set_description( _("Matroska stream demuxer" ) );
99     set_capability( "demux2", 50 );
100     set_callbacks( Open, Close );
101
102     add_bool( "mkv-seek-percent", 1, NULL,
103             N_("Seek based on percent not time"),
104             N_("Seek based on percent not time"), VLC_TRUE );
105
106     add_shortcut( "mka" );
107     add_shortcut( "mkv" );
108 vlc_module_end();
109
110 /*****************************************************************************
111  * Local prototypes
112  *****************************************************************************/
113 static int  Demux  ( demux_t * );
114 static int  Control( demux_t *, int, va_list );
115 static void Seek   ( demux_t *, mtime_t i_date, int i_percent );
116
117 #ifdef HAVE_ZLIB_H
118 block_t *block_zlib_decompress( vlc_object_t *p_this, block_t *p_in_block ) {
119     int result, dstsize, n;
120     unsigned char *dst;
121     block_t *p_block;
122     z_stream d_stream;
123
124     d_stream.zalloc = (alloc_func)0;
125     d_stream.zfree = (free_func)0;
126     d_stream.opaque = (voidpf)0;
127     result = inflateInit(&d_stream);
128     if( result != Z_OK )
129     {
130         msg_Dbg( p_this, "inflateInit() failed. Result: %d", result );
131         return NULL;
132     }
133
134     d_stream.next_in = (Bytef *)p_in_block->p_buffer;
135     d_stream.avail_in = p_in_block->i_buffer;
136     n = 0;
137     p_block = block_New( p_this, 0 );
138     dst = NULL;
139     do
140     {
141         n++;
142         p_block = block_Realloc( p_block, 0, n * 1000 );
143         dst = (unsigned char *)p_block->p_buffer;
144         d_stream.next_out = (Bytef *)&dst[(n - 1) * 1000];
145         d_stream.avail_out = 1000;
146         result = inflate(&d_stream, Z_NO_FLUSH);
147         if( ( result != Z_OK ) && ( result != Z_STREAM_END ) )
148         {
149             msg_Dbg( p_this, "Zlib decompression failed. Result: %d", result );
150             return NULL;
151         }
152     }
153     while( ( d_stream.avail_out == 0 ) && ( d_stream.avail_in != 0 ) &&
154            ( result != Z_STREAM_END ) );
155
156     dstsize = d_stream.total_out;
157     inflateEnd( &d_stream );
158
159     p_block = block_Realloc( p_block, 0, dstsize );
160     p_block->i_buffer = dstsize;
161     block_Release( p_in_block );
162
163     return p_block;
164 }
165 #endif
166
167 /**
168  * Helper function to print the mkv parse tree
169  */
170 static void MkvTree( demux_t *p_this, int i_level, char *psz_format, ... )
171 {
172     va_list args;
173     if( i_level > 9 )
174     {
175         msg_Err( p_this, "too deep tree" );
176         return;
177     }
178     va_start( args, psz_format );
179     static char *psz_foo = "|   |   |   |   |   |   |   |   |   |";
180     char *psz_foo2 = (char*)malloc( ( i_level * 4 + 3 + strlen( psz_format ) ) * sizeof(char) );
181     strncpy( psz_foo2, psz_foo, 4 * i_level );
182     psz_foo2[ 4 * i_level ] = '+';
183     psz_foo2[ 4 * i_level + 1 ] = ' ';
184     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
185     __msg_GenericVa( VLC_OBJECT(p_this), VLC_MSG_DBG, "mkv", psz_foo2, args );
186     free( psz_foo2 );
187     va_end( args );
188 }
189     
190 /*****************************************************************************
191  * Stream managment
192  *****************************************************************************/
193 class vlc_stream_io_callback: public IOCallback
194 {
195   private:
196     stream_t       *s;
197     vlc_bool_t     mb_eof;
198
199   public:
200     vlc_stream_io_callback( stream_t * );
201
202     virtual uint32   read            ( void *p_buffer, size_t i_size);
203     virtual void     setFilePointer  ( int64_t i_offset, seek_mode mode = seek_beginning );
204     virtual size_t   write           ( const void *p_buffer, size_t i_size);
205     virtual uint64   getFilePointer  ( void );
206     virtual void     close           ( void );
207 };
208
209 /*****************************************************************************
210  * Ebml Stream parser
211  *****************************************************************************/
212 class EbmlParser
213 {
214   public:
215     EbmlParser( EbmlStream *es, EbmlElement *el_start );
216     ~EbmlParser( void );
217
218     void Up( void );
219     void Down( void );
220     EbmlElement *Get( void );
221     void        Keep( void );
222
223     int GetLevel( void );
224
225   private:
226     EbmlStream  *m_es;
227     int         mi_level;
228     EbmlElement *m_el[10];
229
230     EbmlElement *m_got;
231
232     int         mi_user_level;
233     vlc_bool_t  mb_keep;
234 };
235
236
237 /*****************************************************************************
238  * Some functions to manipulate memory
239  *****************************************************************************/
240 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
241 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
242 {
243     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
244 }
245
246 /*****************************************************************************
247  * definitions of structures and functions used by this plugins
248  *****************************************************************************/
249 typedef struct
250 {
251     vlc_bool_t  b_default;
252     vlc_bool_t  b_enabled;
253     int         i_number;
254
255     int         i_extra_data;
256     uint8_t     *p_extra_data;
257
258     char         *psz_codec;
259
260     uint64_t     i_default_duration;
261     float        f_timecodescale;
262
263     /* video */
264     es_format_t fmt;
265     float       f_fps;
266     es_out_id_t *p_es;
267
268     vlc_bool_t      b_inited;
269     /* data to be send first */
270     int             i_data_init;
271     uint8_t         *p_data_init;
272
273     /* hack : it's for seek */
274     vlc_bool_t      b_search_keyframe;
275
276     /* informative */
277     char         *psz_codec_name;
278     char         *psz_codec_settings;
279     char         *psz_codec_info_url;
280     char         *psz_codec_download_url;
281     
282     /* encryption/compression */
283     int           i_compression_type;
284
285 } mkv_track_t;
286
287 typedef struct
288 {
289     int     i_track;
290     int     i_block_number;
291
292     int64_t i_position;
293     int64_t i_time;
294
295     vlc_bool_t b_key;
296 } mkv_index_t;
297
298 struct demux_sys_t
299 {
300     vlc_stream_io_callback  *in;
301     EbmlStream              *es;
302     EbmlParser              *ep;
303
304     /* time scale */
305     uint64_t                i_timescale;
306
307     /* duration of the segment */
308     float                   f_duration;
309
310     /* all tracks */
311     int                     i_track;
312     mkv_track_t             *track;
313
314     /* from seekhead */
315     int64_t                 i_cues_position;
316     int64_t                 i_chapters_position;
317     int64_t                 i_tags_position;
318
319     /* current data */
320     KaxSegment              *segment;
321     KaxCluster              *cluster;
322
323     mtime_t                 i_pts;
324
325     vlc_bool_t              b_cues;
326     int                     i_index;
327     int                     i_index_max;
328     mkv_index_t             *index;
329
330     /* info */
331     char                    *psz_muxing_application;
332     char                    *psz_writing_application;
333     char                    *psz_segment_filename;
334     char                    *psz_title;
335     char                    *psz_date_utc;
336
337     vlc_meta_t              *meta;
338
339     input_title_t           *title;
340 };
341
342 #define MKVD_TIMECODESCALE 1000000
343
344 #define MKV_IS_ID( el, C ) ( EbmlId( (*el) ) == C::ClassInfos.GlobalId )
345
346 static void IndexAppendCluster  ( demux_t *p_demux, KaxCluster *cluster );
347 static char *UTF8ToStr          ( const UTFstring &u );
348 static void LoadCues            ( demux_t * );
349 static void InformationCreate  ( demux_t * );
350
351 static void ParseInfo( demux_t *, EbmlElement *info );
352 static void ParseTracks( demux_t *, EbmlElement *tracks );
353 static void ParseSeekHead( demux_t *, EbmlElement *seekhead );
354 static void ParseChapters( demux_t *, EbmlElement *chapters );
355
356 /*****************************************************************************
357  * Open: initializes matroska demux structures
358  *****************************************************************************/
359 static int Open( vlc_object_t * p_this )
360 {
361     demux_t     *p_demux = (demux_t*)p_this;
362     demux_sys_t *p_sys;
363     uint8_t     *p_peek;
364
365     int          i_track;
366
367     EbmlElement *el = NULL, *el1 = NULL;
368
369     /* peek the begining */
370     if( stream_Peek( p_demux->s, &p_peek, 4 ) < 4 )
371     {
372         msg_Warn( p_demux, "cannot peek" );
373         return VLC_EGENERIC;
374     }
375
376     /* is a valid file */
377     if( p_peek[0] != 0x1a || p_peek[1] != 0x45 ||
378         p_peek[2] != 0xdf || p_peek[3] != 0xa3 )
379     {
380         msg_Warn( p_demux, "matroska module discarded "
381                            "(invalid header 0x%.2x%.2x%.2x%.2x)",
382                            p_peek[0], p_peek[1], p_peek[2], p_peek[3] );
383         return VLC_EGENERIC;
384     }
385
386     /* Set the demux function */
387     p_demux->pf_demux   = Demux;
388     p_demux->pf_control = Control;
389     p_demux->p_sys      = p_sys = (demux_sys_t*)malloc(sizeof( demux_sys_t ));
390
391     memset( p_sys, 0, sizeof( demux_sys_t ) );
392     p_sys->in = new vlc_stream_io_callback( p_demux->s );
393     p_sys->es = new EbmlStream( *p_sys->in );
394     p_sys->f_duration   = -1;
395     p_sys->i_timescale     = MKVD_TIMECODESCALE;
396     p_sys->i_track      = 0;
397     p_sys->track        = (mkv_track_t*)malloc( sizeof( mkv_track_t ) );
398     p_sys->i_pts   = 0;
399     p_sys->i_cues_position = -1;
400     p_sys->i_chapters_position = -1;
401     p_sys->i_tags_position = -1;
402
403     p_sys->b_cues       = VLC_FALSE;
404     p_sys->i_index      = 0;
405     p_sys->i_index_max  = 1024;
406     p_sys->index        = (mkv_index_t*)malloc( sizeof( mkv_index_t ) *
407                                                 p_sys->i_index_max );
408
409     p_sys->psz_muxing_application = NULL;
410     p_sys->psz_writing_application = NULL;
411     p_sys->psz_segment_filename = NULL;
412     p_sys->psz_title = NULL;
413     p_sys->psz_date_utc = NULL;;
414     p_sys->meta = NULL;
415     p_sys->title = NULL;
416
417     if( p_sys->es == NULL )
418     {
419         msg_Err( p_demux, "failed to create EbmlStream" );
420         delete p_sys->in;
421         free( p_sys );
422         return VLC_EGENERIC;
423     }
424     /* Find the EbmlHead element */
425     el = p_sys->es->FindNextID(EbmlHead::ClassInfos, 0xFFFFFFFFL);
426     if( el == NULL )
427     {
428         msg_Err( p_demux, "cannot find EbmlHead" );
429         goto error;
430     }
431     msg_Dbg( p_demux, "EbmlHead" );
432     /* skip it */
433     el->SkipData( *p_sys->es, el->Generic().Context );
434     delete el;
435
436     /* Find a segment */
437     el = p_sys->es->FindNextID( KaxSegment::ClassInfos, 0xFFFFFFFFL);
438     if( el == NULL )
439     {
440         msg_Err( p_demux, "cannot find KaxSegment" );
441         goto error;
442     }
443     MkvTree( p_demux, 0, "Segment" );
444     p_sys->segment = (KaxSegment*)el;
445     p_sys->cluster = NULL;
446
447     p_sys->ep = new EbmlParser( p_sys->es, el );
448
449     while( ( el1 = p_sys->ep->Get() ) != NULL )
450     {
451         if( MKV_IS_ID( el1, KaxInfo ) )
452         {
453             ParseInfo( p_demux, el1 );
454         }
455         else if( MKV_IS_ID( el1, KaxTracks ) )
456         {
457             ParseTracks( p_demux, el1 );
458         }
459         else if( MKV_IS_ID( el1, KaxSeekHead ) )
460         {
461             ParseSeekHead( p_demux, el1 );
462         }
463         else if( MKV_IS_ID( el1, KaxCues ) )
464         {
465             msg_Dbg( p_demux, "|   + Cues" );
466         }
467         else if( MKV_IS_ID( el1, KaxCluster ) )
468         {
469             msg_Dbg( p_demux, "|   + Cluster" );
470
471             p_sys->cluster = (KaxCluster*)el1;
472
473             p_sys->ep->Down();
474             /* stop parsing the stream */
475             break;
476         }
477         else if( MKV_IS_ID( el1, KaxAttachments ) )
478         {
479             msg_Dbg( p_demux, "|   + Attachments FIXME TODO (but probably never supported)" );
480         }
481         else if( MKV_IS_ID( el1, KaxChapters ) )
482         {
483             msg_Dbg( p_demux, "|   + Chapters" );
484             ParseChapters( p_demux, el1 );
485         }
486         else if( MKV_IS_ID( el1, KaxTag ) )
487         {
488             msg_Dbg( p_demux, "|   + Tags FIXME TODO" );
489         }
490         else
491         {
492             msg_Dbg( p_demux, "|   + Unknown (%s)", typeid(*el1).name() );
493         }
494     }
495
496     if( p_sys->cluster == NULL )
497     {
498         msg_Err( p_demux, "cannot find any cluster, damaged file ?" );
499         goto error;
500     }
501
502     /* *** Load the cue if found *** */
503     if( p_sys->i_cues_position >= 0 )
504     {
505         vlc_bool_t b_seekable;
506
507         stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
508         if( b_seekable )
509         {
510             LoadCues( p_demux );
511         }
512     }
513
514     if( !p_sys->b_cues || p_sys->i_index <= 0 )
515     {
516         msg_Warn( p_demux, "no cues/empty cues found->seek won't be precise" );
517
518         IndexAppendCluster( p_demux, p_sys->cluster );
519
520         p_sys->b_cues = VLC_FALSE;
521     }
522
523     /* add all es */
524     msg_Dbg( p_demux, "found %d es", p_sys->i_track );
525     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
526     {
527 #define tk  p_sys->track[i_track]
528         if( tk.fmt.i_cat == UNKNOWN_ES )
529         {
530             msg_Warn( p_demux, "invalid track[%d, n=%d]", i_track, tk.i_number );
531             tk.p_es = NULL;
532             continue;
533         }
534
535         if( !strcmp( tk.psz_codec, "V_MS/VFW/FOURCC" ) )
536         {
537             if( tk.i_extra_data < (int)sizeof( BITMAPINFOHEADER ) )
538             {
539                 msg_Err( p_demux, "missing/invalid BITMAPINFOHEADER" );
540                 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
541             }
542             else
543             {
544                 BITMAPINFOHEADER *p_bih = (BITMAPINFOHEADER*)tk.p_extra_data;
545
546                 tk.fmt.video.i_width = GetDWLE( &p_bih->biWidth );
547                 tk.fmt.video.i_height= GetDWLE( &p_bih->biHeight );
548                 tk.fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
549
550                 tk.fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( BITMAPINFOHEADER );
551                 if( tk.fmt.i_extra > 0 )
552                 {
553                     tk.fmt.p_extra = malloc( tk.fmt.i_extra );
554                     memcpy( tk.fmt.p_extra, &p_bih[1], tk.fmt.i_extra );
555                 }
556             }
557         }
558         else if( !strcmp( tk.psz_codec, "V_MPEG1" ) ||
559                  !strcmp( tk.psz_codec, "V_MPEG2" ) )
560         {
561             tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'v' );
562         }
563         else if( !strncmp( tk.psz_codec, "V_MPEG4", 7 ) )
564         {
565             if( !strcmp( tk.psz_codec, "V_MPEG4/MS/V3" ) )
566             {
567                 tk.fmt.i_codec = VLC_FOURCC( 'D', 'I', 'V', '3' );
568             }
569             else
570             {
571                 tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'v' );
572             }
573         }
574         else if( !strcmp( tk.psz_codec, "V_QUICKTIME" ) )
575         {
576             MP4_Box_t *p_box = (MP4_Box_t*)malloc( sizeof( MP4_Box_t ) );
577             stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(p_demux),
578                                                        tk.p_extra_data,
579                                                        tk.i_extra_data );
580             MP4_ReadBoxCommon( p_mp4_stream, p_box );
581             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
582             tk.fmt.i_codec = p_box->i_type;
583             tk.fmt.video.i_width = p_box->data.p_sample_vide->i_width;
584             tk.fmt.video.i_height = p_box->data.p_sample_vide->i_height;
585             tk.fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
586             tk.fmt.p_extra = malloc( tk.fmt.i_extra );
587             memcpy( tk.fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk.fmt.i_extra );
588             MP4_FreeBox_sample_vide( p_box );
589             stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
590         }
591         else if( !strcmp( tk.psz_codec, "A_MS/ACM" ) )
592         {
593             if( tk.i_extra_data < (int)sizeof( WAVEFORMATEX ) )
594             {
595                 msg_Err( p_demux, "missing/invalid WAVEFORMATEX" );
596                 tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
597             }
598             else
599             {
600                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk.p_extra_data;
601
602                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk.fmt.i_codec, NULL );
603
604                 tk.fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
605                 tk.fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
606                 tk.fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
607                 tk.fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
608                 tk.fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
609
610                 tk.fmt.i_extra            = GetWLE( &p_wf->cbSize );
611                 if( tk.fmt.i_extra > 0 )
612                 {
613                     tk.fmt.p_extra = malloc( tk.fmt.i_extra );
614                     memcpy( tk.fmt.p_extra, &p_wf[1], tk.fmt.i_extra );
615                 }
616             }
617         }
618         else if( !strcmp( tk.psz_codec, "A_MPEG/L3" ) ||
619                  !strcmp( tk.psz_codec, "A_MPEG/L2" ) ||
620                  !strcmp( tk.psz_codec, "A_MPEG/L1" ) )
621         {
622             tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
623         }
624         else if( !strcmp( tk.psz_codec, "A_AC3" ) )
625         {
626             tk.fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
627         }
628         else if( !strcmp( tk.psz_codec, "A_DTS" ) )
629         {
630             tk.fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
631         }
632         else if( !strcmp( tk.psz_codec, "A_FLAC" ) )
633         {
634             tk.fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
635             tk.fmt.i_extra = tk.i_extra_data;
636             tk.fmt.p_extra = malloc( tk.i_extra_data );
637             memcpy( tk.fmt.p_extra,tk.p_extra_data, tk.i_extra_data );
638         }
639         else if( !strcmp( tk.psz_codec, "A_VORBIS" ) )
640         {
641             int i, i_offset = 1, i_size[3], i_extra;
642             uint8_t *p_extra;
643
644             tk.fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
645
646             /* Split the 3 headers */
647             if( tk.p_extra_data[0] != 0x02 )
648                 msg_Err( p_demux, "invalid vorbis header" );
649
650             for( i = 0; i < 2; i++ )
651             {
652                 i_size[i] = 0;
653                 while( i_offset < tk.i_extra_data )
654                 {
655                     i_size[i] += tk.p_extra_data[i_offset];
656                     if( tk.p_extra_data[i_offset++] != 0xff ) break;
657                 }
658             }
659
660             i_size[0] = __MIN(i_size[0], tk.i_extra_data - i_offset);
661             i_size[1] = __MIN(i_size[1], tk.i_extra_data -i_offset -i_size[0]);
662             i_size[2] = tk.i_extra_data - i_offset - i_size[0] - i_size[1];
663
664             tk.fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
665             tk.fmt.p_extra = malloc( tk.fmt.i_extra );
666             p_extra = (uint8_t *)tk.fmt.p_extra; i_extra = 0;
667             for( i = 0; i < 3; i++ )
668             {
669                 *(p_extra++) = i_size[i] >> 8;
670                 *(p_extra++) = i_size[i] & 0xFF;
671                 memcpy( p_extra, tk.p_extra_data + i_offset + i_extra,
672                         i_size[i] );
673                 p_extra += i_size[i];
674                 i_extra += i_size[i];
675             }
676         }
677         else if( !strncmp( tk.psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
678                  !strncmp( tk.psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
679         {
680             int i_profile, i_srate;
681             static unsigned int i_sample_rates[] =
682             {
683                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
684                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
685             };
686
687             tk.fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
688             /* create data for faad (MP4DecSpecificDescrTag)*/
689
690             if( !strcmp( &tk.psz_codec[12], "MAIN" ) )
691             {
692                 i_profile = 0;
693             }
694             else if( !strcmp( &tk.psz_codec[12], "LC" ) )
695             {
696                 i_profile = 1;
697             }
698             else if( !strcmp( &tk.psz_codec[12], "SSR" ) )
699             {
700                 i_profile = 2;
701             }
702             else
703             {
704                 i_profile = 3;
705             }
706
707             for( i_srate = 0; i_srate < 13; i_srate++ )
708             {
709                 if( i_sample_rates[i_srate] == tk.fmt.audio.i_rate )
710                 {
711                     break;
712                 }
713             }
714             msg_Dbg( p_demux, "profile=%d srate=%d", i_profile, i_srate );
715
716             tk.fmt.i_extra = 2;
717             tk.fmt.p_extra = malloc( tk.fmt.i_extra );
718             ((uint8_t*)tk.fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
719             ((uint8_t*)tk.fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk.fmt.audio.i_channels << 3);
720         }
721         else if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) ||
722                  !strcmp( tk.psz_codec, "A_PCM/INT/LIT" ) ||
723                  !strcmp( tk.psz_codec, "A_PCM/FLOAT/IEEE" ) )
724         {
725             if( !strcmp( tk.psz_codec, "A_PCM/INT/BIG" ) )
726             {
727                 tk.fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
728             }
729             else
730             {
731                 tk.fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
732             }
733             tk.fmt.audio.i_blockalign = ( tk.fmt.audio.i_bitspersample + 7 ) / 8 * tk.fmt.audio.i_channels;
734         }
735         else if( !strcmp( tk.psz_codec, "S_TEXT/UTF8" ) )
736         {
737             tk.fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
738             tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
739         }
740         else if( !strcmp( tk.psz_codec, "S_TEXT/SSA" ) ||
741                  !strcmp( tk.psz_codec, "S_TEXT/ASS" ) ||
742                  !strcmp( tk.psz_codec, "S_SSA" ) ||
743                  !strcmp( tk.psz_codec, "S_ASS" ))
744         {
745             tk.fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
746             tk.fmt.subs.psz_encoding = strdup( "UTF-8" );
747         }
748         else if( !strcmp( tk.psz_codec, "S_VOBSUB" ) )
749         {
750             tk.fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
751             if( tk.i_extra_data )
752             {
753                 char *p_start;
754                 char *p_buf = (char *)malloc( tk.i_extra_data + 1);
755                 memcpy( p_buf, tk.p_extra_data , tk.i_extra_data );
756                 p_buf[tk.i_extra_data] = '\0';
757                 
758                 p_start = strstr( p_buf, "size:" );
759                 if( sscanf( p_start, "size: %dx%d",
760                         &tk.fmt.subs.spu.i_original_frame_width, &tk.fmt.subs.spu.i_original_frame_height ) == 2 )
761                 {
762                     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 );
763                 }
764                 else
765                 {
766                     msg_Warn( p_demux, "reading original frame size for vobsub failed" );
767                 }
768                 free( p_buf );
769             }
770         }
771         else
772         {
773             msg_Err( p_demux, "unknow codec id=`%s'", tk.psz_codec );
774             tk.fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
775         }
776         if( tk.b_default )
777         {
778             tk.fmt.i_priority = 1000;
779         }
780
781         tk.p_es = es_out_Add( p_demux->out, &tk.fmt );
782 #undef tk
783     }
784
785     /* add information */
786     InformationCreate( p_demux );
787
788     return VLC_SUCCESS;
789
790 error:
791     delete p_sys->es;
792     delete p_sys->in;
793     free( p_sys );
794     return VLC_EGENERIC;
795 }
796
797 /*****************************************************************************
798  * Close: frees unused data
799  *****************************************************************************/
800 static void Close( vlc_object_t *p_this )
801 {
802     demux_t     *p_demux = (demux_t*)p_this;
803     demux_sys_t *p_sys   = p_demux->p_sys;
804     int         i_track;
805
806     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
807     {
808 #define tk  p_sys->track[i_track]
809         if( tk.fmt.psz_description )
810         {
811             free( tk.fmt.psz_description );
812         }
813         if( tk.psz_codec )
814         {
815             free( tk.psz_codec );
816         }
817         if( tk.fmt.psz_language )
818         {
819             free( tk.fmt.psz_language );
820         }
821 #undef tk
822     }
823     free( p_sys->track );
824
825     if( p_sys->psz_writing_application  )
826     {
827         free( p_sys->psz_writing_application );
828     }
829     if( p_sys->psz_muxing_application  )
830     {
831         free( p_sys->psz_muxing_application );
832     }
833
834     delete p_sys->segment;
835
836     delete p_sys->ep;
837     delete p_sys->es;
838     delete p_sys->in;
839
840     free( p_sys );
841 }
842
843 /*****************************************************************************
844  * Control:
845  *****************************************************************************/
846 static int Control( demux_t *p_demux, int i_query, va_list args )
847 {
848     demux_sys_t *p_sys = p_demux->p_sys;
849     int64_t     *pi64;
850     double      *pf, f;
851
852     vlc_meta_t **pp_meta;
853
854     switch( i_query )
855     {
856         case DEMUX_GET_META:
857             pp_meta = (vlc_meta_t**)va_arg( args, vlc_meta_t** );
858             *pp_meta = vlc_meta_Duplicate( p_sys->meta );
859             return VLC_SUCCESS;
860
861         case DEMUX_GET_LENGTH:
862             pi64 = (int64_t*)va_arg( args, int64_t * );
863             if( p_sys->f_duration > 0.0 )
864             {
865                 *pi64 = (int64_t)(p_sys->f_duration * 1000);
866                 return VLC_SUCCESS;
867             }
868             return VLC_EGENERIC;
869
870         case DEMUX_GET_POSITION:
871             pf = (double*)va_arg( args, double * );
872             *pf = (double)p_sys->in->getFilePointer() / (double)stream_Size( p_demux->s );
873             return VLC_SUCCESS;
874
875         case DEMUX_SET_POSITION:
876             f = (double)va_arg( args, double );
877             Seek( p_demux, -1, (int)(100.0 * f) );
878             return VLC_SUCCESS;
879
880         case DEMUX_GET_TIME:
881             pi64 = (int64_t*)va_arg( args, int64_t * );
882             if( p_sys->f_duration > 0.0 )
883             {
884                 mtime_t i_duration = (mtime_t)( p_sys->f_duration / 1000 );
885
886                 /* FIXME */
887                 *pi64 = (mtime_t)1000000 *
888                         (mtime_t)i_duration*
889                         (mtime_t)p_sys->in->getFilePointer() /
890                         (mtime_t)stream_Size( p_demux->s );
891                 return VLC_SUCCESS;
892             }
893             return VLC_EGENERIC;
894
895         case DEMUX_GET_TITLE_INFO:
896             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
897             {
898                 input_title_t ***ppp_title = (input_title_t***)va_arg( args, input_title_t*** );
899                 int *pi_int    = (int*)va_arg( args, int* );
900
901                 *pi_int = 1;
902                 *ppp_title = (input_title_t**)malloc( sizeof( input_title_t**) );
903
904                 (*ppp_title)[0] = vlc_input_title_Duplicate( p_sys->title );
905
906                 return VLC_SUCCESS;
907             }
908             return VLC_EGENERIC;
909
910         case DEMUX_SET_TITLE:
911             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
912             {
913                 return VLC_SUCCESS;
914             }
915             return VLC_EGENERIC;
916
917         case DEMUX_SET_SEEKPOINT:
918             /* FIXME do a better implementation */
919             if( p_sys->title && p_sys->title->i_seekpoint > 0 )
920             {
921                 int i_skp = (int)va_arg( args, int );
922
923                 Seek( p_demux, (int64_t)p_sys->title->seekpoint[i_skp]->i_time_offset, -1);
924                 return VLC_SUCCESS;
925             }
926             return VLC_EGENERIC;
927
928
929         case DEMUX_SET_TIME:
930         case DEMUX_GET_FPS:
931         default:
932             return VLC_EGENERIC;
933     }
934 }
935
936 static int BlockGet( demux_t *p_demux, KaxBlock **pp_block, int64_t *pi_ref1, int64_t *pi_ref2, int64_t *pi_duration )
937 {
938     demux_sys_t *p_sys = p_demux->p_sys;
939
940     *pp_block = NULL;
941     *pi_ref1  = -1;
942     *pi_ref2  = -1;
943
944     for( ;; )
945     {
946         EbmlElement *el;
947         int         i_level;
948
949         if( p_demux->b_die )
950         {
951             return VLC_EGENERIC;
952         }
953
954         el = p_sys->ep->Get();
955         i_level = p_sys->ep->GetLevel();
956
957         if( el == NULL && *pp_block != NULL )
958         {
959             /* update the index */
960 #define idx p_sys->index[p_sys->i_index - 1]
961             if( p_sys->i_index > 0 && idx.i_time == -1 )
962             {
963                 idx.i_time        = (*pp_block)->GlobalTimecode() / (mtime_t)1000;
964                 idx.b_key         = *pi_ref1 == -1 ? VLC_TRUE : VLC_FALSE;
965             }
966 #undef idx
967             return VLC_SUCCESS;
968         }
969
970         if( el == NULL )
971         {
972             if( p_sys->ep->GetLevel() > 1 )
973             {
974                 p_sys->ep->Up();
975                 continue;
976             }
977             msg_Warn( p_demux, "EOF" );
978             return VLC_EGENERIC;
979         }
980
981         /* do parsing */
982         if( i_level == 1 )
983         {
984             if( MKV_IS_ID( el, KaxCluster ) )
985             {
986                 p_sys->cluster = (KaxCluster*)el;
987
988                 /* add it to the index */
989                 if( p_sys->i_index == 0 ||
990                     ( p_sys->i_index > 0 && p_sys->index[p_sys->i_index - 1].i_position < (int64_t)p_sys->cluster->GetElementPosition() ) )
991                 {
992                     IndexAppendCluster( p_demux, p_sys->cluster );
993                 }
994
995                 p_sys->ep->Down();
996             }
997             else if( MKV_IS_ID( el, KaxCues ) )
998             {
999                 msg_Warn( p_demux, "find KaxCues FIXME" );
1000                 return VLC_EGENERIC;
1001             }
1002             else
1003             {
1004                 msg_Dbg( p_demux, "unknown (%s)", typeid( el ).name() );
1005             }
1006         }
1007         else if( i_level == 2 )
1008         {
1009             if( MKV_IS_ID( el, KaxClusterTimecode ) )
1010             {
1011                 KaxClusterTimecode &ctc = *(KaxClusterTimecode*)el;
1012
1013                 ctc.ReadData( p_sys->es->I_O(), SCOPE_ALL_DATA );
1014                 p_sys->cluster->InitTimecode( uint64( ctc ), p_sys->i_timescale );
1015             }
1016             else if( MKV_IS_ID( el, KaxBlockGroup ) )
1017             {
1018                 p_sys->ep->Down();
1019             }
1020         }
1021         else if( i_level == 3 )
1022         {
1023             if( MKV_IS_ID( el, KaxBlock ) )
1024             {
1025                 *pp_block = (KaxBlock*)el;
1026
1027                 (*pp_block)->ReadData( p_sys->es->I_O() );
1028                 (*pp_block)->SetParent( *p_sys->cluster );
1029
1030                 p_sys->ep->Keep();
1031             }
1032             else if( MKV_IS_ID( el, KaxBlockDuration ) )
1033             {
1034                 KaxBlockDuration &dur = *(KaxBlockDuration*)el;
1035
1036                 dur.ReadData( p_sys->es->I_O() );
1037                 *pi_duration = uint64( dur );
1038             }
1039             else if( MKV_IS_ID( el, KaxReferenceBlock ) )
1040             {
1041                 KaxReferenceBlock &ref = *(KaxReferenceBlock*)el;
1042
1043                 ref.ReadData( p_sys->es->I_O() );
1044                 if( *pi_ref1 == -1 )
1045                 {
1046                     *pi_ref1 = int64( ref );
1047                 }
1048                 else
1049                 {
1050                     *pi_ref2 = int64( ref );
1051                 }
1052             }
1053         }
1054         else
1055         {
1056             msg_Err( p_demux, "invalid level = %d", i_level );
1057             return VLC_EGENERIC;
1058         }
1059     }
1060 }
1061
1062 static block_t *MemToBlock( demux_t *p_demux, uint8_t *p_mem, int i_mem)
1063 {
1064     block_t *p_block;
1065     if( !(p_block = block_New( p_demux, i_mem ) ) ) return NULL;
1066     memcpy( p_block->p_buffer, p_mem, i_mem );
1067     //p_block->i_rate = p_input->stream.control.i_rate;
1068     return p_block;
1069 }
1070
1071 static void BlockDecode( demux_t *p_demux, KaxBlock *block, mtime_t i_pts,
1072                          mtime_t i_duration )
1073 {
1074     demux_sys_t *p_sys = p_demux->p_sys;
1075
1076     int             i_track;
1077     unsigned int    i;
1078     vlc_bool_t      b;
1079
1080 #define tk  p_sys->track[i_track]
1081     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1082     {
1083         if( tk.i_number == block->TrackNum() )
1084         {
1085             break;
1086         }
1087     }
1088
1089     if( i_track >= p_sys->i_track )
1090     {
1091         msg_Err( p_demux, "invalid track number=%d", block->TrackNum() );
1092         return;
1093     }
1094
1095     es_out_Control( p_demux->out, ES_OUT_GET_ES_STATE, tk.p_es, &b );
1096     if( !b )
1097     {
1098         tk.b_inited = VLC_FALSE;
1099         return;
1100     }
1101
1102     /* First send init data */
1103     if( !tk.b_inited && tk.i_data_init > 0 )
1104     {
1105         block_t *p_init;
1106
1107         msg_Dbg( p_demux, "sending header (%d bytes)", tk.i_data_init );
1108         p_init = MemToBlock( p_demux, tk.p_data_init, tk.i_data_init );
1109         if( p_init ) es_out_Send( p_demux->out, tk.p_es, p_init );
1110     }
1111     tk.b_inited = VLC_TRUE;
1112
1113
1114     for( i = 0; i < block->NumberFrames(); i++ )
1115     {
1116         block_t *p_block;
1117         DataBuffer &data = block->GetBuffer(i);
1118
1119         p_block = MemToBlock( p_demux, data.Buffer(), data.Size() );
1120
1121         if( p_block == NULL )
1122         {
1123             break;
1124         }
1125
1126 #if defined(HAVE_ZLIB_H)
1127         if( tk.i_compression_type )
1128         {
1129             p_block = block_zlib_decompress( VLC_OBJECT(p_demux), p_block );
1130         }
1131 #endif
1132
1133         if( tk.fmt.i_cat != VIDEO_ES )
1134             p_block->i_dts = p_block->i_pts = i_pts;
1135         else
1136         {
1137             p_block->i_dts = i_pts;
1138             p_block->i_pts = 0;
1139         }
1140
1141         if( tk.fmt.i_cat == SPU_ES && strcmp( tk.psz_codec, "S_VOBSUB" ) )
1142         {
1143             p_block->i_length = i_duration * 1000;
1144         }
1145         es_out_Send( p_demux->out, tk.p_es, p_block );
1146
1147         /* use time stamp only for first block */
1148         i_pts = 0;
1149     }
1150
1151 #undef tk
1152 }
1153
1154 static void Seek( demux_t *p_demux, mtime_t i_date, int i_percent)
1155 {
1156     demux_sys_t *p_sys = p_demux->p_sys;
1157
1158     KaxBlock    *block;
1159     int64_t     i_block_duration;
1160     int64_t     i_block_ref1;
1161     int64_t     i_block_ref2;
1162
1163     int         i_index;
1164     int         i_track_skipping;
1165     int         i_track;
1166
1167     msg_Dbg( p_demux, "seek request to "I64Fd" (%d%%)", i_date, i_percent );
1168     if( i_date < 0 && i_percent < 0 )
1169     {
1170         return;
1171     }
1172     if( i_percent > 100 ) i_percent = 100;
1173
1174     delete p_sys->ep;
1175     p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1176     p_sys->cluster = NULL;
1177
1178     /* seek without index or without date */
1179     if( config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 )
1180     {
1181         int64_t i_pos = i_percent * stream_Size( p_demux->s ) / 100;
1182
1183         msg_Dbg( p_demux, "inacurate way of seeking" );
1184         for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1185         {
1186             if( p_sys->index[i_index].i_position >= i_pos)
1187             {
1188                 break;
1189             }
1190         }
1191         if( i_index == p_sys->i_index )
1192         {
1193             i_index--;
1194         }
1195
1196         p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1197                                    seek_beginning );
1198
1199         if( p_sys->index[i_index].i_position < i_pos )
1200         {
1201             EbmlElement *el;
1202
1203             msg_Warn( p_demux, "searching for cluster, could take some time" );
1204
1205             /* search a cluster */
1206             while( ( el = p_sys->ep->Get() ) != NULL )
1207             {
1208                 if( MKV_IS_ID( el, KaxCluster ) )
1209                 {
1210                     KaxCluster *cluster = (KaxCluster*)el;
1211
1212                     /* add it to the index */
1213                     IndexAppendCluster( p_demux, cluster );
1214
1215                     if( (int64_t)cluster->GetElementPosition() >= i_pos )
1216                     {
1217                         p_sys->cluster = cluster;
1218                         p_sys->ep->Down();
1219                         break;
1220                     }
1221                 }
1222             }
1223         }
1224     }
1225     else
1226     {
1227         for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1228         {
1229             if( p_sys->index[i_index].i_time >= i_date )
1230             {
1231                 break;
1232             }
1233         }
1234
1235         if( i_index > 0 )
1236         {
1237             i_index--;
1238         }
1239
1240         msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1241                  p_sys->index[i_index].i_time,
1242                  (int)( 100 * p_sys->index[i_index].i_position /
1243                         stream_Size( p_demux->s ) ) );
1244
1245         p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1246                                    seek_beginning );
1247     }
1248
1249     /* now parse until key frame */
1250 #define tk  p_sys->track[i_track]
1251     i_track_skipping = 0;
1252     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1253     {
1254         if( tk.fmt.i_cat == VIDEO_ES )
1255         {
1256             tk.b_search_keyframe = VLC_TRUE;
1257             i_track_skipping++;
1258         }
1259     }
1260
1261     while( i_track_skipping > 0 )
1262     {
1263         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1264         {
1265             msg_Warn( p_demux, "cannot get block EOF?" );
1266
1267             return;
1268         }
1269
1270         p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000 + 1;
1271
1272         for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1273         {
1274             if( tk.i_number == block->TrackNum() )
1275             {
1276                 break;
1277             }
1278         }
1279
1280         if( i_track < p_sys->i_track )
1281         {
1282             if( tk.fmt.i_cat == VIDEO_ES && i_block_ref1 == -1 && tk.b_search_keyframe )
1283             {
1284                 tk.b_search_keyframe = VLC_FALSE;
1285                 i_track_skipping--;
1286             }
1287             if( tk.fmt.i_cat == VIDEO_ES && !tk.b_search_keyframe )
1288             {
1289                 BlockDecode( p_demux, block, 0, 0 );
1290             }
1291         }
1292
1293         delete block;
1294     }
1295 #undef tk
1296 }
1297
1298 /*****************************************************************************
1299  * Demux: reads and demuxes data packets
1300  *****************************************************************************
1301  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1302  *****************************************************************************/
1303 static int Demux( demux_t *p_demux)
1304 {
1305     demux_sys_t *p_sys = p_demux->p_sys;
1306     mtime_t        i_start_pts;
1307     int            i_block_count = 0;
1308
1309     KaxBlock *block;
1310     int64_t i_block_duration;
1311     int64_t i_block_ref1;
1312     int64_t i_block_ref2;
1313
1314     i_start_pts = -1;
1315
1316     for( ;; )
1317     {
1318         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1319         {
1320             msg_Warn( p_demux, "cannot get block EOF?" );
1321
1322             return 0;
1323         }
1324
1325         p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000 + 1;
1326
1327         if( p_sys->i_pts > 0 )
1328         {
1329             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1330         }
1331
1332         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1333
1334         delete block;
1335         i_block_count++;
1336
1337         if( i_start_pts == -1 )
1338         {
1339             i_start_pts = p_sys->i_pts;
1340         }
1341         else if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )
1342         {
1343             return 1;
1344         }
1345     }
1346 }
1347
1348
1349
1350 /*****************************************************************************
1351  * Stream managment
1352  *****************************************************************************/
1353 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1354 {
1355     s = s_;
1356     mb_eof = VLC_FALSE;
1357 }
1358
1359 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1360 {
1361     if( i_size <= 0 || mb_eof )
1362     {
1363         return 0;
1364     }
1365
1366     return stream_Read( s, p_buffer, i_size );
1367 }
1368 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1369 {
1370     int64_t i_pos;
1371
1372     switch( mode )
1373     {
1374         case seek_beginning:
1375             i_pos = i_offset;
1376             break;
1377         case seek_end:
1378             i_pos = stream_Size( s ) - i_offset;
1379             break;
1380         default:
1381             i_pos= stream_Tell( s ) + i_offset;
1382             break;
1383     }
1384
1385     if( i_pos < 0 || i_pos >= stream_Size( s ) )
1386     {
1387         mb_eof = VLC_TRUE;
1388         return;
1389     }
1390
1391     mb_eof = VLC_FALSE;
1392     if( stream_Seek( s, i_pos ) )
1393     {
1394         mb_eof = VLC_TRUE;
1395     }
1396     return;
1397 }
1398 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1399 {
1400     return 0;
1401 }
1402 uint64 vlc_stream_io_callback::getFilePointer( void )
1403 {
1404     return stream_Tell( s );
1405 }
1406 void vlc_stream_io_callback::close( void )
1407 {
1408     return;
1409 }
1410
1411
1412 /*****************************************************************************
1413  * Ebml Stream parser
1414  *****************************************************************************/
1415 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1416 {
1417     int i;
1418
1419     m_es = es;
1420     m_got = NULL;
1421     m_el[0] = el_start;
1422
1423     for( i = 1; i < 6; i++ )
1424     {
1425         m_el[i] = NULL;
1426     }
1427     mi_level = 1;
1428     mi_user_level = 1;
1429     mb_keep = VLC_FALSE;
1430 }
1431
1432 EbmlParser::~EbmlParser( void )
1433 {
1434     int i;
1435
1436     for( i = 1; i < mi_level; i++ )
1437     {
1438         if( !mb_keep )
1439         {
1440             delete m_el[i];
1441         }
1442         mb_keep = VLC_FALSE;
1443     }
1444 }
1445
1446 void EbmlParser::Up( void )
1447 {
1448     if( mi_user_level == mi_level )
1449     {
1450         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1451     }
1452
1453     mi_user_level--;
1454 }
1455
1456 void EbmlParser::Down( void )
1457 {
1458     mi_user_level++;
1459     mi_level++;
1460 }
1461
1462 void EbmlParser::Keep( void )
1463 {
1464     mb_keep = VLC_TRUE;
1465 }
1466
1467 int EbmlParser::GetLevel( void )
1468 {
1469     return mi_user_level;
1470 }
1471
1472 EbmlElement *EbmlParser::Get( void )
1473 {
1474     int i_ulev = 0;
1475
1476     if( mi_user_level != mi_level )
1477     {
1478         return NULL;
1479     }
1480     if( m_got )
1481     {
1482         EbmlElement *ret = m_got;
1483         m_got = NULL;
1484
1485         return ret;
1486     }
1487
1488     if( m_el[mi_level] )
1489     {
1490         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1491         if( !mb_keep )
1492         {
1493             delete m_el[mi_level];
1494         }
1495         mb_keep = VLC_FALSE;
1496     }
1497
1498     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1499     if( i_ulev > 0 )
1500     {
1501         while( i_ulev > 0 )
1502         {
1503             if( mi_level == 1 )
1504             {
1505                 mi_level = 0;
1506                 return NULL;
1507             }
1508
1509             delete m_el[mi_level - 1];
1510             m_got = m_el[mi_level -1] = m_el[mi_level];
1511             m_el[mi_level] = NULL;
1512
1513             mi_level--;
1514             i_ulev--;
1515         }
1516         return NULL;
1517     }
1518     else if( m_el[mi_level] == NULL )
1519     {
1520         fprintf( stderr," m_el[mi_level] == NULL\n" );
1521     }
1522
1523     return m_el[mi_level];
1524 }
1525
1526
1527 /*****************************************************************************
1528  * Tools
1529  *  * LoadCues : load the cues element and update index
1530  *
1531  *  * LoadTags : load ... the tags element
1532  *
1533  *  * InformationCreate : create all information, load tags if present
1534  *
1535  *****************************************************************************/
1536 static void LoadCues( demux_t *p_demux )
1537 {
1538     demux_sys_t *p_sys = p_demux->p_sys;
1539     int64_t     i_sav_position = p_sys->in->getFilePointer();
1540     EbmlParser  *ep;
1541     EbmlElement *el, *cues;
1542
1543     msg_Dbg( p_demux, "loading cues" );
1544     p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1545     cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1546
1547     if( cues == NULL )
1548     {
1549         msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1550         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1551         return;
1552     }
1553
1554     ep = new EbmlParser( p_sys->es, cues );
1555     while( ( el = ep->Get() ) != NULL )
1556     {
1557         if( MKV_IS_ID( el, KaxCuePoint ) )
1558         {
1559 #define idx p_sys->index[p_sys->i_index]
1560
1561             idx.i_track       = -1;
1562             idx.i_block_number= -1;
1563             idx.i_position    = -1;
1564             idx.i_time        = 0;
1565             idx.b_key         = VLC_TRUE;
1566
1567             ep->Down();
1568             while( ( el = ep->Get() ) != NULL )
1569             {
1570                 if( MKV_IS_ID( el, KaxCueTime ) )
1571                 {
1572                     KaxCueTime &ctime = *(KaxCueTime*)el;
1573
1574                     ctime.ReadData( p_sys->es->I_O() );
1575
1576                     idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1577                 }
1578                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1579                 {
1580                     ep->Down();
1581                     while( ( el = ep->Get() ) != NULL )
1582                     {
1583                         if( MKV_IS_ID( el, KaxCueTrack ) )
1584                         {
1585                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1586
1587                             ctrack.ReadData( p_sys->es->I_O() );
1588                             idx.i_track = uint16( ctrack );
1589                         }
1590                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1591                         {
1592                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1593
1594                             ccpos.ReadData( p_sys->es->I_O() );
1595                             idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1596                         }
1597                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1598                         {
1599                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1600
1601                             cbnum.ReadData( p_sys->es->I_O() );
1602                             idx.i_block_number = uint32( cbnum );
1603                         }
1604                         else
1605                         {
1606                             msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );
1607                         }
1608                     }
1609                     ep->Up();
1610                 }
1611                 else
1612                 {
1613                     msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );
1614                 }
1615             }
1616             ep->Up();
1617
1618 #if 0
1619             msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
1620                      " track=%d bnum=%d", idx.i_time, idx.i_position,
1621                      idx.i_track, idx.i_block_number );
1622 #endif
1623
1624             p_sys->i_index++;
1625             if( p_sys->i_index >= p_sys->i_index_max )
1626             {
1627                 p_sys->i_index_max += 1024;
1628                 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
1629             }
1630 #undef idx
1631         }
1632         else
1633         {
1634             msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1635         }
1636     }
1637     delete ep;
1638     delete cues;
1639
1640     p_sys->b_cues = VLC_TRUE;
1641
1642     msg_Dbg( p_demux, "loading cues done." );
1643     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1644 }
1645
1646 static void LoadTags( demux_t *p_demux )
1647 {
1648     demux_sys_t *p_sys = p_demux->p_sys;
1649     int64_t     i_sav_position = p_sys->in->getFilePointer();
1650     EbmlParser  *ep;
1651     EbmlElement *el, *tags;
1652
1653     msg_Dbg( p_demux, "loading tags" );
1654     p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
1655     tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
1656
1657     if( tags == NULL )
1658     {
1659         msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
1660         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1661         return;
1662     }
1663
1664     msg_Dbg( p_demux, "Tags" );
1665     ep = new EbmlParser( p_sys->es, tags );
1666     while( ( el = ep->Get() ) != NULL )
1667     {
1668         if( MKV_IS_ID( el, KaxTag ) )
1669         {
1670             msg_Dbg( p_demux, "+ Tag" );
1671             ep->Down();
1672             while( ( el = ep->Get() ) != NULL )
1673             {
1674                 if( MKV_IS_ID( el, KaxTagTargets ) )
1675                 {
1676                     msg_Dbg( p_demux, "|   + Targets" );
1677                     ep->Down();
1678                     while( ( el = ep->Get() ) != NULL )
1679                     {
1680                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1681                     }
1682                     ep->Up();
1683                 }
1684                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
1685                 {
1686                     msg_Dbg( p_demux, "|   + General" );
1687                     ep->Down();
1688                     while( ( el = ep->Get() ) != NULL )
1689                     {
1690                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1691                     }
1692                     ep->Up();
1693                 }
1694                 else if( MKV_IS_ID( el, KaxTagGenres ) )
1695                 {
1696                     msg_Dbg( p_demux, "|   + Genres" );
1697                     ep->Down();
1698                     while( ( el = ep->Get() ) != NULL )
1699                     {
1700                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1701                     }
1702                     ep->Up();
1703                 }
1704                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
1705                 {
1706                     msg_Dbg( p_demux, "|   + Audio Specific" );
1707                     ep->Down();
1708                     while( ( el = ep->Get() ) != NULL )
1709                     {
1710                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1711                     }
1712                     ep->Up();
1713                 }
1714                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
1715                 {
1716                     msg_Dbg( p_demux, "|   + Images Specific" );
1717                     ep->Down();
1718                     while( ( el = ep->Get() ) != NULL )
1719                     {
1720                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1721                     }
1722                     ep->Up();
1723                 }
1724                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
1725                 {
1726                     msg_Dbg( p_demux, "|   + Multi Comment" );
1727                 }
1728                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
1729                 {
1730                     msg_Dbg( p_demux, "|   + Multi Commercial" );
1731                 }
1732                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
1733                 {
1734                     msg_Dbg( p_demux, "|   + Multi Date" );
1735                 }
1736                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
1737                 {
1738                     msg_Dbg( p_demux, "|   + Multi Entity" );
1739                 }
1740                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
1741                 {
1742                     msg_Dbg( p_demux, "|   + Multi Identifier" );
1743                 }
1744                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
1745                 {
1746                     msg_Dbg( p_demux, "|   + Multi Legal" );
1747                 }
1748                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
1749                 {
1750                     msg_Dbg( p_demux, "|   + Multi Title" );
1751                 }
1752                 else
1753                 {
1754                     msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );
1755                 }
1756             }
1757             ep->Up();
1758         }
1759         else
1760         {
1761             msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
1762         }
1763     }
1764     delete ep;
1765     delete tags;
1766
1767     msg_Dbg( p_demux, "loading tags done." );
1768     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1769 }
1770
1771 /*****************************************************************************
1772  * ParseInfo:
1773  *****************************************************************************/
1774 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
1775 {
1776     demux_sys_t *p_sys = p_demux->p_sys;
1777     EbmlElement *el;
1778     EbmlMaster  *m;
1779     unsigned int i;
1780     int i_upper_level = 0;
1781
1782     msg_Dbg( p_demux, "|   + Seek head" );
1783
1784     /* Master elements */
1785     m = static_cast<EbmlMaster *>(seekhead);
1786     m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
1787
1788     for( i = 0; i < m->ListSize(); i++ )
1789     {
1790         EbmlElement *l = (*m)[i];
1791
1792         if( MKV_IS_ID( l, KaxSeek ) )
1793         {
1794             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
1795             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
1796             int64_t i_pos = -1;
1797
1798             unsigned int j;
1799
1800             for( j = 0; j < sk->ListSize(); j++ )
1801             {
1802                 EbmlElement *l = (*sk)[j];
1803
1804                 if( MKV_IS_ID( l, KaxSeekID ) )
1805                 {
1806                     KaxSeekID &sid = *(KaxSeekID*)l;
1807                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
1808                 }
1809                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
1810                 {
1811                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
1812                     i_pos = uint64( spos );
1813                 }
1814                 else
1815                 {
1816                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
1817                 }
1818             }
1819
1820             if( i_pos >= 0 )
1821             {
1822                 if( id == KaxCues::ClassInfos.GlobalId )
1823                 {
1824                     msg_Dbg( p_demux, "|   |   |   = cues at "I64Fd, i_pos );
1825                     p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
1826                 }
1827                 else if( id == KaxChapters::ClassInfos.GlobalId )
1828                 {
1829                     msg_Dbg( p_demux, "|   |   |   = chapters at "I64Fd, i_pos );
1830                     p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
1831                 }
1832                 else if( id == KaxTags::ClassInfos.GlobalId )
1833                 {
1834                     msg_Dbg( p_demux, "|   |   |   = tags at "I64Fd, i_pos );
1835                     p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
1836                 }
1837             }
1838         }
1839         else
1840         {
1841             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
1842         }
1843     }
1844 }
1845
1846 /*****************************************************************************
1847  * ParseTracks:
1848  *****************************************************************************/
1849 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
1850 {
1851     demux_sys_t *p_sys = p_demux->p_sys;
1852     unsigned int i;
1853
1854     mkv_track_t *tk;
1855
1856     msg_Dbg( p_demux, "|   |   + Track Entry" );
1857
1858     p_sys->i_track++;
1859     p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
1860
1861     /* Init the track */
1862     tk = &p_sys->track[p_sys->i_track - 1];
1863
1864     memset( tk, 0, sizeof( mkv_track_t ) );
1865
1866     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
1867     tk->fmt.psz_language = strdup("English");
1868     tk->fmt.psz_description = NULL;
1869
1870     tk->b_default = VLC_TRUE;
1871     tk->b_enabled = VLC_TRUE;
1872     tk->i_number = p_sys->i_track - 1;
1873     tk->i_extra_data = 0;
1874     tk->p_extra_data = NULL;
1875     tk->psz_codec = NULL;
1876     tk->i_default_duration = 0;
1877     tk->f_timecodescale = 1.0;
1878
1879     tk->b_inited = VLC_FALSE;
1880     tk->i_data_init = 0;
1881     tk->p_data_init = NULL;
1882
1883     tk->psz_codec_name = NULL;
1884     tk->psz_codec_settings = NULL;
1885     tk->psz_codec_info_url = NULL;
1886     tk->psz_codec_download_url = NULL;
1887     
1888     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
1889
1890     for( i = 0; i < m->ListSize(); i++ )
1891     {
1892         EbmlElement *l = (*m)[i];
1893
1894         if( MKV_IS_ID( l, KaxTrackNumber ) )
1895         {
1896             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
1897
1898             tk->i_number = uint32( tnum );
1899             msg_Dbg( p_demux, "|   |   |   + Track Number=%u", uint32( tnum ) );
1900         }
1901         else  if( MKV_IS_ID( l, KaxTrackUID ) )
1902         {
1903             KaxTrackUID &tuid = *(KaxTrackUID*)l;
1904
1905             msg_Dbg( p_demux, "|   |   |   + Track UID=%u",  uint32( tuid ) );
1906         }
1907         else  if( MKV_IS_ID( l, KaxTrackType ) )
1908         {
1909             char *psz_type;
1910             KaxTrackType &ttype = *(KaxTrackType*)l;
1911
1912             switch( uint8(ttype) )
1913             {
1914                 case track_audio:
1915                     psz_type = "audio";
1916                     tk->fmt.i_cat = AUDIO_ES;
1917                     break;
1918                 case track_video:
1919                     psz_type = "video";
1920                     tk->fmt.i_cat = VIDEO_ES;
1921                     break;
1922                 case track_subtitle:
1923                     psz_type = "subtitle";
1924                     tk->fmt.i_cat = SPU_ES;
1925                     break;
1926                 default:
1927                     psz_type = "unknown";
1928                     tk->fmt.i_cat = UNKNOWN_ES;
1929                     break;
1930             }
1931
1932             msg_Dbg( p_demux, "|   |   |   + Track Type=%s", psz_type );
1933         }
1934 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
1935 //        {
1936 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
1937
1938 //            tk->b_enabled = uint32( fenb );
1939 //            msg_Dbg( p_demux, "|   |   |   + Track Enabled=%u",
1940 //                     uint32( fenb )  );
1941 //        }
1942         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
1943         {
1944             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
1945
1946             tk->b_default = uint32( fdef );
1947             msg_Dbg( p_demux, "|   |   |   + Track Default=%u", uint32( fdef )  );
1948         }
1949         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
1950         {
1951             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
1952
1953             msg_Dbg( p_demux, "|   |   |   + Track Lacing=%d", uint32( lac ) );
1954         }
1955         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
1956         {
1957             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
1958
1959             msg_Dbg( p_demux, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
1960         }
1961         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
1962         {
1963             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
1964
1965             msg_Dbg( p_demux, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
1966         }
1967         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
1968         {
1969             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
1970
1971             tk->i_default_duration = uint64(defd);
1972             msg_Dbg( p_demux, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
1973         }
1974         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
1975         {
1976             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
1977
1978             tk->f_timecodescale = float( ttcs );
1979             msg_Dbg( p_demux, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
1980         }
1981         else if( MKV_IS_ID( l, KaxTrackName ) )
1982         {
1983             KaxTrackName &tname = *(KaxTrackName*)l;
1984
1985             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
1986             msg_Dbg( p_demux, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
1987         }
1988         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
1989         {
1990             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
1991
1992             tk->fmt.psz_language = strdup( string( lang ).c_str() );
1993             msg_Dbg( p_demux,
1994                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
1995         }
1996         else  if( MKV_IS_ID( l, KaxCodecID ) )
1997         {
1998             KaxCodecID &codecid = *(KaxCodecID*)l;
1999
2000             tk->psz_codec = strdup( string( codecid ).c_str() );
2001             msg_Dbg( p_demux, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2002         }
2003         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2004         {
2005             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2006
2007             tk->i_extra_data = cpriv.GetSize();
2008             if( tk->i_extra_data > 0 )
2009             {
2010                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2011                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2012             }
2013             msg_Dbg( p_demux, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2014         }
2015         else if( MKV_IS_ID( l, KaxCodecName ) )
2016         {
2017             KaxCodecName &cname = *(KaxCodecName*)l;
2018
2019             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2020             msg_Dbg( p_demux, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2021         }
2022         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2023         {
2024             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2025             MkvTree( p_demux, 3, "Content Encodings" );
2026             for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2027             {
2028                 EbmlElement *l2 = (*cencs)[i];
2029                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2030                 {
2031                     MkvTree( p_demux, 4, "Content Encoding" );
2032                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2033                     for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2034                     {
2035                         EbmlElement *l3 = (*cenc)[i];
2036                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2037                         {
2038                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2039                             MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2040                         }
2041                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2042                         {
2043                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2044                             MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2045                         }
2046                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2047                         {
2048                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2049                             MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2050                         }
2051                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
2052                         {
2053                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2054                             MkvTree( p_demux, 5, "Content Compression" );
2055                             for( unsigned int i = 0; i < compr->ListSize(); i++ )
2056                             {
2057                                 EbmlElement *l4 = (*compr)[i];
2058                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2059                                 {
2060                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2061                                     MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2062                                     if( uint32( compalg ) == 0 )
2063                                     {
2064                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2065                                     }
2066                                 }
2067                                 else
2068                                 {
2069                                     MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2070                                 }
2071                             }
2072                         }
2073
2074                         else
2075                         {
2076                             MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2077                         }
2078                     }
2079                     
2080                 }
2081                 else
2082                 {
2083                     MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2084                 }
2085             }
2086                 
2087         }
2088 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2089 //        {
2090 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2091
2092 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2093 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
2094 //        }
2095 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2096 //        {
2097 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2098
2099 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2100 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
2101 //        }
2102 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2103 //        {
2104 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2105
2106 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2107 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
2108 //        }
2109 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2110 //        {
2111 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2112
2113 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2114 //        }
2115 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2116 //        {
2117 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2118
2119 //            msg_Dbg( p_demux, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2120 //        }
2121         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
2122         {
2123             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2124             unsigned int j;
2125
2126             msg_Dbg( p_demux, "|   |   |   + Track Video" );
2127             tk->f_fps = 0.0;
2128
2129             for( j = 0; j < tkv->ListSize(); j++ )
2130             {
2131                 EbmlElement *l = (*tkv)[j];
2132 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2133 //                {
2134 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2135
2136 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
2137 //                }
2138 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2139 //                {
2140 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2141
2142 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
2143 //                }
2144 //                else
2145                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2146                 {
2147                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2148
2149                     tk->fmt.video.i_width = uint16( vwidth );
2150                     msg_Dbg( p_demux, "|   |   |   |   + width=%d", uint16( vwidth ) );
2151                 }
2152                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2153                 {
2154                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2155
2156                     tk->fmt.video.i_height = uint16( vheight );
2157                     msg_Dbg( p_demux, "|   |   |   |   + height=%d", uint16( vheight ) );
2158                 }
2159                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2160                 {
2161                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2162
2163                     tk->fmt.video.i_visible_width = uint16( vwidth );
2164                     msg_Dbg( p_demux, "|   |   |   |   + display width=%d", uint16( vwidth ) );
2165                 }
2166                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2167                 {
2168                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2169
2170                     tk->fmt.video.i_visible_height = uint16( vheight );
2171                     msg_Dbg( p_demux, "|   |   |   |   + display height=%d", uint16( vheight ) );
2172                 }
2173                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2174                 {
2175                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2176
2177                     tk->f_fps = float( vfps );
2178                     msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( vfps ) );
2179                 }
2180 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2181 //                {
2182 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2183
2184 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Display Unit=%s",
2185 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2186 //                }
2187 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2188 //                {
2189 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2190
2191 //                    msg_Dbg( p_demux, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2192 //                }
2193 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2194 //                {
2195 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2196
2197 //                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( gamma ) );
2198 //                }
2199                 else
2200                 {
2201                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2202                 }
2203             }
2204         }
2205         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
2206         {
2207             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2208             unsigned int j;
2209
2210             msg_Dbg( p_demux, "|   |   |   + Track Audio" );
2211
2212             for( j = 0; j < tka->ListSize(); j++ )
2213             {
2214                 EbmlElement *l = (*tka)[j];
2215
2216                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2217                 {
2218                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2219
2220                     tk->fmt.audio.i_rate = (int)float( afreq );
2221                     msg_Dbg( p_demux, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
2222                 }
2223                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2224                 {
2225                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2226
2227                     tk->fmt.audio.i_channels = uint8( achan );
2228                     msg_Dbg( p_demux, "|   |   |   |   + achan=%u", uint8( achan ) );
2229                 }
2230                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2231                 {
2232                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2233
2234                     tk->fmt.audio.i_bitspersample = uint8( abits );
2235                     msg_Dbg( p_demux, "|   |   |   |   + abits=%u", uint8( abits ) );
2236                 }
2237                 else
2238                 {
2239                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2240                 }
2241             }
2242         }
2243         else
2244         {
2245             msg_Dbg( p_demux, "|   |   |   + Unknown (%s)",
2246                      typeid(*l).name() );
2247         }
2248     }
2249 }
2250
2251 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2252 {
2253     demux_sys_t *p_sys = p_demux->p_sys;
2254     EbmlElement *el;
2255     EbmlMaster  *m;
2256     unsigned int i;
2257     int i_upper_level = 0;
2258
2259     msg_Dbg( p_demux, "|   + Tracks" );
2260
2261     /* Master elements */
2262     m = static_cast<EbmlMaster *>(tracks);
2263     m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2264
2265     for( i = 0; i < m->ListSize(); i++ )
2266     {
2267         EbmlElement *l = (*m)[i];
2268
2269         if( MKV_IS_ID( l, KaxTrackEntry ) )
2270         {
2271             ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2272         }
2273         else
2274         {
2275             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2276         }
2277     }
2278 }
2279
2280 /*****************************************************************************
2281  * ParseInfo:
2282  *****************************************************************************/
2283 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2284 {
2285     demux_sys_t *p_sys = p_demux->p_sys;
2286     EbmlElement *el;
2287     EbmlMaster  *m;
2288     unsigned int i;
2289     int i_upper_level = 0;
2290
2291     msg_Dbg( p_demux, "|   + Information" );
2292
2293     /* Master elements */
2294     m = static_cast<EbmlMaster *>(info);
2295     m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2296
2297     for( i = 0; i < m->ListSize(); i++ )
2298     {
2299         EbmlElement *l = (*m)[i];
2300
2301         if( MKV_IS_ID( l, KaxSegmentUID ) )
2302         {
2303             KaxSegmentUID &uid = *(KaxSegmentUID*)l;
2304
2305             msg_Dbg( p_demux, "|   |   + UID=%d", uint32(uid) );
2306         }
2307         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2308         {
2309             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2310
2311             p_sys->i_timescale = uint64(tcs);
2312
2313             msg_Dbg( p_demux, "|   |   + TimecodeScale="I64Fd,
2314                      p_sys->i_timescale );
2315         }
2316         else if( MKV_IS_ID( l, KaxDuration ) )
2317         {
2318             KaxDuration &dur = *(KaxDuration*)l;
2319
2320             p_sys->f_duration = float(dur);
2321
2322             msg_Dbg( p_demux, "|   |   + Duration=%f",
2323                      p_sys->f_duration );
2324         }
2325         else if( MKV_IS_ID( l, KaxMuxingApp ) )
2326         {
2327             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2328
2329             p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2330
2331             msg_Dbg( p_demux, "|   |   + Muxing Application=%s",
2332                      p_sys->psz_muxing_application );
2333         }
2334         else if( MKV_IS_ID( l, KaxWritingApp ) )
2335         {
2336             KaxWritingApp &wapp = *(KaxWritingApp*)l;
2337
2338             p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2339
2340             msg_Dbg( p_demux, "|   |   + Writing Application=%s",
2341                      p_sys->psz_writing_application );
2342         }
2343         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2344         {
2345             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2346
2347             p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2348
2349             msg_Dbg( p_demux, "|   |   + Segment Filename=%s",
2350                      p_sys->psz_segment_filename );
2351         }
2352         else if( MKV_IS_ID( l, KaxTitle ) )
2353         {
2354             KaxTitle &title = *(KaxTitle*)l;
2355
2356             p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2357
2358             msg_Dbg( p_demux, "|   |   + Title=%s", p_sys->psz_title );
2359         }
2360 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2361         else if( MKV_IS_ID( l, KaxDateUTC ) )
2362         {
2363             KaxDateUTC &date = *(KaxDateUTC*)l;
2364             time_t i_date;
2365             struct tm tmres;
2366             char   buffer[256];
2367
2368             i_date = date.GetEpochDate();
2369             memset( buffer, 0, 256 );
2370             if( gmtime_r( &i_date, &tmres ) &&
2371                 asctime_r( &tmres, buffer ) )
2372             {
2373                 buffer[strlen( buffer)-1]= '\0';
2374                 p_sys->psz_date_utc = strdup( buffer );
2375                 msg_Dbg( p_demux, "|   |   + Date=%s", p_sys->psz_date_utc );
2376             }
2377         }
2378 #endif
2379         else
2380         {
2381             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2382         }
2383     }
2384
2385     p_sys->f_duration = p_sys->f_duration * p_sys->i_timescale / 1000000.0;
2386 }
2387
2388
2389 /*****************************************************************************
2390  * ParseChapterAtom
2391  *****************************************************************************/
2392 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
2393 {
2394     demux_sys_t *p_sys = p_demux->p_sys;
2395     unsigned int i;
2396     seekpoint_t *sk;
2397
2398     if( p_sys->title == NULL )
2399     {
2400         p_sys->title = vlc_input_title_New();
2401     }
2402     sk = vlc_seekpoint_New();
2403
2404     msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );
2405     for( i = 0; i < ca->ListSize(); i++ )
2406     {
2407         EbmlElement *l = (*ca)[i];
2408
2409         if( MKV_IS_ID( l, KaxChapterUID ) )
2410         {
2411             KaxChapterUID &uid = *(KaxChapterUID*)l;
2412             uint32_t i_uid = uint32( uid );
2413             msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: 0x%x", i_uid );
2414         }
2415         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2416         {
2417             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2418             sk->i_time_offset = uint64( start ) / I64C(1000);
2419
2420             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", sk->i_time_offset );
2421         }
2422         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2423         {
2424             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2425             int64_t i_end = uint64( end );
2426
2427             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", i_end );
2428         }
2429         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2430         {
2431             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2432             unsigned int j;
2433
2434             msg_Dbg( p_demux, "|   |   |   |   + ChapterDisplay" );
2435             for( j = 0; j < cd->ListSize(); j++ )
2436             {
2437                 EbmlElement *l= (*cd)[j];
2438
2439                 if( MKV_IS_ID( l, KaxChapterString ) )
2440                 {
2441                     KaxChapterString &name =*(KaxChapterString*)l;
2442                     char *psz = UTF8ToStr( UTFstring( name ) );
2443                     sk->psz_name = strdup( psz );
2444                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", psz );
2445                 }
2446                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2447                 {
2448                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2449                     const char *psz = string( lang ).c_str();
2450
2451                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
2452                 }
2453                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2454                 {
2455                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2456                     const char *psz = string( ct ).c_str();
2457
2458                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterCountry '%s'", psz );
2459                 }
2460             }
2461         }
2462         else if( MKV_IS_ID( l, KaxChapterAtom ) )
2463         {
2464             ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l) );
2465         }
2466     }
2467     // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2468     p_sys->title->i_seekpoint++;
2469     p_sys->title->seekpoint = (seekpoint_t**)realloc( p_sys->title->seekpoint, p_sys->title->i_seekpoint * sizeof( seekpoint_t* ) );
2470     p_sys->title->seekpoint[p_sys->title->i_seekpoint-1] = sk;
2471 }
2472
2473 /*****************************************************************************
2474  * ParseChapters:
2475  *****************************************************************************/
2476 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2477 {
2478     demux_sys_t *p_sys = p_demux->p_sys;
2479     EbmlElement *el;
2480     EbmlMaster  *m;
2481     unsigned int i;
2482     int i_upper_level = 0;
2483
2484
2485     /* Master elements */
2486     m = static_cast<EbmlMaster *>(chapters);
2487     m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2488
2489     for( i = 0; i < m->ListSize(); i++ )
2490     {
2491         EbmlElement *l = (*m)[i];
2492
2493         if( MKV_IS_ID( l, KaxEditionEntry ) )
2494         {
2495             EbmlMaster *E = static_cast<EbmlMaster *>(l );
2496             unsigned int j;
2497             msg_Dbg( p_demux, "|   |   + EditionEntry" );
2498             for( j = 0; j < E->ListSize(); j++ )
2499             {
2500                 EbmlElement *l = (*E)[j];
2501
2502                 if( MKV_IS_ID( l, KaxChapterAtom ) )
2503                 {
2504                     ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l) );
2505                 }
2506                 else
2507                 {
2508                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2509                 }
2510             }
2511         }
2512         else
2513         {
2514             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2515         }
2516     }
2517 }
2518
2519 /*****************************************************************************
2520  * InformationCreate:
2521  *****************************************************************************/
2522 static void InformationCreate( demux_t *p_demux )
2523 {
2524     demux_sys_t *p_sys = p_demux->p_sys;
2525     int         i_track;
2526
2527     p_sys->meta = vlc_meta_New();
2528
2529     if( p_sys->psz_title )
2530     {
2531         vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2532     }
2533     if( p_sys->psz_date_utc )
2534     {
2535         vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2536     }
2537     if( p_sys->psz_segment_filename )
2538     {
2539         vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2540     }
2541     if( p_sys->psz_muxing_application )
2542     {
2543         vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2544     }
2545     if( p_sys->psz_writing_application )
2546     {
2547         vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2548     }
2549
2550     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2551     {
2552         mkv_track_t *tk = &p_sys->track[i_track];
2553         vlc_meta_t *mtk = vlc_meta_New();
2554
2555         p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2556                                                     sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2557         p_sys->meta->track[p_sys->meta->i_track++] = mtk;
2558
2559         if( tk->fmt.psz_description )
2560         {
2561             vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
2562         }
2563         if( tk->psz_codec_name )
2564         {
2565             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
2566         }
2567         if( tk->psz_codec_settings )
2568         {
2569             vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
2570         }
2571         if( tk->psz_codec_info_url )
2572         {
2573             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
2574         }
2575         if( tk->psz_codec_download_url )
2576         {
2577             vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
2578         }
2579     }
2580
2581     if( p_sys->i_tags_position >= 0 )
2582     {
2583         vlc_bool_t b_seekable;
2584
2585         stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
2586         if( b_seekable )
2587         {
2588             LoadTags( p_demux );
2589         }
2590     }
2591 }
2592
2593
2594 /*****************************************************************************
2595  * Divers
2596  *****************************************************************************/
2597
2598 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
2599 {
2600     demux_sys_t *p_sys = p_demux->p_sys;
2601
2602 #define idx p_sys->index[p_sys->i_index]
2603     idx.i_track       = -1;
2604     idx.i_block_number= -1;
2605     idx.i_position    = cluster->GetElementPosition();
2606     idx.i_time        = -1;
2607     idx.b_key         = VLC_TRUE;
2608
2609     p_sys->i_index++;
2610     if( p_sys->i_index >= p_sys->i_index_max )
2611     {
2612         p_sys->i_index_max += 1024;
2613         p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2614     }
2615 #undef idx
2616 }
2617
2618 static char * UTF8ToStr( const UTFstring &u )
2619 {
2620     int     i_src;
2621     const wchar_t *src;
2622     char *dst, *p;
2623
2624     i_src = u.length();
2625     src   = u.c_str();
2626
2627     p = dst = (char*)malloc( i_src + 1);
2628     while( i_src > 0 )
2629     {
2630         if( *src < 255 )
2631         {
2632             *p++ = (char)*src;
2633         }
2634         else
2635         {
2636             *p++ = '?';
2637         }
2638         src++;
2639         i_src--;
2640     }
2641     *p++= '\0';
2642
2643     return dst;
2644 }
2645