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