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