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