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