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