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