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