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