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