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