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