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