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