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