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