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