]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
mkv.cpp: Fix a problem when entering a chapter after the previous chapter produced...
[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                     psz_current_chapter = psz_curr_chapter;
1930                 }
1931             }
1932             else if ( psz_curr_chapter->i_seekpoint_num > 0 )
1933             {
1934                 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
1935                 demux.info.i_title = sys.i_current_title = i_sys_title;
1936                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1937                 psz_current_chapter = psz_curr_chapter;
1938             }
1939             else
1940             {
1941                 psz_current_chapter = psz_curr_chapter;
1942             }
1943
1944             return true;
1945         }
1946     }
1947     return false;
1948 }
1949
1950 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id, 
1951                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
1952                                     const void *p_cookie, 
1953                                     size_t i_cookie_size )
1954 {
1955     // FIXME don't assume it is the first edition
1956     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
1957     if ( index != p_editions->end() )
1958     {
1959         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
1960         if ( p_result != NULL )
1961             return p_result;
1962     }
1963     return NULL;
1964 }
1965
1966 chapter_item_c *virtual_segment_c::FindChapter( int64_t i_find_uid )
1967 {
1968     // FIXME don't assume it is the first edition
1969     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
1970     if ( index != p_editions->end() )
1971     {
1972         chapter_item_c *p_result = (*index)->FindChapter( i_find_uid );
1973         if ( p_result != NULL )
1974             return p_result;
1975     }
1976     return NULL;
1977 }
1978
1979 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id, 
1980                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
1981                                     const void *p_cookie, 
1982                                     size_t i_cookie_size )
1983 {
1984     // this chapter
1985     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
1986     while ( index != codecs.end() )
1987     {
1988         if ( match( **index ,p_cookie, i_cookie_size ) )
1989             return this;
1990         index++;
1991     }
1992     
1993     // sub-chapters
1994     chapter_item_c *p_result = NULL;
1995     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
1996     while ( index2 != sub_chapters.end() )
1997     {
1998         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
1999         if ( p_result != NULL )
2000             return p_result;
2001         index2++;
2002     }
2003     
2004     return p_result;
2005 }
2006
2007 void chapter_item_c::Append( const chapter_item_c & chapter )
2008 {
2009     // we are appending content for the same chapter UID
2010     size_t i;
2011     chapter_item_c *p_chapter;
2012
2013     for ( i=0; i<chapter.sub_chapters.size(); i++ )
2014     {
2015         p_chapter = FindChapter( chapter.sub_chapters[i]->i_uid );
2016         if ( p_chapter != NULL )
2017         {
2018             p_chapter->Append( *chapter.sub_chapters[i] );
2019         }
2020         else
2021         {
2022             sub_chapters.push_back( chapter.sub_chapters[i] );
2023         }
2024     }
2025
2026     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
2027     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
2028 }
2029
2030 chapter_item_c * chapter_item_c::FindChapter( int64_t i_find_uid )
2031 {
2032     size_t i;
2033     chapter_item_c *p_result = NULL;
2034
2035     if ( i_uid == i_find_uid )
2036         return this;
2037
2038     for ( i=0; i<sub_chapters.size(); i++)
2039     {
2040         p_result = sub_chapters[i]->FindChapter( i_find_uid );
2041         if ( p_result != NULL )
2042             break;
2043     }
2044     return p_result;
2045 }
2046
2047 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
2048 {
2049     std::string result;
2050
2051     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
2052     while ( index != codecs.end() )
2053     {
2054         result = (*index)->GetCodecName( f_for_title );
2055         if ( result != "" )
2056             break;
2057         index++;
2058     }
2059
2060     return result;
2061 }
2062
2063 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
2064 {
2065     std::string result;
2066     if ( m_private_data.GetSize() >= 3)
2067     {
2068         const binary* p_data = m_private_data.GetBuffer();
2069 /*        if ( p_data[0] == MATROSKA_DVD_LEVEL_TT )
2070         {
2071             uint16_t i_title = (p_data[1] << 8) + p_data[2];
2072             char psz_str[11];
2073             sprintf( psz_str, " %d  ---", i_title );
2074             result = N_("---  DVD Title");
2075             result += psz_str;
2076         }
2077         else */ if ( p_data[0] == MATROSKA_DVD_LEVEL_LU )
2078         {
2079             char psz_str[11];
2080             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
2081             result = N_("---  DVD Menu");
2082             result += psz_str;
2083         }
2084         else if ( p_data[0] == MATROSKA_DVD_LEVEL_SS && f_for_title )
2085         {
2086             if ( p_data[1] == 0x00 )
2087                 result = N_("First Played");
2088             else if ( p_data[1] == 0xC0 )
2089                 result = N_("Video Manager");
2090             else if ( p_data[1] == 0x80 )
2091             {
2092                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2093                 char psz_str[20];
2094                 sprintf( psz_str, " %d -----", i_title );
2095                 result = N_("----- Title");
2096                 result += psz_str;
2097             }
2098         }
2099     }
2100
2101     return result;
2102 }
2103
2104 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2105 {
2106     demux_sys_t        *p_sys = p_demux->p_sys;
2107     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2108     matroska_segment_c *p_segment = p_vsegment->Segment();
2109     mtime_t            i_time_offset = 0;
2110
2111     int         i_index;
2112
2113     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2114     if( i_date < 0 && f_percent < 0 )
2115     {
2116         msg_Warn( p_demux, "cannot seek nowhere !" );
2117         return;
2118     }
2119     if( f_percent > 1.0 )
2120     {
2121         msg_Warn( p_demux, "cannot seek so far !" );
2122         return;
2123     }
2124
2125     /* seek without index or without date */
2126     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2127     {
2128         if (p_sys->f_duration >= 0)
2129         {
2130             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2131         }
2132         else
2133         {
2134             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2135
2136             msg_Dbg( p_demux, "inacurate way of seeking" );
2137             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2138             {
2139                 if( p_segment->index[i_index].i_position >= i_pos)
2140                 {
2141                     break;
2142                 }
2143             }
2144             if( i_index == p_segment->i_index )
2145             {
2146                 i_index--;
2147             }
2148
2149             i_date = p_segment->index[i_index].i_time;
2150
2151 #if 0
2152             if( p_segment->index[i_index].i_position < i_pos )
2153             {
2154                 EbmlElement *el;
2155
2156                 msg_Warn( p_demux, "searching for cluster, could take some time" );
2157
2158                 /* search a cluster */
2159                 while( ( el = p_sys->ep->Get() ) != NULL )
2160                 {
2161                     if( MKV_IS_ID( el, KaxCluster ) )
2162                     {
2163                         KaxCluster *cluster = (KaxCluster*)el;
2164
2165                         /* add it to the index */
2166                         p_segment->IndexAppendCluster( cluster );
2167
2168                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
2169                         {
2170                             p_sys->cluster = cluster;
2171                             p_sys->ep->Down();
2172                             break;
2173                         }
2174                     }
2175                 }
2176             }
2177 #endif
2178         }
2179     }
2180
2181     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
2182 }
2183
2184 /*****************************************************************************
2185  * Demux: reads and demuxes data packets
2186  *****************************************************************************
2187  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2188  *****************************************************************************/
2189 static int Demux( demux_t *p_demux)
2190 {
2191     demux_sys_t        *p_sys = p_demux->p_sys;
2192     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2193     matroska_segment_c *p_segmet = p_vsegment->Segment();
2194     if ( p_segmet == NULL ) return 0;
2195     int                i_block_count = 0;
2196
2197     KaxBlock *block;
2198     int64_t i_block_duration;
2199     int64_t i_block_ref1;
2200     int64_t i_block_ref2;
2201
2202     for( ;; )
2203     {
2204         if ( p_sys->demuxer.b_die )
2205             return 0;
2206
2207         if( p_sys->i_pts >= p_sys->i_start_pts  )
2208             if ( p_vsegment->UpdateCurrentToChapter( *p_demux ) )
2209                 return 1;
2210         
2211         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
2212         {
2213             /* nothing left to read in this ordered edition */
2214             if ( !p_vsegment->SelectNext() )
2215                 return 0;
2216             p_segmet->UnSelect( );
2217             
2218             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2219
2220             /* switch to the next segment */
2221             p_segmet = p_vsegment->Segment();
2222             if ( !p_segmet->Select( 0 ) )
2223             {
2224                 msg_Err( p_demux, "Failed to select new segment" );
2225                 return 0;
2226             }
2227             continue;
2228         }
2229
2230
2231         if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
2232         {
2233             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
2234             {
2235                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
2236                 // check if there are more chapters to read
2237                 if ( p_chap != NULL )
2238                 {
2239                     /* TODO handle successive chapters with the same user_start_time/user_end_time
2240                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
2241                         p_vsegment->SelectNext();
2242                     */
2243                     p_sys->i_pts = p_chap->i_user_end_time;
2244                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2245
2246                     return 1;
2247                 }
2248
2249                 return 0;
2250             }
2251             msg_Warn( p_demux, "cannot get block EOF?" );
2252             p_segmet->UnSelect( );
2253             
2254             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2255
2256             /* switch to the next segment */
2257             if ( !p_vsegment->SelectNext() )
2258                 // no more segments in this stream
2259                 return 0;
2260             p_segmet = p_vsegment->Segment();
2261             if ( !p_segmet->Select( 0 ) )
2262             {
2263                 msg_Err( p_demux, "Failed to select new segment" );
2264                 return 0;
2265             }
2266
2267             continue;
2268         }
2269
2270         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2271
2272         if( p_sys->i_pts >= p_sys->i_start_pts  )
2273         {
2274             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2275         }
2276
2277         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2278
2279         delete block;
2280         i_block_count++;
2281
2282         // TODO optimize when there is need to leave or when seeking has been called
2283         if( i_block_count > 5 )
2284         {
2285             return 1;
2286         }
2287     }
2288 }
2289
2290
2291
2292 /*****************************************************************************
2293  * Stream managment
2294  *****************************************************************************/
2295 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2296 {
2297     s = s_;
2298     mb_eof = VLC_FALSE;
2299 }
2300
2301 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2302 {
2303     if( i_size <= 0 || mb_eof )
2304     {
2305         return 0;
2306     }
2307
2308     return stream_Read( s, p_buffer, i_size );
2309 }
2310 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2311 {
2312     int64_t i_pos;
2313
2314     switch( mode )
2315     {
2316         case seek_beginning:
2317             i_pos = i_offset;
2318             break;
2319         case seek_end:
2320             i_pos = stream_Size( s ) - i_offset;
2321             break;
2322         default:
2323             i_pos= stream_Tell( s ) + i_offset;
2324             break;
2325     }
2326
2327     if( i_pos < 0 || i_pos >= stream_Size( s ) )
2328     {
2329         mb_eof = VLC_TRUE;
2330         return;
2331     }
2332
2333     mb_eof = VLC_FALSE;
2334     if( stream_Seek( s, i_pos ) )
2335     {
2336         mb_eof = VLC_TRUE;
2337     }
2338     return;
2339 }
2340 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2341 {
2342     return 0;
2343 }
2344 uint64 vlc_stream_io_callback::getFilePointer( void )
2345 {
2346     return stream_Tell( s );
2347 }
2348 void vlc_stream_io_callback::close( void )
2349 {
2350     return;
2351 }
2352
2353
2354 /*****************************************************************************
2355  * Ebml Stream parser
2356  *****************************************************************************/
2357 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2358 {
2359     int i;
2360
2361     m_es = es;
2362     m_got = NULL;
2363     m_el[0] = el_start;
2364     mi_remain_size[0] = el_start->GetSize();
2365
2366     for( i = 1; i < 6; i++ )
2367     {
2368         m_el[i] = NULL;
2369     }
2370     mi_level = 1;
2371     mi_user_level = 1;
2372     mb_keep = VLC_FALSE;
2373     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2374 }
2375
2376 EbmlParser::~EbmlParser( void )
2377 {
2378     int i;
2379
2380     for( i = 1; i < mi_level; i++ )
2381     {
2382         if( !mb_keep )
2383         {
2384             delete m_el[i];
2385         }
2386         mb_keep = VLC_FALSE;
2387     }
2388 }
2389
2390 void EbmlParser::Up( void )
2391 {
2392     if( mi_user_level == mi_level )
2393     {
2394         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2395     }
2396
2397     mi_user_level--;
2398 }
2399
2400 void EbmlParser::Down( void )
2401 {
2402     mi_user_level++;
2403     mi_level++;
2404 }
2405
2406 void EbmlParser::Keep( void )
2407 {
2408     mb_keep = VLC_TRUE;
2409 }
2410
2411 int EbmlParser::GetLevel( void )
2412 {
2413     return mi_user_level;
2414 }
2415
2416 void EbmlParser::Reset( demux_t *p_demux )
2417 {
2418     while ( mi_level > 0)
2419     {
2420         delete m_el[mi_level];
2421         m_el[mi_level] = NULL;
2422         mi_level--;
2423     }
2424     mi_user_level = mi_level = 1;
2425 #if LIBEBML_VERSION >= 0x000704
2426     // a little faster and cleaner
2427     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2428 #else
2429     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2430 #endif
2431     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2432 }
2433
2434 EbmlElement *EbmlParser::Get( void )
2435 {
2436     int i_ulev = 0;
2437
2438     if( mi_user_level != mi_level )
2439     {
2440         return NULL;
2441     }
2442     if( m_got )
2443     {
2444         EbmlElement *ret = m_got;
2445         m_got = NULL;
2446
2447         return ret;
2448     }
2449
2450     if( m_el[mi_level] )
2451     {
2452         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2453         if( !mb_keep )
2454         {
2455             delete m_el[mi_level];
2456         }
2457         mb_keep = VLC_FALSE;
2458     }
2459
2460     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2461 //    mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2462     if( i_ulev > 0 )
2463     {
2464         while( i_ulev > 0 )
2465         {
2466             if( mi_level == 1 )
2467             {
2468                 mi_level = 0;
2469                 return NULL;
2470             }
2471
2472             delete m_el[mi_level - 1];
2473             m_got = m_el[mi_level -1] = m_el[mi_level];
2474             m_el[mi_level] = NULL;
2475
2476             mi_level--;
2477             i_ulev--;
2478         }
2479         return NULL;
2480     }
2481     else if( m_el[mi_level] == NULL )
2482     {
2483         fprintf( stderr," m_el[mi_level] == NULL\n" );
2484     }
2485
2486     return m_el[mi_level];
2487 }
2488
2489
2490 /*****************************************************************************
2491  * Tools
2492  *  * LoadCues : load the cues element and update index
2493  *
2494  *  * LoadTags : load ... the tags element
2495  *
2496  *  * InformationCreate : create all information, load tags if present
2497  *
2498  *****************************************************************************/
2499 void matroska_segment_c::LoadCues( )
2500 {
2501     int64_t     i_sav_position = es.I_O().getFilePointer();
2502     EbmlParser  *ep;
2503     EbmlElement *el, *cues;
2504
2505     /* *** Load the cue if found *** */
2506     if( i_cues_position < 0 )
2507     {
2508         msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2509
2510 //        IndexAppendCluster( cluster );
2511     }
2512
2513     vlc_bool_t b_seekable;
2514
2515     stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2516     if( !b_seekable )
2517         return;
2518
2519     msg_Dbg( &sys.demuxer, "loading cues" );
2520     es.I_O().setFilePointer( i_cues_position, seek_beginning );
2521     cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2522
2523     if( cues == NULL )
2524     {
2525         msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2526         es.I_O().setFilePointer( i_sav_position, seek_beginning );
2527         return;
2528     }
2529
2530     ep = new EbmlParser( &es, cues, &sys.demuxer );
2531     while( ( el = ep->Get() ) != NULL )
2532     {
2533         if( MKV_IS_ID( el, KaxCuePoint ) )
2534         {
2535 #define idx index[i_index]
2536
2537             idx.i_track       = -1;
2538             idx.i_block_number= -1;
2539             idx.i_position    = -1;
2540             idx.i_time        = 0;
2541             idx.b_key         = VLC_TRUE;
2542
2543             ep->Down();
2544             while( ( el = ep->Get() ) != NULL )
2545             {
2546                 if( MKV_IS_ID( el, KaxCueTime ) )
2547                 {
2548                     KaxCueTime &ctime = *(KaxCueTime*)el;
2549
2550                     ctime.ReadData( es.I_O() );
2551
2552                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2553                 }
2554                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2555                 {
2556                     ep->Down();
2557                     while( ( el = ep->Get() ) != NULL )
2558                     {
2559                         if( MKV_IS_ID( el, KaxCueTrack ) )
2560                         {
2561                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2562
2563                             ctrack.ReadData( es.I_O() );
2564                             idx.i_track = uint16( ctrack );
2565                         }
2566                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2567                         {
2568                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2569
2570                             ccpos.ReadData( es.I_O() );
2571                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2572                         }
2573                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2574                         {
2575                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2576
2577                             cbnum.ReadData( es.I_O() );
2578                             idx.i_block_number = uint32( cbnum );
2579                         }
2580                         else
2581                         {
2582                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
2583                         }
2584                     }
2585                     ep->Up();
2586                 }
2587                 else
2588                 {
2589                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
2590                 }
2591             }
2592             ep->Up();
2593
2594 #if 0
2595             msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2596                      " track=%d bnum=%d", idx.i_time, idx.i_position,
2597                      idx.i_track, idx.i_block_number );
2598 #endif
2599
2600             i_index++;
2601             if( i_index >= i_index_max )
2602             {
2603                 i_index_max += 1024;
2604                 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2605             }
2606 #undef idx
2607         }
2608         else
2609         {
2610             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2611         }
2612     }
2613     delete ep;
2614     delete cues;
2615
2616     b_cues = VLC_TRUE;
2617
2618     msg_Dbg( &sys.demuxer, "loading cues done." );
2619     es.I_O().setFilePointer( i_sav_position, seek_beginning );
2620 }
2621
2622 void matroska_segment_c::LoadTags( )
2623 {
2624     int64_t     i_sav_position = es.I_O().getFilePointer();
2625     EbmlParser  *ep;
2626     EbmlElement *el, *tags;
2627
2628     msg_Dbg( &sys.demuxer, "loading tags" );
2629     es.I_O().setFilePointer( i_tags_position, seek_beginning );
2630     tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2631
2632     if( tags == NULL )
2633     {
2634         msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2635         es.I_O().setFilePointer( i_sav_position, seek_beginning );
2636         return;
2637     }
2638
2639     msg_Dbg( &sys.demuxer, "Tags" );
2640     ep = new EbmlParser( &es, tags, &sys.demuxer );
2641     while( ( el = ep->Get() ) != NULL )
2642     {
2643         if( MKV_IS_ID( el, KaxTag ) )
2644         {
2645             msg_Dbg( &sys.demuxer, "+ Tag" );
2646             ep->Down();
2647             while( ( el = ep->Get() ) != NULL )
2648             {
2649                 if( MKV_IS_ID( el, KaxTagTargets ) )
2650                 {
2651                     msg_Dbg( &sys.demuxer, "|   + Targets" );
2652                     ep->Down();
2653                     while( ( el = ep->Get() ) != NULL )
2654                     {
2655                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2656                     }
2657                     ep->Up();
2658                 }
2659                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2660                 {
2661                     msg_Dbg( &sys.demuxer, "|   + General" );
2662                     ep->Down();
2663                     while( ( el = ep->Get() ) != NULL )
2664                     {
2665                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2666                     }
2667                     ep->Up();
2668                 }
2669                 else if( MKV_IS_ID( el, KaxTagGenres ) )
2670                 {
2671                     msg_Dbg( &sys.demuxer, "|   + Genres" );
2672                     ep->Down();
2673                     while( ( el = ep->Get() ) != NULL )
2674                     {
2675                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2676                     }
2677                     ep->Up();
2678                 }
2679                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2680                 {
2681                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
2682                     ep->Down();
2683                     while( ( el = ep->Get() ) != NULL )
2684                     {
2685                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2686                     }
2687                     ep->Up();
2688                 }
2689                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2690                 {
2691                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
2692                     ep->Down();
2693                     while( ( el = ep->Get() ) != NULL )
2694                     {
2695                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2696                     }
2697                     ep->Up();
2698                 }
2699                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2700                 {
2701                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
2702                 }
2703                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2704                 {
2705                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
2706                 }
2707                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2708                 {
2709                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
2710                 }
2711                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2712                 {
2713                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
2714                 }
2715                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2716                 {
2717                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
2718                 }
2719                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2720                 {
2721                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
2722                 }
2723                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2724                 {
2725                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
2726                 }
2727                 else
2728                 {
2729                     msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid( *el ).name() );
2730                 }
2731             }
2732             ep->Up();
2733         }
2734         else
2735         {
2736             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2737         }
2738     }
2739     delete ep;
2740     delete tags;
2741
2742     msg_Dbg( &sys.demuxer, "loading tags done." );
2743     es.I_O().setFilePointer( i_sav_position, seek_beginning );
2744 }
2745
2746 /*****************************************************************************
2747  * ParseSeekHead:
2748  *****************************************************************************/
2749 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2750 {
2751     EbmlElement *el;
2752     size_t i, j;
2753     int i_upper_level = 0;
2754
2755     msg_Dbg( &sys.demuxer, "|   + Seek head" );
2756
2757     /* Master elements */
2758     seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2759
2760     for( i = 0; i < seekhead->ListSize(); i++ )
2761     {
2762         EbmlElement *l = (*seekhead)[i];
2763
2764         if( MKV_IS_ID( l, KaxSeek ) )
2765         {
2766             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2767             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2768             int64_t i_pos = -1;
2769
2770             for( j = 0; j < sk->ListSize(); j++ )
2771             {
2772                 EbmlElement *l = (*sk)[j];
2773
2774                 if( MKV_IS_ID( l, KaxSeekID ) )
2775                 {
2776                     KaxSeekID &sid = *(KaxSeekID*)l;
2777                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2778                 }
2779                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2780                 {
2781                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2782                     i_pos = uint64( spos );
2783                 }
2784                 else
2785                 {
2786                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2787                 }
2788             }
2789
2790             if( i_pos >= 0 )
2791             {
2792                 if( id == KaxCues::ClassInfos.GlobalId )
2793                 {
2794                     msg_Dbg( &sys.demuxer, "|   |   |   = cues at "I64Fd, i_pos );
2795                     i_cues_position = segment->GetGlobalPosition( i_pos );
2796                 }
2797                 else if( id == KaxChapters::ClassInfos.GlobalId )
2798                 {
2799                     msg_Dbg( &sys.demuxer, "|   |   |   = chapters at "I64Fd, i_pos );
2800                     i_chapters_position = segment->GetGlobalPosition( i_pos );
2801                 }
2802                 else if( id == KaxTags::ClassInfos.GlobalId )
2803                 {
2804                     msg_Dbg( &sys.demuxer, "|   |   |   = tags at "I64Fd, i_pos );
2805                     i_tags_position = segment->GetGlobalPosition( i_pos );
2806                 }
2807             }
2808         }
2809         else
2810         {
2811             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
2812         }
2813     }
2814 }
2815
2816 /*****************************************************************************
2817  * ParseTrackEntry:
2818  *****************************************************************************/
2819 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2820 {
2821     size_t i, j, k, n;
2822
2823     mkv_track_t *tk;
2824
2825     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
2826
2827     tk = new mkv_track_t();
2828     tracks.push_back( tk );
2829
2830     /* Init the track */
2831     memset( tk, 0, sizeof( mkv_track_t ) );
2832
2833     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2834     tk->fmt.psz_language = strdup("English");
2835     tk->fmt.psz_description = NULL;
2836
2837     tk->b_default = VLC_TRUE;
2838     tk->b_enabled = VLC_TRUE;
2839     tk->b_silent = VLC_FALSE;
2840     tk->i_number = tracks.size() - 1;
2841     tk->i_extra_data = 0;
2842     tk->p_extra_data = NULL;
2843     tk->psz_codec = NULL;
2844     tk->i_default_duration = 0;
2845     tk->f_timecodescale = 1.0;
2846
2847     tk->b_inited = VLC_FALSE;
2848     tk->i_data_init = 0;
2849     tk->p_data_init = NULL;
2850
2851     tk->psz_codec_name = NULL;
2852     tk->psz_codec_settings = NULL;
2853     tk->psz_codec_info_url = NULL;
2854     tk->psz_codec_download_url = NULL;
2855     
2856     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2857
2858     for( i = 0; i < m->ListSize(); i++ )
2859     {
2860         EbmlElement *l = (*m)[i];
2861
2862         if( MKV_IS_ID( l, KaxTrackNumber ) )
2863         {
2864             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2865
2866             tk->i_number = uint32( tnum );
2867             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
2868         }
2869         else  if( MKV_IS_ID( l, KaxTrackUID ) )
2870         {
2871             KaxTrackUID &tuid = *(KaxTrackUID*)l;
2872
2873             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
2874         }
2875         else  if( MKV_IS_ID( l, KaxTrackType ) )
2876         {
2877             char *psz_type;
2878             KaxTrackType &ttype = *(KaxTrackType*)l;
2879
2880             switch( uint8(ttype) )
2881             {
2882                 case track_audio:
2883                     psz_type = "audio";
2884                     tk->fmt.i_cat = AUDIO_ES;
2885                     break;
2886                 case track_video:
2887                     psz_type = "video";
2888                     tk->fmt.i_cat = VIDEO_ES;
2889                     break;
2890                 case track_subtitle:
2891                     psz_type = "subtitle";
2892                     tk->fmt.i_cat = SPU_ES;
2893                     break;
2894                 default:
2895                     psz_type = "unknown";
2896                     tk->fmt.i_cat = UNKNOWN_ES;
2897                     break;
2898             }
2899
2900             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
2901         }
2902 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2903 //        {
2904 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2905
2906 //            tk->b_enabled = uint32( fenb );
2907 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
2908 //                     uint32( fenb )  );
2909 //        }
2910         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2911         {
2912             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2913
2914             tk->b_default = uint32( fdef );
2915             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
2916         }
2917         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2918         {
2919             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2920
2921             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
2922         }
2923         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
2924         {
2925             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2926
2927             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
2928         }
2929         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2930         {
2931             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2932
2933             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
2934         }
2935         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2936         {
2937             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2938
2939             tk->i_default_duration = uint64(defd);
2940             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
2941         }
2942         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2943         {
2944             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2945
2946             tk->f_timecodescale = float( ttcs );
2947             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
2948         }
2949         else if( MKV_IS_ID( l, KaxTrackName ) )
2950         {
2951             KaxTrackName &tname = *(KaxTrackName*)l;
2952
2953             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2954             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
2955         }
2956         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
2957         {
2958             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2959
2960             tk->fmt.psz_language = strdup( string( lang ).c_str() );
2961             msg_Dbg( &sys.demuxer,
2962                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
2963         }
2964         else  if( MKV_IS_ID( l, KaxCodecID ) )
2965         {
2966             KaxCodecID &codecid = *(KaxCodecID*)l;
2967
2968             tk->psz_codec = strdup( string( codecid ).c_str() );
2969             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2970         }
2971         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2972         {
2973             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2974
2975             tk->i_extra_data = cpriv.GetSize();
2976             if( tk->i_extra_data > 0 )
2977             {
2978                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2979                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2980             }
2981             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2982         }
2983         else if( MKV_IS_ID( l, KaxCodecName ) )
2984         {
2985             KaxCodecName &cname = *(KaxCodecName*)l;
2986
2987             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2988             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2989         }
2990         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2991         {
2992             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2993             MkvTree( sys.demuxer, 3, "Content Encodings" );
2994             for( j = 0; j < cencs->ListSize(); j++ )
2995             {
2996                 EbmlElement *l2 = (*cencs)[j];
2997                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2998                 {
2999                     MkvTree( sys.demuxer, 4, "Content Encoding" );
3000                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
3001                     for( k = 0; k < cenc->ListSize(); k++ )
3002                     {
3003                         EbmlElement *l3 = (*cenc)[k];
3004                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
3005                         {
3006                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
3007                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
3008                         }
3009                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
3010                         {
3011                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
3012                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
3013                         }
3014                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
3015                         {
3016                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
3017                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
3018                         }
3019                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
3020                         {
3021                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
3022                             MkvTree( sys.demuxer, 5, "Content Compression" );
3023                             for( n = 0; n < compr->ListSize(); n++ )
3024                             {
3025                                 EbmlElement *l4 = (*compr)[n];
3026                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
3027                                 {
3028                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
3029                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
3030                                     if( uint32( compalg ) == 0 )
3031                                     {
3032                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
3033                                     }
3034                                 }
3035                                 else
3036                                 {
3037                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
3038                                 }
3039                             }
3040                         }
3041
3042                         else
3043                         {
3044                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
3045                         }
3046                     }
3047                     
3048                 }
3049                 else
3050                 {
3051                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
3052                 }
3053             }
3054                 
3055         }
3056 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
3057 //        {
3058 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
3059
3060 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
3061 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
3062 //        }
3063 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
3064 //        {
3065 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
3066
3067 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3068 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
3069 //        }
3070 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3071 //        {
3072 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3073
3074 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3075 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
3076 //        }
3077 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3078 //        {
3079 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3080
3081 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3082 //        }
3083 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3084 //        {
3085 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3086
3087 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3088 //        }
3089         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
3090         {
3091             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3092             unsigned int j;
3093
3094             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
3095             tk->f_fps = 0.0;
3096
3097             for( j = 0; j < tkv->ListSize(); j++ )
3098             {
3099                 EbmlElement *l = (*tkv)[j];
3100 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3101 //                {
3102 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3103
3104 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
3105 //                }
3106 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3107 //                {
3108 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3109
3110 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
3111 //                }
3112 //                else
3113                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3114                 {
3115                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3116
3117                     tk->fmt.video.i_width = uint16( vwidth );
3118                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
3119                 }
3120                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3121                 {
3122                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3123
3124                     tk->fmt.video.i_height = uint16( vheight );
3125                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
3126                 }
3127                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3128                 {
3129                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3130
3131                     tk->fmt.video.i_visible_width = uint16( vwidth );
3132                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
3133                 }
3134                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
3135                 {
3136                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
3137
3138                     tk->fmt.video.i_visible_height = uint16( vheight );
3139                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
3140                 }
3141                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
3142                 {
3143                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
3144
3145                     tk->f_fps = float( vfps );
3146                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
3147                 }
3148 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
3149 //                {
3150 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
3151
3152 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
3153 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
3154 //                }
3155 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
3156 //                {
3157 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
3158
3159 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
3160 //                }
3161 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
3162 //                {
3163 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
3164
3165 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( gamma ) );
3166 //                }
3167                 else
3168                 {
3169                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
3170                 }
3171             }
3172             if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
3173                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
3174         }
3175         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
3176         {
3177             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
3178             unsigned int j;
3179
3180             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
3181
3182             for( j = 0; j < tka->ListSize(); j++ )
3183             {
3184                 EbmlElement *l = (*tka)[j];
3185
3186                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
3187                 {
3188                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
3189
3190                     tk->fmt.audio.i_rate = (int)float( afreq );
3191                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
3192                 }
3193                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
3194                 {
3195                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
3196
3197                     tk->fmt.audio.i_channels = uint8( achan );
3198                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
3199                 }
3200                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
3201                 {
3202                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
3203
3204                     tk->fmt.audio.i_bitspersample = uint8( abits );
3205                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
3206                 }
3207                 else
3208                 {
3209                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
3210                 }
3211             }
3212         }
3213         else
3214         {
3215             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
3216                      typeid(*l).name() );
3217         }
3218     }
3219 }
3220
3221 /*****************************************************************************
3222  * ParseTracks:
3223  *****************************************************************************/
3224 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
3225 {
3226     EbmlElement *el;
3227     unsigned int i;
3228     int i_upper_level = 0;
3229
3230     msg_Dbg( &sys.demuxer, "|   + Tracks" );
3231
3232     /* Master elements */
3233     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
3234
3235     for( i = 0; i < tracks->ListSize(); i++ )
3236     {
3237         EbmlElement *l = (*tracks)[i];
3238
3239         if( MKV_IS_ID( l, KaxTrackEntry ) )
3240         {
3241             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
3242         }
3243         else
3244         {
3245             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3246         }
3247     }
3248 }
3249
3250 /*****************************************************************************
3251  * ParseInfo:
3252  *****************************************************************************/
3253 void matroska_segment_c::ParseInfo( KaxInfo *info )
3254 {
3255     EbmlElement *el;
3256     EbmlMaster  *m;
3257     size_t i, j;
3258     int i_upper_level = 0;
3259
3260     msg_Dbg( &sys.demuxer, "|   + Information" );
3261
3262     /* Master elements */
3263     m = static_cast<EbmlMaster *>(info);
3264     m->Read( es, info->Generic().Context, i_upper_level, el, true );
3265
3266     for( i = 0; i < m->ListSize(); i++ )
3267     {
3268         EbmlElement *l = (*m)[i];
3269
3270         if( MKV_IS_ID( l, KaxSegmentUID ) )
3271         {
3272             segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3273
3274             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3275         }
3276         else if( MKV_IS_ID( l, KaxPrevUID ) )
3277         {
3278             prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3279
3280             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3281         }
3282         else if( MKV_IS_ID( l, KaxNextUID ) )
3283         {
3284             next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3285
3286             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3287         }
3288         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3289         {
3290             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3291
3292             i_timescale = uint64(tcs);
3293
3294             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale="I64Fd,
3295                      i_timescale );
3296         }
3297         else if( MKV_IS_ID( l, KaxDuration ) )
3298         {
3299             KaxDuration &dur = *(KaxDuration*)l;
3300
3301             i_duration = mtime_t( double( dur ) );
3302
3303             msg_Dbg( &sys.demuxer, "|   |   + Duration="I64Fd,
3304                      i_duration );
3305         }
3306         else if( MKV_IS_ID( l, KaxMuxingApp ) )
3307         {
3308             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3309
3310             psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3311
3312             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
3313                      psz_muxing_application );
3314         }
3315         else if( MKV_IS_ID( l, KaxWritingApp ) )
3316         {
3317             KaxWritingApp &wapp = *(KaxWritingApp*)l;
3318
3319             psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3320
3321             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
3322                      psz_writing_application );
3323         }
3324         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3325         {
3326             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3327
3328             psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3329
3330             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
3331                      psz_segment_filename );
3332         }
3333         else if( MKV_IS_ID( l, KaxTitle ) )
3334         {
3335             KaxTitle &title = *(KaxTitle*)l;
3336
3337             psz_title = UTF8ToStr( UTFstring( title ) );
3338
3339             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
3340         }
3341         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3342         {
3343             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3344
3345             families.push_back(*uid);
3346
3347             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
3348         }
3349 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3350         else if( MKV_IS_ID( l, KaxDateUTC ) )
3351         {
3352             KaxDateUTC &date = *(KaxDateUTC*)l;
3353             time_t i_date;
3354             struct tm tmres;
3355             char   buffer[256];
3356
3357             i_date = date.GetEpochDate();
3358             memset( buffer, 0, 256 );
3359             if( gmtime_r( &i_date, &tmres ) &&
3360                 asctime_r( &tmres, buffer ) )
3361             {
3362                 buffer[strlen( buffer)-1]= '\0';
3363                 psz_date_utc = strdup( buffer );
3364                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
3365             }
3366         }
3367 #endif
3368 #if LIBMATROSKA_VERSION >= 0x000704
3369         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3370         {
3371             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3372             chapter_translation_c translated;
3373
3374             p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3375             for( j = 0; j < p_trans->ListSize(); j++ )
3376             {
3377                 EbmlElement *l = (*p_trans)[j];
3378
3379                 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3380                 {
3381                     translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3382                 }
3383                 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3384                 {
3385                     translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3386                 }
3387                 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3388                 {
3389                     translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3390                 }
3391             }
3392
3393             translations.push_back( translated );
3394         }
3395 #endif
3396         else
3397         {
3398             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3399         }
3400     }
3401
3402     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3403     i_duration = mtime_t(f_dur);
3404 }
3405
3406
3407 /*****************************************************************************
3408  * ParseChapterAtom
3409  *****************************************************************************/
3410 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3411 {
3412     size_t i, j;
3413
3414     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
3415     for( i = 0; i < ca->ListSize(); i++ )
3416     {
3417         EbmlElement *l = (*ca)[i];
3418
3419         if( MKV_IS_ID( l, KaxChapterUID ) )
3420         {
3421             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3422             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
3423         }
3424         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3425         {
3426             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3427             chapters.b_display_seekpoint = uint8( flag ) == 0;
3428
3429             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3430         }
3431         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3432         {
3433             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3434             chapters.i_start_time = uint64( start ) / I64C(1000);
3435
3436             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
3437         }
3438         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3439         {
3440             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3441             chapters.i_end_time = uint64( end ) / I64C(1000);
3442
3443             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
3444         }
3445         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3446         {
3447             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3448
3449             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
3450             for( j = 0; j < cd->ListSize(); j++ )
3451             {
3452                 EbmlElement *l= (*cd)[j];
3453
3454                 if( MKV_IS_ID( l, KaxChapterString ) )
3455                 {
3456                     int k;
3457
3458                     KaxChapterString &name =*(KaxChapterString*)l;
3459                     for (k = 0; k < i_level; k++)
3460                         chapters.psz_name += '+';
3461                     chapters.psz_name += ' ';
3462                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3463                     chapters.b_user_display = true;
3464
3465                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
3466                 }
3467                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
3468                 {
3469                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
3470                     const char *psz = string( lang ).c_str();
3471
3472                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
3473                 }
3474                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
3475                 {
3476                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
3477                     const char *psz = string( ct ).c_str();
3478
3479                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
3480                 }
3481             }
3482         }
3483         else if( MKV_IS_ID( l, KaxChapterProcess ) )
3484         {
3485             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterProcess" );
3486
3487             KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
3488             chapter_codec_cmds_c *p_ccodec = NULL;
3489
3490             for( j = 0; j < cp->ListSize(); j++ )
3491             {
3492                 EbmlElement *k= (*cp)[j];
3493
3494                 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
3495                 {
3496                     KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
3497                     if ( uint32(*p_codec_id) == 0 )
3498                         p_ccodec = new matroska_script_codec_c( sys );
3499                     else if ( uint32(*p_codec_id) == 1 )
3500                         p_ccodec = new dvd_chapter_codec_c( sys );
3501                     break;
3502                 }
3503             }
3504
3505             if ( p_ccodec != NULL )
3506             {
3507                 for( j = 0; j < cp->ListSize(); j++ )
3508                 {
3509                     EbmlElement *k= (*cp)[j];
3510
3511                     if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
3512                     {
3513                         KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
3514                         p_ccodec->SetPrivate( *p_private );
3515                     }
3516                     else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
3517                     {
3518                         p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
3519                     }
3520                 }
3521                 chapters.codecs.push_back( p_ccodec );
3522             }
3523         }
3524         else if( MKV_IS_ID( l, KaxChapterAtom ) )
3525         {
3526             chapter_item_c *new_sub_chapter = new chapter_item_c();
3527             ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3528             new_sub_chapter->psz_parent = &chapters;
3529             chapters.sub_chapters.push_back( new_sub_chapter );
3530         }
3531     }
3532 }
3533
3534 /*****************************************************************************
3535  * ParseChapters:
3536  *****************************************************************************/
3537 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
3538 {
3539     EbmlElement *el;
3540     size_t i;
3541     int i_upper_level = 0;
3542     mtime_t i_dur;
3543
3544     /* Master elements */
3545     chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
3546
3547     for( i = 0; i < chapters->ListSize(); i++ )
3548     {
3549         EbmlElement *l = (*chapters)[i];
3550
3551         if( MKV_IS_ID( l, KaxEditionEntry ) )
3552         {
3553             chapter_edition_c *p_edition = new chapter_edition_c();
3554             
3555             EbmlMaster *E = static_cast<EbmlMaster *>(l );
3556             size_t j;
3557             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
3558             for( j = 0; j < E->ListSize(); j++ )
3559             {
3560                 EbmlElement *l = (*E)[j];
3561
3562                 if( MKV_IS_ID( l, KaxChapterAtom ) )
3563                 {
3564                     chapter_item_c *new_sub_chapter = new chapter_item_c();
3565                     ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
3566                     p_edition->sub_chapters.push_back( new_sub_chapter );
3567                 }
3568                 else if( MKV_IS_ID( l, KaxEditionUID ) )
3569                 {
3570                     p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3571                 }
3572                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3573                 {
3574                     p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3575                 }
3576                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3577                 {
3578                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3579                         i_default_edition = stored_editions.size();
3580                 }
3581                 else
3582                 {
3583                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
3584                 }
3585             }
3586             stored_editions.push_back( p_edition );
3587         }
3588         else
3589         {
3590             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3591         }
3592     }
3593
3594     for( i = 0; i < stored_editions.size(); i++ )
3595     {
3596         stored_editions[i]->RefreshChapters( );
3597     }
3598     
3599     if ( stored_editions[i_default_edition]->b_ordered )
3600     {
3601         /* update the duration of the segment according to the sum of all sub chapters */
3602         i_dur = stored_editions[i_default_edition]->Duration() / I64C(1000);
3603         if (i_dur > 0)
3604             i_duration = i_dur;
3605     }
3606 }
3607
3608 void matroska_segment_c::ParseCluster( )
3609 {
3610     EbmlElement *el;
3611     EbmlMaster  *m;
3612     unsigned int i;
3613     int i_upper_level = 0;
3614
3615     /* Master elements */
3616     m = static_cast<EbmlMaster *>( cluster );
3617     m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3618
3619     for( i = 0; i < m->ListSize(); i++ )
3620     {
3621         EbmlElement *l = (*m)[i];
3622
3623         if( MKV_IS_ID( l, KaxClusterTimecode ) )
3624         {
3625             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3626
3627             cluster->InitTimecode( uint64( ctc ), i_timescale );
3628             break;
3629         }
3630     }
3631
3632     i_start_time = cluster->GlobalTimecode() / 1000;
3633 }
3634
3635 /*****************************************************************************
3636  * InformationCreate:
3637  *****************************************************************************/
3638 void matroska_segment_c::InformationCreate( )
3639 {
3640     size_t      i_track;
3641
3642     sys.meta = vlc_meta_New();
3643
3644     if( psz_title )
3645     {
3646         vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3647     }
3648     if( psz_date_utc )
3649     {
3650         vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3651     }
3652     if( psz_segment_filename )
3653     {
3654         vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3655     }
3656     if( psz_muxing_application )
3657     {
3658         vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3659     }
3660     if( psz_writing_application )
3661     {
3662         vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3663     }
3664
3665     for( i_track = 0; i_track < tracks.size(); i_track++ )
3666     {
3667         mkv_track_t *tk = tracks[i_track];
3668         vlc_meta_t *mtk = vlc_meta_New();
3669
3670         sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3671                                                     sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3672         sys.meta->track[sys.meta->i_track++] = mtk;
3673
3674         if( tk->fmt.psz_description )
3675         {
3676             vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3677         }
3678         if( tk->psz_codec_name )
3679         {
3680             vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3681         }
3682         if( tk->psz_codec_settings )
3683         {
3684             vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3685         }
3686         if( tk->psz_codec_info_url )
3687         {
3688             vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3689         }
3690         if( tk->psz_codec_download_url )
3691         {
3692             vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3693         }
3694     }
3695
3696     if( i_tags_position >= 0 )
3697     {
3698         vlc_bool_t b_seekable;
3699
3700         stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3701         if( b_seekable )
3702         {
3703             LoadTags( );
3704         }
3705     }
3706 }
3707
3708
3709 /*****************************************************************************
3710  * Divers
3711  *****************************************************************************/
3712
3713 void matroska_segment_c::IndexAppendCluster( KaxCluster *cluster )
3714 {
3715 #define idx index[i_index]
3716     idx.i_track       = -1;
3717     idx.i_block_number= -1;
3718     idx.i_position    = cluster->GetElementPosition();
3719     idx.i_time        = -1;
3720     idx.b_key         = VLC_TRUE;
3721
3722     i_index++;
3723     if( i_index >= i_index_max )
3724     {
3725         i_index_max += 1024;
3726         index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3727     }
3728 #undef idx
3729 }
3730
3731 static char * UTF8ToStr( const UTFstring &u )
3732 {
3733     int     i_src;
3734     const wchar_t *src;
3735     char *dst, *p;
3736
3737     i_src = u.length();
3738     src   = u.c_str();
3739
3740     p = dst = (char*)malloc( i_src + 1);
3741     while( i_src > 0 )
3742     {
3743         if( *src < 255 )
3744         {
3745             *p++ = (char)*src;
3746         }
3747         else
3748         {
3749             *p++ = '?';
3750         }
3751         src++;
3752         i_src--;
3753     }
3754     *p++= '\0';
3755
3756     return dst;
3757 }
3758
3759 void chapter_edition_c::RefreshChapters( )
3760 {
3761     chapter_item_c::RefreshChapters( b_ordered, -1 );
3762     b_display_seekpoint = false;
3763 }
3764
3765 int64_t chapter_item_c::RefreshChapters( bool b_ordered, int64_t i_prev_user_time )
3766 {
3767     int64_t i_user_time = i_prev_user_time;
3768     
3769     // first the sub-chapters, and then ourself
3770     std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3771     while ( index != sub_chapters.end() )
3772     {
3773         i_user_time = (*index)->RefreshChapters( b_ordered, i_user_time );
3774         index++;
3775     }
3776
3777     if ( b_ordered )
3778     {
3779         // the ordered chapters always start at zero
3780         if ( i_prev_user_time == -1 )
3781         {
3782             if ( i_user_time == -1 )
3783                 i_user_time = 0;
3784             i_prev_user_time = 0;
3785         }
3786
3787         i_user_start_time = i_prev_user_time;
3788         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3789         {
3790             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3791         }
3792         else
3793         {
3794             i_user_end_time = i_user_time;
3795         }
3796     }
3797     else
3798     {
3799         std::sort( sub_chapters.begin(), sub_chapters.end() );
3800         i_user_start_time = i_start_time;
3801         if ( i_end_time != -1 )
3802             i_user_end_time = i_end_time;
3803         else if ( i_user_time != -1 )
3804             i_user_end_time = i_user_time;
3805         else
3806             i_user_end_time = i_user_start_time;
3807     }
3808
3809     return i_user_end_time;
3810 }
3811
3812 mtime_t chapter_edition_c::Duration() const
3813 {
3814     mtime_t i_result = 0;
3815     
3816     if ( sub_chapters.size() )
3817     {
3818         std::vector<chapter_item_c*>::const_iterator index = sub_chapters.end();
3819         index--;
3820         i_result = (*index)->i_user_end_time;
3821     }
3822     
3823     return i_result;
3824 }
3825
3826 chapter_item_c *chapter_item_c::FindTimecode( mtime_t i_user_timecode )
3827 {
3828     chapter_item_c *psz_result = NULL;
3829
3830     if ( i_user_timecode >= i_user_start_time && 
3831         ( i_user_timecode < i_user_end_time || 
3832           ( i_user_start_time == i_user_end_time && i_user_timecode == i_user_end_time )))
3833     {
3834         std::vector<chapter_item_c*>::iterator index = sub_chapters.begin();
3835         while ( index != sub_chapters.end() && psz_result == NULL )
3836         {
3837             psz_result = (*index)->FindTimecode( i_user_timecode );
3838             index++;
3839         }
3840         
3841         if ( psz_result == NULL )
3842             psz_result = this;
3843     }
3844
3845     return psz_result;
3846 }
3847
3848 bool chapter_item_c::ParentOf( const chapter_item_c & item ) const
3849 {
3850     if ( &item == this )
3851         return true;
3852
3853     std::vector<chapter_item_c*>::const_iterator index = sub_chapters.begin();
3854     while ( index != sub_chapters.end() )
3855     {
3856         if ( (*index)->ParentOf( item ) )
3857             return true;
3858         index++;
3859     }
3860
3861     return false;
3862 }
3863
3864 void demux_sys_t::PreloadFamily( const matroska_segment_c & of_segment )
3865 {
3866     for (size_t i=0; i<opened_segments.size(); i++)
3867     {
3868         opened_segments[i]->PreloadFamily( of_segment );
3869     }
3870 }
3871 bool matroska_segment_c::PreloadFamily( const matroska_segment_c & of_segment )
3872 {
3873     if ( b_preloaded )
3874         return false;
3875
3876     for (size_t i=0; i<families.size(); i++)
3877     {
3878         for (size_t j=0; j<of_segment.families.size(); j++)
3879         {
3880             if ( families[i] == of_segment.families[j] )
3881                 return Preload( );
3882         }
3883     }
3884
3885     return false;
3886 }
3887
3888 // preload all the linked segments for all preloaded segments
3889 void demux_sys_t::PreloadLinked( matroska_segment_c *p_segment )
3890 {
3891     size_t i_preloaded, i, j;
3892     virtual_segment_c *p_seg;
3893
3894     p_current_segment = VirtualFromSegments( p_segment );
3895     
3896     used_segments.push_back( p_current_segment );
3897
3898     // create all the other virtual segments of the family
3899     do {
3900         i_preloaded = 0;
3901         for ( i=0; i< opened_segments.size(); i++ )
3902         {
3903             if ( opened_segments[i]->b_preloaded && !IsUsedSegment( *opened_segments[i] ) )
3904             {
3905                 p_seg = VirtualFromSegments( opened_segments[i] );
3906                 used_segments.push_back( p_seg );
3907                 i_preloaded++;
3908             }
3909         }
3910     } while ( i_preloaded ); // worst case: will stop when all segments are found as family related
3911
3912     // publish all editions of all usable segment
3913     for ( i=0; i< used_segments.size(); i++ )
3914     {
3915         p_seg = used_segments[i];
3916         if ( p_seg->p_editions != NULL )
3917         {
3918             std::string sz_name;
3919             input_title_t *p_title = vlc_input_title_New();
3920             p_seg->i_sys_title = i;
3921             int i_chapters;
3922
3923             // TODO use a name for each edition, let the TITLE deal with a codec name
3924             for ( j=0; j<p_seg->p_editions->size(); j++ )
3925             {
3926                 if ( p_title->psz_name == NULL )
3927                 {
3928                     sz_name = (*p_seg->p_editions)[j]->GetMainName();
3929                     if ( sz_name != "" )
3930                         p_title->psz_name = strdup( sz_name.c_str() );
3931                 }
3932
3933                 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
3934
3935                 i_chapters = 0;
3936                 p_edition->PublishChapters( *p_title, i_chapters, 0 );
3937             }
3938
3939             // create a name if there is none
3940             if ( p_title->psz_name == NULL )
3941             {
3942                 sz_name = N_("Segment ");
3943                 char psz_str[6];
3944                 sprintf( psz_str, "%d", i );
3945                 sz_name += psz_str;
3946                 p_title->psz_name = strdup( sz_name.c_str() );
3947             }
3948
3949             titles.push_back( *p_title );
3950         }
3951     }
3952 }
3953
3954 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
3955 {
3956     for ( size_t i=0; i< used_segments.size(); i++ )
3957     {
3958         if ( used_segments[i]->FindUID( segment.segment_uid ) )
3959             return true;
3960     }
3961     return false;
3962 }
3963
3964 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
3965 {
3966     size_t i_preloaded, i;
3967
3968     virtual_segment_c *p_result = new virtual_segment_c( p_segment );
3969
3970     // fill our current virtual segment with all hard linked segments
3971     do {
3972         i_preloaded = 0;
3973         for ( i=0; i< opened_segments.size(); i++ )
3974         {
3975             i_preloaded += p_result->AddSegment( opened_segments[i] );
3976         }
3977     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3978
3979     p_result->Sort( );
3980
3981     p_result->PreloadLinked( );
3982
3983     p_result->PrepareChapters( );
3984
3985     return p_result;
3986 }
3987
3988 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
3989 {
3990     if ( p_new_segment != NULL && p_new_segment != p_current_segment )
3991     {
3992         if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
3993             p_current_segment->Segment()->UnSelect();
3994
3995         p_current_segment = p_new_segment;
3996         i_current_title = p_new_segment->i_sys_title;
3997     }
3998
3999     p_current_segment->LoadCues();
4000     f_duration = p_current_segment->Duration();
4001
4002     /* add information */
4003     p_current_segment->Segment()->InformationCreate( );
4004
4005     p_current_segment->Segment()->Select( 0 );
4006
4007     return true;
4008 }
4009
4010 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
4011 {
4012     EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
4013     if ( *p_itema == p_item_b->prev_segment_uid )
4014         return true;
4015
4016     p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
4017     if ( *p_itema == p_item_b->segment_uid )
4018         return true;
4019
4020     if ( *p_itema == p_item_b->prev_segment_uid )
4021         return true;
4022
4023     return false;
4024 }
4025
4026 bool matroska_segment_c::Preload( )
4027 {
4028     if ( b_preloaded )
4029         return false;
4030
4031     EbmlElement *el = NULL;
4032
4033     ep->Reset( &sys.demuxer );
4034
4035     while( ( el = ep->Get() ) != NULL )
4036     {
4037         if( MKV_IS_ID( el, KaxInfo ) )
4038         {
4039             ParseInfo( static_cast<KaxInfo*>( el ) );
4040         }
4041         else if( MKV_IS_ID( el, KaxTracks ) )
4042         {
4043             ParseTracks( static_cast<KaxTracks*>( el ) );
4044         }
4045         else if( MKV_IS_ID( el, KaxSeekHead ) )
4046         {
4047             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
4048         }
4049         else if( MKV_IS_ID( el, KaxCues ) )
4050         {
4051             msg_Dbg( &sys.demuxer, "|   + Cues" );
4052         }
4053         else if( MKV_IS_ID( el, KaxCluster ) )
4054         {
4055             msg_Dbg( &sys.demuxer, "|   + Cluster" );
4056
4057             cluster = (KaxCluster*)el;
4058
4059             i_start_pos = cluster->GetElementPosition();
4060             ParseCluster( );
4061
4062             ep->Down();
4063             /* stop parsing the stream */
4064             break;
4065         }
4066         else if( MKV_IS_ID( el, KaxAttachments ) )
4067         {
4068             msg_Dbg( &sys.demuxer, "|   + Attachments FIXME (but probably never supported)" );
4069         }
4070         else if( MKV_IS_ID( el, KaxChapters ) )
4071         {
4072             msg_Dbg( &sys.demuxer, "|   + Chapters" );
4073             ParseChapters( static_cast<KaxChapters*>( el ) );
4074         }
4075         else if( MKV_IS_ID( el, KaxTag ) )
4076         {
4077             msg_Dbg( &sys.demuxer, "|   + Tags FIXME TODO" );
4078         }
4079         else
4080         {
4081             msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid(*el).name() );
4082         }
4083     }
4084
4085     b_preloaded = true;
4086
4087     return true;
4088 }
4089
4090 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4091 {
4092     for (size_t i=0; i<opened_segments.size(); i++)
4093     {
4094         if ( opened_segments[i]->segment_uid == uid )
4095             return opened_segments[i];
4096     }
4097     return NULL;
4098 }
4099
4100 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id, 
4101                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
4102                                         const void *p_cookie, 
4103                                         size_t i_cookie_size, 
4104                                         virtual_segment_c * &p_segment_found )
4105 {
4106     chapter_item_c *p_result = NULL;
4107     for (size_t i=0; i<used_segments.size(); i++)
4108     {
4109         p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4110         if ( p_result != NULL )
4111         {
4112             p_segment_found = used_segments[i];
4113             break;
4114         }
4115     }
4116     return p_result;
4117 }
4118
4119 chapter_item_c *demux_sys_t::FindChapter( int64_t i_find_uid, virtual_segment_c * & p_segment_found )
4120 {
4121     chapter_item_c *p_result = NULL;
4122     for (size_t i=0; i<used_segments.size(); i++)
4123     {
4124         p_result = used_segments[i]->FindChapter( i_find_uid );
4125         if ( p_result != NULL )
4126         {
4127             p_segment_found = used_segments[i];
4128             break;
4129         }
4130     }
4131     return p_result;
4132 }
4133
4134 void virtual_segment_c::Sort()
4135 {
4136     // keep the current segment index
4137     matroska_segment_c *p_segment = linked_segments[i_current_segment];
4138
4139     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
4140
4141     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
4142         if ( linked_segments[i_current_segment] == p_segment )
4143             break;
4144 }
4145
4146 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
4147 {
4148     size_t i;
4149     // check if it's not already in here
4150     for ( i=0; i<linked_segments.size(); i++ )
4151     {
4152         if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
4153             return 0;
4154     }
4155
4156     // find possible mates
4157     for ( i=0; i<linked_uids.size(); i++ )
4158     {
4159         if (   p_segment->segment_uid == linked_uids[i] 
4160             || p_segment->prev_segment_uid == linked_uids[i] 
4161             || p_segment->next_segment_uid == linked_uids[i] )
4162         {
4163             linked_segments.push_back( p_segment );
4164
4165             AppendUID( p_segment->prev_segment_uid );
4166             AppendUID( p_segment->next_segment_uid );
4167
4168             return 1;
4169         }
4170     }
4171     return 0;
4172 }
4173
4174 void virtual_segment_c::PreloadLinked( )
4175 {
4176     for ( size_t i=0; i<linked_segments.size(); i++ )
4177     {
4178         linked_segments[i]->Preload( );
4179     }
4180     i_current_edition = linked_segments[0]->i_default_edition;
4181 }
4182
4183 mtime_t virtual_segment_c::Duration() const
4184 {
4185     mtime_t i_duration;
4186     if ( linked_segments.size() == 0 )
4187         i_duration = 0;
4188     else {
4189         matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
4190 //        p_last_segment->ParseCluster( );
4191
4192         i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
4193     }
4194     return i_duration;
4195 }
4196
4197 void virtual_segment_c::LoadCues( )
4198 {
4199     for ( size_t i=0; i<linked_segments.size(); i++ )
4200     {
4201         linked_segments[i]->LoadCues();
4202     }
4203 }
4204
4205 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
4206 {
4207     if ( UID.GetBuffer() == NULL )
4208         return;
4209
4210     for (size_t i=0; i<linked_uids.size(); i++)
4211     {
4212         if ( UID == linked_uids[i] )
4213             return;
4214     }
4215     linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
4216 }
4217
4218 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
4219 {
4220     KaxBlock    *block;
4221     int         i_track_skipping;
4222     int64_t     i_block_duration;
4223     int64_t     i_block_ref1;
4224     int64_t     i_block_ref2;
4225     size_t      i_track;
4226     int64_t     i_seek_position = i_start_pos;
4227     int64_t     i_seek_time = i_start_time;
4228
4229     if ( i_index > 0 )
4230     {
4231         int i_idx = 0;
4232
4233         for( ; i_idx < i_index; i_idx++ )
4234         {
4235             if( index[i_idx].i_time + i_time_offset > i_date )
4236             {
4237                 break;
4238             }
4239         }
4240
4241         if( i_idx > 0 )
4242         {
4243             i_idx--;
4244         }
4245
4246         i_seek_position = index[i_idx].i_position;
4247         i_seek_time = index[i_idx].i_time;
4248     }
4249
4250     msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
4251                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
4252
4253     es.I_O().setFilePointer( i_seek_position, seek_beginning );
4254
4255     delete ep;
4256     ep = new EbmlParser( &es, segment, &sys.demuxer );
4257     cluster = NULL;
4258
4259     sys.i_start_pts = i_date;
4260
4261     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
4262
4263     /* now parse until key frame */
4264 #define tk  tracks[i_track]
4265     i_track_skipping = 0;
4266     for( i_track = 0; i_track < tracks.size(); i_track++ )
4267     {
4268         if( tk->fmt.i_cat == VIDEO_ES )
4269         {
4270             tk->b_search_keyframe = VLC_TRUE;
4271             i_track_skipping++;
4272         }
4273         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
4274     }
4275
4276
4277     while( i_track_skipping > 0 )
4278     {
4279         if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
4280         {
4281             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
4282
4283             return;
4284         }
4285
4286         for( i_track = 0; i_track < tracks.size(); i_track++ )
4287         {
4288             if( tk->i_number == block->TrackNum() )
4289             {
4290                 break;
4291             }
4292         }
4293
4294         sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
4295
4296         if( i_track < tracks.size() )
4297         {
4298             if( sys.i_pts >= sys.i_start_pts )
4299             {
4300                 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4301                 i_track_skipping = 0;
4302             }
4303             else if( tk->fmt.i_cat == VIDEO_ES )
4304             {
4305                 if( i_block_ref1 == -1 && tk->b_search_keyframe )
4306                 {
4307                     tk->b_search_keyframe = VLC_FALSE;
4308                     i_track_skipping--;
4309                 }
4310                 if( !tk->b_search_keyframe )
4311                 {
4312                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4313                 }
4314             } 
4315         }
4316
4317         delete block;
4318     }
4319 #undef tk
4320 }
4321
4322 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
4323 {
4324     demux_sys_t *p_sys = demuxer.p_sys;
4325     size_t i;
4326
4327     // find the actual time for an ordered edition
4328     if ( psz_chapter == NULL )
4329     {
4330         if ( Edition() && Edition()->b_ordered )
4331         {
4332             /* 1st, we need to know in which chapter we are */
4333             psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
4334         }
4335     }
4336
4337     if ( psz_chapter != NULL )
4338     {
4339         psz_current_chapter = psz_chapter;
4340         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
4341         if ( psz_chapter->i_seekpoint_num > 0 )
4342         {
4343             demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
4344             demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
4345             demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
4346         }
4347     }
4348
4349     // find the best matching segment
4350     for ( i=0; i<linked_segments.size(); i++ )
4351     {
4352         if ( i_date < linked_segments[i]->i_start_time )
4353             break;
4354     }
4355
4356     if ( i > 0 )
4357         i--;
4358
4359     if ( i_current_segment != i  )
4360     {
4361         linked_segments[i_current_segment]->UnSelect();
4362         linked_segments[i]->Select( i_date );
4363         i_current_segment = i;
4364     }
4365
4366     linked_segments[i]->Seek( i_date, i_time_offset );
4367 }
4368
4369 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
4370 {
4371     size_t i;
4372
4373     uint32 codec_time = uint32(-1);
4374     for( i = 0; i < command.ListSize(); i++ )
4375     {
4376         const EbmlElement *k = command[i];
4377
4378         if( MKV_IS_ID( k, KaxChapterProcessTime ) )
4379         {
4380             codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
4381             break;
4382         }
4383     }
4384
4385     for( i = 0; i < command.ListSize(); i++ )
4386     {
4387         const EbmlElement *k = command[i];
4388
4389         if( MKV_IS_ID( k, KaxChapterProcessData ) )
4390         {
4391             KaxChapterProcessData *p_data =  new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4392             switch ( codec_time )
4393             {
4394             case 0:
4395                 during_cmds.push_back( *p_data );
4396                 break;
4397             case 1:
4398                 enter_cmds.push_back( *p_data );
4399                 break;
4400             case 2:
4401                 leave_cmds.push_back( *p_data );
4402                 break;
4403             default:
4404                 delete p_data;
4405             }
4406         }
4407     }
4408 }
4409
4410 bool chapter_item_c::Enter( bool b_do_subs )
4411 {
4412     bool f_result = false;
4413     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4414     while ( index != codecs.end() )
4415     {
4416         f_result |= (*index)->Enter();
4417         index++;
4418     }
4419
4420     if ( b_do_subs )
4421     {
4422         // sub chapters
4423         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4424         while ( index_ != sub_chapters.end() )
4425         {
4426             f_result |= (*index_)->Enter( true );
4427             index_++;
4428         }
4429     }
4430     return f_result;
4431 }
4432
4433 bool chapter_item_c::Leave( bool b_do_subs )
4434 {
4435     bool f_result = false;
4436     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4437     while ( index != codecs.end() )
4438     {
4439         f_result |= (*index)->Leave();
4440         index++;
4441     }
4442
4443     if ( b_do_subs )
4444     {
4445         // sub chapters
4446         std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4447         while ( index_ != sub_chapters.end() )
4448         {
4449             f_result |= (*index_)->Leave( true );
4450             index_++;
4451         }
4452     }
4453     return f_result;
4454 }
4455
4456 bool chapter_item_c::EnterAndLeave( chapter_item_c *p_item )
4457 {
4458     chapter_item_c *p_common_parent = p_item;
4459
4460     // leave, up to a common parent
4461     while ( p_common_parent != NULL && !p_common_parent->ParentOf( *this ) )
4462     {
4463         if ( p_common_parent->Leave( false ) )
4464             return true;
4465         p_common_parent = p_common_parent->psz_parent;
4466     }
4467
4468     // enter from the parent to <this>
4469     if ( p_common_parent != NULL )
4470     {
4471         do
4472         {
4473             for ( size_t i = 0; i<p_common_parent->sub_chapters.size(); i++ )
4474             {
4475                 if ( p_common_parent->sub_chapters[i]->ParentOf( *this ) )
4476                 {
4477                     p_common_parent = p_common_parent->sub_chapters[i];
4478                     break;
4479                 }
4480             }
4481
4482             if ( p_common_parent == this )
4483                 break;
4484
4485             if ( p_common_parent->Enter( false ) )
4486                 return true;
4487         } while ( 1 );
4488     }
4489
4490     return Enter( true );
4491 }
4492
4493 bool dvd_chapter_codec_c::Enter()
4494 {
4495     bool f_result = false;
4496     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4497     while ( index != enter_cmds.end() )
4498     {
4499         if ( (*index).GetSize() )
4500         {
4501             binary *p_data = (*index).GetBuffer();
4502             size_t i_size = *p_data++;
4503             // avoid reading too much from the buffer
4504             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4505             for ( ; i_size > 0; i_size--, p_data += 8 )
4506             {
4507                 f_result |= interpretor.Interpret( p_data );
4508             }
4509         }
4510         index++;
4511     }
4512     return f_result;
4513 }
4514
4515 bool dvd_chapter_codec_c::Leave()
4516 {
4517     bool f_result = false;
4518     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4519     while ( index != leave_cmds.end() )
4520     {
4521         if ( (*index).GetSize() )
4522         {
4523             binary *p_data = (*index).GetBuffer();
4524             size_t i_size = *p_data++;
4525             // avoid reading too much from the buffer
4526             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4527             for ( ; i_size > 0; i_size--, p_data += 8 )
4528             {
4529                 f_result |= interpretor.Interpret( p_data );
4530             }
4531         }
4532         index++;
4533     }
4534     return f_result;
4535 }
4536
4537 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
4538 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4539 {
4540     if ( i_size != 8 )
4541         return false;
4542
4543     virtual_segment_c *p_segment;
4544     chapter_item_c *p_chapter;
4545     bool f_result = false;
4546     uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4547
4548     switch ( i_command )
4549     {
4550     case CMD_JUMP_TT:
4551         {
4552             uint8 i_title = p_command[5];
4553             msg_Dbg( &sys.demuxer, "DVD command: JumpTT %d", i_title );
4554
4555             // find in the ChapProcessPrivate matching this Title level
4556             p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
4557             if ( p_chapter != NULL )
4558             {
4559                 // if the segment is not part of the current segment, select the new one
4560                 if ( p_segment != sys.p_current_segment )
4561                 {
4562                     sys.PreparePlayback( p_segment );
4563                 }
4564     
4565                 // jump to the location in the found segment
4566                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, NULL );
4567                 p_chapter->Enter( true );
4568                 
4569                 f_result = true;
4570             }
4571
4572             break;
4573         }
4574     case CMD_CALLSS_VTSM:
4575         {
4576             msg_Dbg( &sys.demuxer, "DVD command: CallSS VTSM" );
4577             switch( (p_command[6] & 0xC0) >> 6 ) {
4578                 case 0:
4579                     switch ( p_command[5] )
4580                     {
4581                     case 0x00:
4582                         msg_Dbg( &sys.demuxer, "CallSS PGC (rsm_cell %x)", p_command[5]);
4583                         break;
4584                     case 0x82:
4585                         msg_Dbg( &sys.demuxer, "CallSS Title Entry (rsm_cell %x)", p_command[5]);
4586                         break;
4587                     case 0x83:
4588                         msg_Dbg( &sys.demuxer, "CallSS Root Menu (rsm_cell %x)", p_command[5]);
4589                         break;
4590                     case 0x84:
4591                         msg_Dbg( &sys.demuxer, "CallSS Subpicture Menu (rsm_cell %x)", p_command[5]);
4592                         break;
4593                     case 0x85:
4594                         msg_Dbg( &sys.demuxer, "CallSS Audio Menu (rsm_cell %x)", p_command[5]);
4595                         break;
4596                     case 0x86:
4597                         msg_Dbg( &sys.demuxer, "CallSS Angle Menu (rsm_cell %x)", p_command[5]);
4598                         break;
4599                     case 0x87:
4600                         msg_Dbg( &sys.demuxer, "CallSS Chapter Menu (rsm_cell %x)", p_command[5]);
4601                         break;
4602                     default:
4603                         msg_Dbg( &sys.demuxer, "CallSS <unknown> (rsm_cell %x)", p_command[5]);
4604                         break;
4605                     }
4606                     p_chapter = sys.BrowseCodecPrivate( 1, MatchPgcType, &p_command[5], 1, p_segment );
4607                     if ( p_chapter != NULL )
4608                     {
4609                         // if the segment is not part of the current segment, select the new one
4610                         if ( p_segment != sys.p_current_segment )
4611                         {
4612                             sys.PreparePlayback( p_segment );
4613                         }
4614             
4615                         p_chapter->Enter( true );
4616                         
4617                         // jump to the location in the found segment
4618                         p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
4619                         f_result = true;
4620                     }
4621                 break;
4622                 case 1:
4623                     msg_Dbg( &sys.demuxer, "CallSS VMGM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4624                 break;
4625                 case 2:
4626                     msg_Dbg( &sys.demuxer, "CallSS VTSM (menu %d, rsm_cell %x)", p_command[6] & 0x0F, p_command[5]);
4627                 break;
4628                 case 3:
4629                     msg_Dbg( &sys.demuxer, "CallSS VMGM (pgc %d, rsm_cell %x)", (p_command[3] << 8) + p_command[4], p_command[5]);
4630                 break;
4631             }
4632             break;
4633         }
4634     default:
4635         {
4636             msg_Dbg( &sys.demuxer, "DVD command: unsupported %02X %02X %02X %02X %02X %02X %02X %02X"
4637                      ,p_command[0]
4638                      ,p_command[1]
4639                      ,p_command[2]
4640                      ,p_command[3]
4641                      ,p_command[4]
4642                      ,p_command[5]
4643                      ,p_command[6]
4644                      ,p_command[7]);
4645             break;
4646         }
4647     }
4648
4649     return f_result;
4650 }
4651
4652 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4653 {
4654     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
4655         return false;
4656     
4657     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_TT )
4658         return false;
4659
4660     uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
4661     uint8 i_title = *(uint8*)p_cookie;
4662
4663     return (i_gtitle == i_title);
4664 }
4665
4666 bool dvd_command_interpretor_c::MatchPgcType( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4667 {
4668     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 7 )
4669         return false;
4670     
4671     if ( data.m_private_data.GetBuffer()[0] != MATROSKA_DVD_LEVEL_PGC )
4672         return false;
4673
4674     uint8 i_pgc_type = data.m_private_data.GetBuffer()[3];
4675     uint8 i_pgc = *(uint8*)p_cookie;
4676
4677     return (i_pgc_type == i_pgc);
4678 }
4679
4680 bool matroska_script_codec_c::Enter()
4681 {
4682     bool f_result = false;
4683     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4684     while ( index != enter_cmds.end() )
4685     {
4686         if ( (*index).GetSize() )
4687         {
4688             f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4689         }
4690         index++;
4691     }
4692     return f_result;
4693 }
4694
4695 bool matroska_script_codec_c::Leave()
4696 {
4697     bool f_result = false;
4698     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4699     while ( index != leave_cmds.end() )
4700     {
4701         if ( (*index).GetSize() )
4702         {
4703             f_result |= interpretor.Interpret( (*index).GetBuffer(), (*index).GetSize() );
4704         }
4705         index++;
4706     }
4707     return f_result;
4708 }
4709
4710 // see http://www.matroska.org/technical/specs/chapters/index.html#mscript 
4711 //  for a description of existing commands
4712 bool matroska_script_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4713 {
4714     bool b_result = false;
4715
4716     char *psz_str = (char*) malloc( i_size + 1 );
4717     memcpy( psz_str, p_command, i_size );
4718     psz_str[ i_size ] = '\0';
4719
4720     std::string sz_command = psz_str;
4721
4722     msg_Dbg( &sys.demuxer, "Matroska Script command : %s", sz_command.c_str() );
4723
4724     if ( sz_command.compare( 0, CMD_MS_GOTO_AND_PLAY.size(), CMD_MS_GOTO_AND_PLAY ) == 0 )
4725     {
4726         size_t i,j;
4727
4728         // find the (
4729         for ( i=CMD_MS_GOTO_AND_PLAY.size(); i<sz_command.size(); i++)
4730         {
4731             if ( sz_command[i] == '(' )
4732             {
4733                 i++;
4734                 break;
4735             }
4736         }
4737         // find the )
4738         for ( j=i; j<sz_command.size(); j++)
4739         {
4740             if ( sz_command[j] == ')' )
4741             {
4742                 i--;
4743                 break;
4744             }
4745         }
4746
4747         std::string st = sz_command.substr( i+1, j-i-1 );
4748         int64_t i_chapter_uid = atoi( st.c_str() );
4749
4750         virtual_segment_c *p_segment;
4751         chapter_item_c *p_chapter = sys.FindChapter( i_chapter_uid, p_segment );
4752
4753         if ( p_chapter == NULL )
4754             msg_Dbg( &sys.demuxer, "Chapter %d not found", i_chapter_uid);
4755         else
4756         {
4757             p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
4758             b_result = true;
4759         }
4760     }
4761
4762     return b_result;
4763 }