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