]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
mkv.cpp: clean the way chapters are presented/handled internally
[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     ,b_display_seekpoint(true)
472     ,b_user_display(false)
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_user_chapters, 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     int64_t                     i_uid;
508     bool                        b_display_seekpoint;
509     bool                        b_user_display;
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             return VLC_EGENERIC;
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_user_chapters, int i_level )
1828 {
1829     // add support for meta-elements from codec like DVD Titles
1830     if ( !b_display_seekpoint || psz_name == "" )
1831     {
1832         psz_name = GetCodecName();
1833         if ( psz_name != "" )
1834             b_display_seekpoint = true;
1835     }
1836
1837     if (b_display_seekpoint)
1838     {
1839         seekpoint_t *sk = vlc_seekpoint_New();
1840
1841         sk->i_level = i_level;
1842         sk->i_time_offset = i_start_time;
1843         sk->psz_name = strdup( psz_name.c_str() );
1844
1845         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
1846         title.i_seekpoint++;
1847         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
1848         title.seekpoint[title.i_seekpoint-1] = sk;
1849
1850         if ( b_user_display )
1851             i_user_chapters++;
1852     }
1853
1854     for ( size_t i=0; i<sub_chapters.size() ; i++)
1855     {
1856         sub_chapters[i]->PublishChapters( title, i_user_chapters, i_level+1 );
1857     }
1858
1859     i_seekpoint_num = i_user_chapters;
1860
1861     return i_user_chapters;
1862 }
1863
1864 void virtual_segment_c::UpdateCurrentToChapter( demux_t & demux )
1865 {
1866     demux_sys_t & sys = *demux.p_sys;
1867     chapter_item_c *psz_curr_chapter;
1868
1869     /* update current chapter/seekpoint */
1870     if ( p_editions->size() )
1871     {
1872         /* 1st, we need to know in which chapter we are */
1873         psz_curr_chapter = (*p_editions)[i_current_edition]->FindTimecode( sys.i_pts );
1874
1875         /* we have moved to a new chapter */
1876         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1877         {
1878             if ( psz_current_chapter != NULL )
1879                 psz_current_chapter->Leave();
1880
1881             if ( (*p_editions)[i_current_edition]->b_ordered )
1882             {
1883                 if ( !psz_curr_chapter->Enter() )
1884                 {
1885                     // only seek if necessary
1886                     if ( psz_current_chapter == NULL || (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time) )
1887                         Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1888                 }
1889             }
1890             else if ( psz_curr_chapter->i_seekpoint_num > 0 )
1891             {
1892                 demux.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
1893                 demux.info.i_title = sys.i_current_title = i_sys_title;
1894                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1895             }
1896
1897             psz_current_chapter = psz_curr_chapter;
1898         }
1899     }
1900 }
1901
1902 chapter_item_c *virtual_segment_c::BrowseCodecPrivate( unsigned int codec_id, 
1903                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
1904                                     const void *p_cookie, 
1905                                     size_t i_cookie_size )
1906 {
1907     // FIXME don't assume it is the first edition
1908     std::vector<chapter_edition_c*>::iterator index = p_editions->begin();
1909     if ( index != p_editions->end() )
1910     {
1911         chapter_item_c *p_result = (*index)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
1912         if ( p_result != NULL )
1913             return p_result;
1914     }
1915     return NULL;
1916 }
1917
1918 chapter_item_c *chapter_item_c::BrowseCodecPrivate( unsigned int codec_id, 
1919                                     bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
1920                                     const void *p_cookie, 
1921                                     size_t i_cookie_size )
1922 {
1923     // this chapter
1924     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
1925     while ( index != codecs.end() )
1926     {
1927         if ( match( **index ,p_cookie, i_cookie_size ) )
1928             return this;
1929         index++;
1930     }
1931     
1932     // sub-chapters
1933     chapter_item_c *p_result = NULL;
1934     std::vector<chapter_item_c*>::const_iterator index2 = sub_chapters.begin();
1935     while ( index2 != sub_chapters.end() )
1936     {
1937         p_result = (*index2)->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
1938         if ( p_result != NULL )
1939             return p_result;
1940         index2++;
1941     }
1942     
1943     return p_result;
1944 }
1945
1946 void chapter_item_c::Append( const chapter_item_c & chapter )
1947 {
1948     // we are appending content for the same chapter UID
1949     size_t i;
1950     chapter_item_c *p_chapter;
1951
1952     for ( i=0; i<chapter.sub_chapters.size(); i++ )
1953     {
1954         p_chapter = FindChapter( *chapter.sub_chapters[i] );
1955         if ( p_chapter != NULL )
1956         {
1957             p_chapter->Append( *chapter.sub_chapters[i] );
1958         }
1959         else
1960         {
1961             sub_chapters.push_back( chapter.sub_chapters[i] );
1962         }
1963     }
1964
1965     i_user_start_time = min( i_user_start_time, chapter.i_user_start_time );
1966     i_user_end_time = max( i_user_end_time, chapter.i_user_end_time );
1967 }
1968
1969 chapter_item_c * chapter_item_c::FindChapter( const chapter_item_c & chapter )
1970 {
1971     size_t i;
1972     for ( i=0; i<sub_chapters.size(); i++)
1973     {
1974         if ( sub_chapters[i]->i_uid == chapter.i_uid )
1975             return sub_chapters[i];
1976     }
1977     return NULL;
1978 }
1979
1980 std::string chapter_item_c::GetCodecName( bool f_for_title ) const
1981 {
1982     std::string result;
1983
1984     std::vector<chapter_codec_cmds_c*>::const_iterator index = codecs.begin();
1985     while ( index != codecs.end() )
1986     {
1987         result = (*index)->GetCodecName( f_for_title );
1988         if ( result != "" )
1989             break;
1990         index++;
1991     }
1992
1993     return result;
1994 }
1995
1996 std::string dvd_chapter_codec_c::GetCodecName( bool f_for_title ) const
1997 {
1998     std::string result;
1999     if ( m_private_data.GetSize() >= 3)
2000     {
2001         const binary* p_data = m_private_data.GetBuffer();
2002 /*        if ( p_data[0] == 0x28 )
2003         {
2004             uint16_t i_title = (p_data[1] << 8) + p_data[2];
2005             char psz_str[11];
2006             sprintf( psz_str, " %d  ---", i_title );
2007             result = N_("---  DVD Title");
2008             result += psz_str;
2009         }
2010         else */ if ( p_data[0] == 0x2A )
2011         {
2012             char psz_str[11];
2013             sprintf( psz_str, " (%c%c)  ---", p_data[1], p_data[2] );
2014             result = N_("---  DVD Menu");
2015             result += psz_str;
2016         }
2017         else if ( p_data[0] == 0x30 && f_for_title )
2018         {
2019             if ( p_data[1] == 0x00 )
2020                 result = N_("First Played");
2021             else if ( p_data[1] == 0xC0 )
2022                 result = N_("Video Manager");
2023             else if ( p_data[1] == 0x80 )
2024             {
2025                 uint16_t i_title = (p_data[2] << 8) + p_data[3];
2026                 char psz_str[20];
2027                 sprintf( psz_str, " %d -----", i_title );
2028                 result = N_("----- Title");
2029                 result += psz_str;
2030             }
2031         }
2032     }
2033
2034     return result;
2035 }
2036
2037 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, chapter_item_c *psz_chapter )
2038 {
2039     demux_sys_t        *p_sys = p_demux->p_sys;
2040     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2041     matroska_segment_c *p_segment = p_vsegment->Segment();
2042     mtime_t            i_time_offset = 0;
2043
2044     int         i_index;
2045
2046     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
2047     if( i_date < 0 && f_percent < 0 )
2048     {
2049         msg_Warn( p_demux, "cannot seek nowhere !" );
2050         return;
2051     }
2052     if( f_percent > 1.0 )
2053     {
2054         msg_Warn( p_demux, "cannot seek so far !" );
2055         return;
2056     }
2057
2058     /* seek without index or without date */
2059     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
2060     {
2061         if (p_sys->f_duration >= 0)
2062         {
2063             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
2064         }
2065         else
2066         {
2067             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
2068
2069             msg_Dbg( p_demux, "inacurate way of seeking" );
2070             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
2071             {
2072                 if( p_segment->index[i_index].i_position >= i_pos)
2073                 {
2074                     break;
2075                 }
2076             }
2077             if( i_index == p_segment->i_index )
2078             {
2079                 i_index--;
2080             }
2081
2082             i_date = p_segment->index[i_index].i_time;
2083
2084 #if 0
2085             if( p_segment->index[i_index].i_position < i_pos )
2086             {
2087                 EbmlElement *el;
2088
2089                 msg_Warn( p_demux, "searching for cluster, could take some time" );
2090
2091                 /* search a cluster */
2092                 while( ( el = p_sys->ep->Get() ) != NULL )
2093                 {
2094                     if( MKV_IS_ID( el, KaxCluster ) )
2095                     {
2096                         KaxCluster *cluster = (KaxCluster*)el;
2097
2098                         /* add it to the index */
2099                         p_segment->IndexAppendCluster( cluster );
2100
2101                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
2102                         {
2103                             p_sys->cluster = cluster;
2104                             p_sys->ep->Down();
2105                             break;
2106                         }
2107                     }
2108                 }
2109             }
2110 #endif
2111         }
2112     }
2113
2114     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
2115 }
2116
2117 /*****************************************************************************
2118  * Demux: reads and demuxes data packets
2119  *****************************************************************************
2120  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
2121  *****************************************************************************/
2122 static int Demux( demux_t *p_demux)
2123 {
2124     demux_sys_t        *p_sys = p_demux->p_sys;
2125     virtual_segment_c  *p_vsegment = p_sys->p_current_segment;
2126     matroska_segment_c *p_segmet = p_vsegment->Segment();
2127     if ( p_segmet == NULL ) return 0;
2128     int                i_block_count = 0;
2129
2130     KaxBlock *block;
2131     int64_t i_block_duration;
2132     int64_t i_block_ref1;
2133     int64_t i_block_ref2;
2134
2135     for( ;; )
2136     {
2137         if ( p_sys->demuxer.b_die )
2138             return 0;
2139
2140         if( p_sys->i_pts >= p_sys->i_start_pts  )
2141             p_vsegment->UpdateCurrentToChapter( *p_demux );
2142         
2143         if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered && p_vsegment->CurrentChapter() == NULL )
2144         {
2145             /* nothing left to read in this ordered edition */
2146             if ( !p_vsegment->SelectNext() )
2147                 return 0;
2148             p_segmet->UnSelect( );
2149             
2150             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2151
2152             /* switch to the next segment */
2153             p_segmet = p_vsegment->Segment();
2154             if ( !p_segmet->Select( 0 ) )
2155             {
2156                 msg_Err( p_demux, "Failed to select new segment" );
2157                 return 0;
2158             }
2159             continue;
2160         }
2161
2162
2163         if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
2164         {
2165             if ( p_vsegment->Edition() && p_vsegment->Edition()->b_ordered )
2166             {
2167                 const chapter_item_c *p_chap = p_vsegment->CurrentChapter();
2168                 // check if there are more chapters to read
2169                 if ( p_chap != NULL )
2170                 {
2171                     /* TODO handle successive chapters with the same user_start_time/user_end_time
2172                     if ( p_chap->i_user_start_time == p_chap->i_user_start_time )
2173                         p_vsegment->SelectNext();
2174                     */
2175                     p_sys->i_pts = p_chap->i_user_end_time;
2176                     p_sys->i_pts++; // trick to avoid staying on segments with no duration and no content
2177
2178                     return 1;
2179                 }
2180
2181                 return 0;
2182             }
2183             msg_Warn( p_demux, "cannot get block EOF?" );
2184             p_segmet->UnSelect( );
2185             
2186             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
2187
2188             /* switch to the next segment */
2189             if ( !p_vsegment->SelectNext() )
2190                 // no more segments in this stream
2191                 return 0;
2192             p_segmet = p_vsegment->Segment();
2193             if ( !p_segmet->Select( 0 ) )
2194             {
2195                 msg_Err( p_demux, "Failed to select new segment" );
2196                 return 0;
2197             }
2198
2199             continue;
2200         }
2201
2202         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
2203
2204         if( p_sys->i_pts >= p_sys->i_start_pts  )
2205         {
2206             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
2207         }
2208
2209         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
2210
2211         delete block;
2212         i_block_count++;
2213
2214         // TODO optimize when there is need to leave or when seeking has been called
2215         if( i_block_count > 5 )
2216         {
2217             return 1;
2218         }
2219     }
2220 }
2221
2222
2223
2224 /*****************************************************************************
2225  * Stream managment
2226  *****************************************************************************/
2227 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
2228 {
2229     s = s_;
2230     mb_eof = VLC_FALSE;
2231 }
2232
2233 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
2234 {
2235     if( i_size <= 0 || mb_eof )
2236     {
2237         return 0;
2238     }
2239
2240     return stream_Read( s, p_buffer, i_size );
2241 }
2242 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
2243 {
2244     int64_t i_pos;
2245
2246     switch( mode )
2247     {
2248         case seek_beginning:
2249             i_pos = i_offset;
2250             break;
2251         case seek_end:
2252             i_pos = stream_Size( s ) - i_offset;
2253             break;
2254         default:
2255             i_pos= stream_Tell( s ) + i_offset;
2256             break;
2257     }
2258
2259     if( i_pos < 0 || i_pos >= stream_Size( s ) )
2260     {
2261         mb_eof = VLC_TRUE;
2262         return;
2263     }
2264
2265     mb_eof = VLC_FALSE;
2266     if( stream_Seek( s, i_pos ) )
2267     {
2268         mb_eof = VLC_TRUE;
2269     }
2270     return;
2271 }
2272 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
2273 {
2274     return 0;
2275 }
2276 uint64 vlc_stream_io_callback::getFilePointer( void )
2277 {
2278     return stream_Tell( s );
2279 }
2280 void vlc_stream_io_callback::close( void )
2281 {
2282     return;
2283 }
2284
2285
2286 /*****************************************************************************
2287  * Ebml Stream parser
2288  *****************************************************************************/
2289 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start, demux_t *p_demux )
2290 {
2291     int i;
2292
2293     m_es = es;
2294     m_got = NULL;
2295     m_el[0] = el_start;
2296     mi_remain_size[0] = el_start->GetSize();
2297
2298     for( i = 1; i < 6; i++ )
2299     {
2300         m_el[i] = NULL;
2301     }
2302     mi_level = 1;
2303     mi_user_level = 1;
2304     mb_keep = VLC_FALSE;
2305     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2306 }
2307
2308 EbmlParser::~EbmlParser( void )
2309 {
2310     int i;
2311
2312     for( i = 1; i < mi_level; i++ )
2313     {
2314         if( !mb_keep )
2315         {
2316             delete m_el[i];
2317         }
2318         mb_keep = VLC_FALSE;
2319     }
2320 }
2321
2322 void EbmlParser::Up( void )
2323 {
2324     if( mi_user_level == mi_level )
2325     {
2326         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
2327     }
2328
2329     mi_user_level--;
2330 }
2331
2332 void EbmlParser::Down( void )
2333 {
2334     mi_user_level++;
2335     mi_level++;
2336 }
2337
2338 void EbmlParser::Keep( void )
2339 {
2340     mb_keep = VLC_TRUE;
2341 }
2342
2343 int EbmlParser::GetLevel( void )
2344 {
2345     return mi_user_level;
2346 }
2347
2348 void EbmlParser::Reset( demux_t *p_demux )
2349 {
2350     while ( mi_level > 0)
2351     {
2352         delete m_el[mi_level];
2353         m_el[mi_level] = NULL;
2354         mi_level--;
2355     }
2356     mi_user_level = mi_level = 1;
2357 #if LIBEBML_VERSION >= 0x000704
2358     // a little faster and cleaner
2359     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
2360 #else
2361     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
2362 #endif
2363     mb_dummy = config_GetInt( p_demux, "mkv-use-dummy" );
2364 }
2365
2366 EbmlElement *EbmlParser::Get( void )
2367 {
2368     int i_ulev = 0;
2369
2370     if( mi_user_level != mi_level )
2371     {
2372         return NULL;
2373     }
2374     if( m_got )
2375     {
2376         EbmlElement *ret = m_got;
2377         m_got = NULL;
2378
2379         return ret;
2380     }
2381
2382     if( m_el[mi_level] )
2383     {
2384         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
2385         if( !mb_keep )
2386         {
2387             delete m_el[mi_level];
2388         }
2389         mb_keep = VLC_FALSE;
2390     }
2391
2392     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, mb_dummy, 1 );
2393 //    mi_remain_size[mi_level] = m_el[mi_level]->GetSize();
2394     if( i_ulev > 0 )
2395     {
2396         while( i_ulev > 0 )
2397         {
2398             if( mi_level == 1 )
2399             {
2400                 mi_level = 0;
2401                 return NULL;
2402             }
2403
2404             delete m_el[mi_level - 1];
2405             m_got = m_el[mi_level -1] = m_el[mi_level];
2406             m_el[mi_level] = NULL;
2407
2408             mi_level--;
2409             i_ulev--;
2410         }
2411         return NULL;
2412     }
2413     else if( m_el[mi_level] == NULL )
2414     {
2415         fprintf( stderr," m_el[mi_level] == NULL\n" );
2416     }
2417
2418     return m_el[mi_level];
2419 }
2420
2421
2422 /*****************************************************************************
2423  * Tools
2424  *  * LoadCues : load the cues element and update index
2425  *
2426  *  * LoadTags : load ... the tags element
2427  *
2428  *  * InformationCreate : create all information, load tags if present
2429  *
2430  *****************************************************************************/
2431 void matroska_segment_c::LoadCues( )
2432 {
2433     int64_t     i_sav_position = es.I_O().getFilePointer();
2434     EbmlParser  *ep;
2435     EbmlElement *el, *cues;
2436
2437     /* *** Load the cue if found *** */
2438     if( i_cues_position < 0 )
2439     {
2440         msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2441
2442 //        IndexAppendCluster( cluster );
2443     }
2444
2445     vlc_bool_t b_seekable;
2446
2447     stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2448     if( !b_seekable )
2449         return;
2450
2451     msg_Dbg( &sys.demuxer, "loading cues" );
2452     es.I_O().setFilePointer( i_cues_position, seek_beginning );
2453     cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2454
2455     if( cues == NULL )
2456     {
2457         msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2458         es.I_O().setFilePointer( i_sav_position, seek_beginning );
2459         return;
2460     }
2461
2462     ep = new EbmlParser( &es, cues, &sys.demuxer );
2463     while( ( el = ep->Get() ) != NULL )
2464     {
2465         if( MKV_IS_ID( el, KaxCuePoint ) )
2466         {
2467 #define idx index[i_index]
2468
2469             idx.i_track       = -1;
2470             idx.i_block_number= -1;
2471             idx.i_position    = -1;
2472             idx.i_time        = 0;
2473             idx.b_key         = VLC_TRUE;
2474
2475             ep->Down();
2476             while( ( el = ep->Get() ) != NULL )
2477             {
2478                 if( MKV_IS_ID( el, KaxCueTime ) )
2479                 {
2480                     KaxCueTime &ctime = *(KaxCueTime*)el;
2481
2482                     ctime.ReadData( es.I_O() );
2483
2484                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2485                 }
2486                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2487                 {
2488                     ep->Down();
2489                     while( ( el = ep->Get() ) != NULL )
2490                     {
2491                         if( MKV_IS_ID( el, KaxCueTrack ) )
2492                         {
2493                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2494
2495                             ctrack.ReadData( es.I_O() );
2496                             idx.i_track = uint16( ctrack );
2497                         }
2498                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2499                         {
2500                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2501
2502                             ccpos.ReadData( es.I_O() );
2503                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2504                         }
2505                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2506                         {
2507                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2508
2509                             cbnum.ReadData( es.I_O() );
2510                             idx.i_block_number = uint32( cbnum );
2511                         }
2512                         else
2513                         {
2514                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
2515                         }
2516                     }
2517                     ep->Up();
2518                 }
2519                 else
2520                 {
2521                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
2522                 }
2523             }
2524             ep->Up();
2525
2526 #if 0
2527             msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2528                      " track=%d bnum=%d", idx.i_time, idx.i_position,
2529                      idx.i_track, idx.i_block_number );
2530 #endif
2531
2532             i_index++;
2533             if( i_index >= i_index_max )
2534             {
2535                 i_index_max += 1024;
2536                 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2537             }
2538 #undef idx
2539         }
2540         else
2541         {
2542             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2543         }
2544     }
2545     delete ep;
2546     delete cues;
2547
2548     b_cues = VLC_TRUE;
2549
2550     msg_Dbg( &sys.demuxer, "loading cues done." );
2551     es.I_O().setFilePointer( i_sav_position, seek_beginning );
2552 }
2553
2554 void matroska_segment_c::LoadTags( )
2555 {
2556     int64_t     i_sav_position = es.I_O().getFilePointer();
2557     EbmlParser  *ep;
2558     EbmlElement *el, *tags;
2559
2560     msg_Dbg( &sys.demuxer, "loading tags" );
2561     es.I_O().setFilePointer( i_tags_position, seek_beginning );
2562     tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2563
2564     if( tags == NULL )
2565     {
2566         msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2567         es.I_O().setFilePointer( i_sav_position, seek_beginning );
2568         return;
2569     }
2570
2571     msg_Dbg( &sys.demuxer, "Tags" );
2572     ep = new EbmlParser( &es, tags, &sys.demuxer );
2573     while( ( el = ep->Get() ) != NULL )
2574     {
2575         if( MKV_IS_ID( el, KaxTag ) )
2576         {
2577             msg_Dbg( &sys.demuxer, "+ Tag" );
2578             ep->Down();
2579             while( ( el = ep->Get() ) != NULL )
2580             {
2581                 if( MKV_IS_ID( el, KaxTagTargets ) )
2582                 {
2583                     msg_Dbg( &sys.demuxer, "|   + Targets" );
2584                     ep->Down();
2585                     while( ( el = ep->Get() ) != NULL )
2586                     {
2587                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2588                     }
2589                     ep->Up();
2590                 }
2591                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2592                 {
2593                     msg_Dbg( &sys.demuxer, "|   + General" );
2594                     ep->Down();
2595                     while( ( el = ep->Get() ) != NULL )
2596                     {
2597                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2598                     }
2599                     ep->Up();
2600                 }
2601                 else if( MKV_IS_ID( el, KaxTagGenres ) )
2602                 {
2603                     msg_Dbg( &sys.demuxer, "|   + Genres" );
2604                     ep->Down();
2605                     while( ( el = ep->Get() ) != NULL )
2606                     {
2607                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2608                     }
2609                     ep->Up();
2610                 }
2611                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2612                 {
2613                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
2614                     ep->Down();
2615                     while( ( el = ep->Get() ) != NULL )
2616                     {
2617                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2618                     }
2619                     ep->Up();
2620                 }
2621                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2622                 {
2623                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
2624                     ep->Down();
2625                     while( ( el = ep->Get() ) != NULL )
2626                     {
2627                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2628                     }
2629                     ep->Up();
2630                 }
2631                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2632                 {
2633                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
2634                 }
2635                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2636                 {
2637                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
2638                 }
2639                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2640                 {
2641                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
2642                 }
2643                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2644                 {
2645                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
2646                 }
2647                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2648                 {
2649                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
2650                 }
2651                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2652                 {
2653                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
2654                 }
2655                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2656                 {
2657                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
2658                 }
2659                 else
2660                 {
2661                     msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid( *el ).name() );
2662                 }
2663             }
2664             ep->Up();
2665         }
2666         else
2667         {
2668             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2669         }
2670     }
2671     delete ep;
2672     delete tags;
2673
2674     msg_Dbg( &sys.demuxer, "loading tags done." );
2675     es.I_O().setFilePointer( i_sav_position, seek_beginning );
2676 }
2677
2678 /*****************************************************************************
2679  * ParseSeekHead:
2680  *****************************************************************************/
2681 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
2682 {
2683     EbmlElement *el;
2684     size_t i, j;
2685     int i_upper_level = 0;
2686
2687     msg_Dbg( &sys.demuxer, "|   + Seek head" );
2688
2689     /* Master elements */
2690     seekhead->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2691
2692     for( i = 0; i < seekhead->ListSize(); i++ )
2693     {
2694         EbmlElement *l = (*seekhead)[i];
2695
2696         if( MKV_IS_ID( l, KaxSeek ) )
2697         {
2698             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2699             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2700             int64_t i_pos = -1;
2701
2702             for( j = 0; j < sk->ListSize(); j++ )
2703             {
2704                 EbmlElement *l = (*sk)[j];
2705
2706                 if( MKV_IS_ID( l, KaxSeekID ) )
2707                 {
2708                     KaxSeekID &sid = *(KaxSeekID*)l;
2709                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2710                 }
2711                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2712                 {
2713                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2714                     i_pos = uint64( spos );
2715                 }
2716                 else
2717                 {
2718                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2719                 }
2720             }
2721
2722             if( i_pos >= 0 )
2723             {
2724                 if( id == KaxCues::ClassInfos.GlobalId )
2725                 {
2726                     msg_Dbg( &sys.demuxer, "|   |   |   = cues at "I64Fd, i_pos );
2727                     i_cues_position = segment->GetGlobalPosition( i_pos );
2728                 }
2729                 else if( id == KaxChapters::ClassInfos.GlobalId )
2730                 {
2731                     msg_Dbg( &sys.demuxer, "|   |   |   = chapters at "I64Fd, i_pos );
2732                     i_chapters_position = segment->GetGlobalPosition( i_pos );
2733                 }
2734                 else if( id == KaxTags::ClassInfos.GlobalId )
2735                 {
2736                     msg_Dbg( &sys.demuxer, "|   |   |   = tags at "I64Fd, i_pos );
2737                     i_tags_position = segment->GetGlobalPosition( i_pos );
2738                 }
2739             }
2740         }
2741         else
2742         {
2743             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
2744         }
2745     }
2746 }
2747
2748 /*****************************************************************************
2749  * ParseTrackEntry:
2750  *****************************************************************************/
2751 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
2752 {
2753     size_t i, j, k, n;
2754
2755     mkv_track_t *tk;
2756
2757     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
2758
2759     tk = new mkv_track_t();
2760     tracks.push_back( tk );
2761
2762     /* Init the track */
2763     memset( tk, 0, sizeof( mkv_track_t ) );
2764
2765     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2766     tk->fmt.psz_language = strdup("English");
2767     tk->fmt.psz_description = NULL;
2768
2769     tk->b_default = VLC_TRUE;
2770     tk->b_enabled = VLC_TRUE;
2771     tk->b_silent = VLC_FALSE;
2772     tk->i_number = tracks.size() - 1;
2773     tk->i_extra_data = 0;
2774     tk->p_extra_data = NULL;
2775     tk->psz_codec = NULL;
2776     tk->i_default_duration = 0;
2777     tk->f_timecodescale = 1.0;
2778
2779     tk->b_inited = VLC_FALSE;
2780     tk->i_data_init = 0;
2781     tk->p_data_init = NULL;
2782
2783     tk->psz_codec_name = NULL;
2784     tk->psz_codec_settings = NULL;
2785     tk->psz_codec_info_url = NULL;
2786     tk->psz_codec_download_url = NULL;
2787     
2788     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2789
2790     for( i = 0; i < m->ListSize(); i++ )
2791     {
2792         EbmlElement *l = (*m)[i];
2793
2794         if( MKV_IS_ID( l, KaxTrackNumber ) )
2795         {
2796             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2797
2798             tk->i_number = uint32( tnum );
2799             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
2800         }
2801         else  if( MKV_IS_ID( l, KaxTrackUID ) )
2802         {
2803             KaxTrackUID &tuid = *(KaxTrackUID*)l;
2804
2805             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
2806         }
2807         else  if( MKV_IS_ID( l, KaxTrackType ) )
2808         {
2809             char *psz_type;
2810             KaxTrackType &ttype = *(KaxTrackType*)l;
2811
2812             switch( uint8(ttype) )
2813             {
2814                 case track_audio:
2815                     psz_type = "audio";
2816                     tk->fmt.i_cat = AUDIO_ES;
2817                     break;
2818                 case track_video:
2819                     psz_type = "video";
2820                     tk->fmt.i_cat = VIDEO_ES;
2821                     break;
2822                 case track_subtitle:
2823                     psz_type = "subtitle";
2824                     tk->fmt.i_cat = SPU_ES;
2825                     break;
2826                 default:
2827                     psz_type = "unknown";
2828                     tk->fmt.i_cat = UNKNOWN_ES;
2829                     break;
2830             }
2831
2832             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
2833         }
2834 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2835 //        {
2836 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2837
2838 //            tk->b_enabled = uint32( fenb );
2839 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
2840 //                     uint32( fenb )  );
2841 //        }
2842         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2843         {
2844             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2845
2846             tk->b_default = uint32( fdef );
2847             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
2848         }
2849         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2850         {
2851             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2852
2853             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
2854         }
2855         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
2856         {
2857             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2858
2859             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
2860         }
2861         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2862         {
2863             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2864
2865             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
2866         }
2867         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2868         {
2869             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2870
2871             tk->i_default_duration = uint64(defd);
2872             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
2873         }
2874         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2875         {
2876             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2877
2878             tk->f_timecodescale = float( ttcs );
2879             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
2880         }
2881         else if( MKV_IS_ID( l, KaxTrackName ) )
2882         {
2883             KaxTrackName &tname = *(KaxTrackName*)l;
2884
2885             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2886             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
2887         }
2888         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
2889         {
2890             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2891
2892             tk->fmt.psz_language = strdup( string( lang ).c_str() );
2893             msg_Dbg( &sys.demuxer,
2894                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
2895         }
2896         else  if( MKV_IS_ID( l, KaxCodecID ) )
2897         {
2898             KaxCodecID &codecid = *(KaxCodecID*)l;
2899
2900             tk->psz_codec = strdup( string( codecid ).c_str() );
2901             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2902         }
2903         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2904         {
2905             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2906
2907             tk->i_extra_data = cpriv.GetSize();
2908             if( tk->i_extra_data > 0 )
2909             {
2910                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2911                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2912             }
2913             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2914         }
2915         else if( MKV_IS_ID( l, KaxCodecName ) )
2916         {
2917             KaxCodecName &cname = *(KaxCodecName*)l;
2918
2919             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2920             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2921         }
2922         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2923         {
2924             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2925             MkvTree( sys.demuxer, 3, "Content Encodings" );
2926             for( j = 0; j < cencs->ListSize(); j++ )
2927             {
2928                 EbmlElement *l2 = (*cencs)[j];
2929                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2930                 {
2931                     MkvTree( sys.demuxer, 4, "Content Encoding" );
2932                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2933                     for( k = 0; k < cenc->ListSize(); k++ )
2934                     {
2935                         EbmlElement *l3 = (*cenc)[k];
2936                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2937                         {
2938                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2939                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2940                         }
2941                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2942                         {
2943                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2944                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2945                         }
2946                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2947                         {
2948                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2949                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2950                         }
2951                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
2952                         {
2953                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2954                             MkvTree( sys.demuxer, 5, "Content Compression" );
2955                             for( n = 0; n < compr->ListSize(); n++ )
2956                             {
2957                                 EbmlElement *l4 = (*compr)[n];
2958                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2959                                 {
2960                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2961                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2962                                     if( uint32( compalg ) == 0 )
2963                                     {
2964                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2965                                     }
2966                                 }
2967                                 else
2968                                 {
2969                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2970                                 }
2971                             }
2972                         }
2973
2974                         else
2975                         {
2976                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2977                         }
2978                     }
2979                     
2980                 }
2981                 else
2982                 {
2983                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2984                 }
2985             }
2986                 
2987         }
2988 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2989 //        {
2990 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2991
2992 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2993 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
2994 //        }
2995 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2996 //        {
2997 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2998
2999 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
3000 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
3001 //        }
3002 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
3003 //        {
3004 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
3005
3006 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
3007 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
3008 //        }
3009 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
3010 //        {
3011 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
3012
3013 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
3014 //        }
3015 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
3016 //        {
3017 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
3018
3019 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
3020 //        }
3021         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
3022         {
3023             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
3024             unsigned int j;
3025
3026             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
3027             tk->f_fps = 0.0;
3028
3029             for( j = 0; j < tkv->ListSize(); j++ )
3030             {
3031                 EbmlElement *l = (*tkv)[j];
3032 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
3033 //                {
3034 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
3035
3036 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
3037 //                }
3038 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
3039 //                {
3040 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
3041
3042 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
3043 //                }
3044 //                else
3045                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
3046                 {
3047                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
3048
3049                     tk->fmt.video.i_width = uint16( vwidth );
3050                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
3051                 }
3052                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
3053                 {
3054                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
3055
3056                     tk->fmt.video.i_height = uint16( vheight );
3057                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
3058                 }
3059                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
3060                 {
3061                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
3062
3063                     tk->fmt.video.i_visible_width = uint16( vwidth );
3064                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
3065                 }
3066                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
3067                 {
3068                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
3069
3070                     tk->fmt.video.i_visible_height = uint16( vheight );
3071                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
3072                 }
3073                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
3074                 {
3075                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
3076
3077                     tk->f_fps = float( vfps );
3078                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
3079                 }
3080 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
3081 //                {
3082 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
3083
3084 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
3085 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
3086 //                }
3087 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
3088 //                {
3089 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
3090
3091 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
3092 //                }
3093 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
3094 //                {
3095 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
3096
3097 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( gamma ) );
3098 //                }
3099                 else
3100                 {
3101                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
3102                 }
3103             }
3104             if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
3105                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
3106         }
3107         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
3108         {
3109             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
3110             unsigned int j;
3111
3112             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
3113
3114             for( j = 0; j < tka->ListSize(); j++ )
3115             {
3116                 EbmlElement *l = (*tka)[j];
3117
3118                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
3119                 {
3120                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
3121
3122                     tk->fmt.audio.i_rate = (int)float( afreq );
3123                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
3124                 }
3125                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
3126                 {
3127                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
3128
3129                     tk->fmt.audio.i_channels = uint8( achan );
3130                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
3131                 }
3132                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
3133                 {
3134                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
3135
3136                     tk->fmt.audio.i_bitspersample = uint8( abits );
3137                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
3138                 }
3139                 else
3140                 {
3141                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
3142                 }
3143             }
3144         }
3145         else
3146         {
3147             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
3148                      typeid(*l).name() );
3149         }
3150     }
3151 }
3152
3153 /*****************************************************************************
3154  * ParseTracks:
3155  *****************************************************************************/
3156 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
3157 {
3158     EbmlElement *el;
3159     unsigned int i;
3160     int i_upper_level = 0;
3161
3162     msg_Dbg( &sys.demuxer, "|   + Tracks" );
3163
3164     /* Master elements */
3165     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
3166
3167     for( i = 0; i < tracks->ListSize(); i++ )
3168     {
3169         EbmlElement *l = (*tracks)[i];
3170
3171         if( MKV_IS_ID( l, KaxTrackEntry ) )
3172         {
3173             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
3174         }
3175         else
3176         {
3177             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3178         }
3179     }
3180 }
3181
3182 /*****************************************************************************
3183  * ParseInfo:
3184  *****************************************************************************/
3185 void matroska_segment_c::ParseInfo( KaxInfo *info )
3186 {
3187     EbmlElement *el;
3188     EbmlMaster  *m;
3189     size_t i, j;
3190     int i_upper_level = 0;
3191
3192     msg_Dbg( &sys.demuxer, "|   + Information" );
3193
3194     /* Master elements */
3195     m = static_cast<EbmlMaster *>(info);
3196     m->Read( es, info->Generic().Context, i_upper_level, el, true );
3197
3198     for( i = 0; i < m->ListSize(); i++ )
3199     {
3200         EbmlElement *l = (*m)[i];
3201
3202         if( MKV_IS_ID( l, KaxSegmentUID ) )
3203         {
3204             segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
3205
3206             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)segment_uid.GetBuffer() );
3207         }
3208         else if( MKV_IS_ID( l, KaxPrevUID ) )
3209         {
3210             prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
3211
3212             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
3213         }
3214         else if( MKV_IS_ID( l, KaxNextUID ) )
3215         {
3216             next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
3217
3218             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
3219         }
3220         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
3221         {
3222             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
3223
3224             i_timescale = uint64(tcs);
3225
3226             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale="I64Fd,
3227                      i_timescale );
3228         }
3229         else if( MKV_IS_ID( l, KaxDuration ) )
3230         {
3231             KaxDuration &dur = *(KaxDuration*)l;
3232
3233             i_duration = mtime_t( double( dur ) );
3234
3235             msg_Dbg( &sys.demuxer, "|   |   + Duration="I64Fd,
3236                      i_duration );
3237         }
3238         else if( MKV_IS_ID( l, KaxMuxingApp ) )
3239         {
3240             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
3241
3242             psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
3243
3244             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
3245                      psz_muxing_application );
3246         }
3247         else if( MKV_IS_ID( l, KaxWritingApp ) )
3248         {
3249             KaxWritingApp &wapp = *(KaxWritingApp*)l;
3250
3251             psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
3252
3253             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
3254                      psz_writing_application );
3255         }
3256         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
3257         {
3258             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
3259
3260             psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
3261
3262             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
3263                      psz_segment_filename );
3264         }
3265         else if( MKV_IS_ID( l, KaxTitle ) )
3266         {
3267             KaxTitle &title = *(KaxTitle*)l;
3268
3269             psz_title = UTF8ToStr( UTFstring( title ) );
3270
3271             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
3272         }
3273         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
3274         {
3275             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
3276
3277             families.push_back(*uid);
3278
3279             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
3280         }
3281 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
3282         else if( MKV_IS_ID( l, KaxDateUTC ) )
3283         {
3284             KaxDateUTC &date = *(KaxDateUTC*)l;
3285             time_t i_date;
3286             struct tm tmres;
3287             char   buffer[256];
3288
3289             i_date = date.GetEpochDate();
3290             memset( buffer, 0, 256 );
3291             if( gmtime_r( &i_date, &tmres ) &&
3292                 asctime_r( &tmres, buffer ) )
3293             {
3294                 buffer[strlen( buffer)-1]= '\0';
3295                 psz_date_utc = strdup( buffer );
3296                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
3297             }
3298         }
3299 #endif
3300 #if LIBMATROSKA_VERSION >= 0x000704
3301         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
3302         {
3303             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
3304             chapter_translation_c translated;
3305
3306             p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
3307             for( j = 0; j < p_trans->ListSize(); j++ )
3308             {
3309                 EbmlElement *l = (*p_trans)[j];
3310
3311                 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
3312                 {
3313                     translated.editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
3314                 }
3315                 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
3316                 {
3317                     translated.codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
3318                 }
3319                 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
3320                 {
3321                     translated.translated = *( new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) ) );
3322                 }
3323             }
3324
3325             translations.push_back( translated );
3326         }
3327 #endif
3328         else
3329         {
3330             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3331         }
3332     }
3333
3334     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
3335     i_duration = mtime_t(f_dur);
3336 }
3337
3338
3339 /*****************************************************************************
3340  * ParseChapterAtom
3341  *****************************************************************************/
3342 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
3343 {
3344     size_t i, j;
3345
3346     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
3347     for( i = 0; i < ca->ListSize(); i++ )
3348     {
3349         EbmlElement *l = (*ca)[i];
3350
3351         if( MKV_IS_ID( l, KaxChapterUID ) )
3352         {
3353             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
3354             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
3355         }
3356         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
3357         {
3358             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
3359             chapters.b_display_seekpoint = uint8( flag ) == 0;
3360
3361             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
3362         }
3363         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
3364         {
3365             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
3366             chapters.i_start_time = uint64( start ) / I64C(1000);
3367
3368             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
3369         }
3370         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
3371         {
3372             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
3373             chapters.i_end_time = uint64( end ) / I64C(1000);
3374
3375             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
3376         }
3377         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
3378         {
3379             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
3380
3381             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
3382             for( j = 0; j < cd->ListSize(); j++ )
3383             {
3384                 EbmlElement *l= (*cd)[j];
3385
3386                 if( MKV_IS_ID( l, KaxChapterString ) )
3387                 {
3388                     int k;
3389
3390                     KaxChapterString &name =*(KaxChapterString*)l;
3391                     for (k = 0; k < i_level; k++)
3392                         chapters.psz_name += '+';
3393                     chapters.psz_name += ' ';
3394                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
3395                     chapters.b_user_display = true;
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             int i_chapters;
3838
3839             // TODO use a name for each edition, let the TITLE deal with a codec name
3840             for ( j=0; j<p_seg->p_editions->size(); j++ )
3841             {
3842                 if ( p_title->psz_name == NULL )
3843                 {
3844                     sz_name = (*p_seg->p_editions)[j]->GetMainName();
3845                     if ( sz_name != "" )
3846                         p_title->psz_name = strdup( sz_name.c_str() );
3847                 }
3848
3849                 chapter_edition_c *p_edition = (*p_seg->p_editions)[j];
3850
3851                 i_chapters = 0;
3852                 p_edition->PublishChapters( *p_title, i_chapters, 0 );
3853             }
3854
3855             // create a name if there is none
3856             if ( p_title->psz_name == NULL )
3857             {
3858                 sz_name = N_("Segment ");
3859                 char psz_str[6];
3860                 sprintf( psz_str, "%d", i );
3861                 sz_name += psz_str;
3862                 p_title->psz_name = strdup( sz_name.c_str() );
3863             }
3864
3865             titles.push_back( *p_title );
3866         }
3867     }
3868 }
3869
3870 bool demux_sys_t::IsUsedSegment( matroska_segment_c &segment ) const
3871 {
3872     for ( size_t i=0; i< used_segments.size(); i++ )
3873     {
3874         if ( used_segments[i]->FindUID( segment.segment_uid ) )
3875             return true;
3876     }
3877     return false;
3878 }
3879
3880 virtual_segment_c *demux_sys_t::VirtualFromSegments( matroska_segment_c *p_segment ) const
3881 {
3882     size_t i_preloaded, i;
3883
3884     virtual_segment_c *p_result = new virtual_segment_c( p_segment );
3885
3886     // fill our current virtual segment with all hard linked segments
3887     do {
3888         i_preloaded = 0;
3889         for ( i=0; i< opened_segments.size(); i++ )
3890         {
3891             i_preloaded += p_result->AddSegment( opened_segments[i] );
3892         }
3893     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3894
3895     p_result->Sort( );
3896
3897     p_result->PreloadLinked( );
3898
3899     p_result->PrepareChapters( );
3900
3901     return p_result;
3902 }
3903
3904 bool demux_sys_t::PreparePlayback( virtual_segment_c *p_new_segment )
3905 {
3906     if ( p_new_segment != NULL && p_new_segment != p_current_segment )
3907     {
3908         if ( p_current_segment != NULL && p_current_segment->Segment() != NULL )
3909             p_current_segment->Segment()->UnSelect();
3910
3911         p_current_segment = p_new_segment;
3912         i_current_title = p_new_segment->i_sys_title;
3913     }
3914
3915     p_current_segment->LoadCues();
3916     f_duration = p_current_segment->Duration();
3917
3918     /* add information */
3919     p_current_segment->Segment()->InformationCreate( );
3920
3921     p_current_segment->Segment()->Select( 0 );
3922
3923     return true;
3924 }
3925
3926 bool matroska_segment_c::CompareSegmentUIDs( const matroska_segment_c * p_item_a, const matroska_segment_c * p_item_b )
3927 {
3928     EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3929     if ( *p_itema == p_item_b->prev_segment_uid )
3930         return true;
3931
3932     p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3933     if ( *p_itema == p_item_b->segment_uid )
3934         return true;
3935
3936     if ( *p_itema == p_item_b->prev_segment_uid )
3937         return true;
3938
3939     return false;
3940 }
3941
3942 bool matroska_segment_c::Preload( )
3943 {
3944     if ( b_preloaded )
3945         return false;
3946
3947     EbmlElement *el = NULL;
3948
3949     ep->Reset( &sys.demuxer );
3950
3951     while( ( el = ep->Get() ) != NULL )
3952     {
3953         if( MKV_IS_ID( el, KaxInfo ) )
3954         {
3955             ParseInfo( static_cast<KaxInfo*>( el ) );
3956         }
3957         else if( MKV_IS_ID( el, KaxTracks ) )
3958         {
3959             ParseTracks( static_cast<KaxTracks*>( el ) );
3960         }
3961         else if( MKV_IS_ID( el, KaxSeekHead ) )
3962         {
3963             ParseSeekHead( static_cast<KaxSeekHead*>( el ) );
3964         }
3965         else if( MKV_IS_ID( el, KaxCues ) )
3966         {
3967             msg_Dbg( &sys.demuxer, "|   + Cues" );
3968         }
3969         else if( MKV_IS_ID( el, KaxCluster ) )
3970         {
3971             msg_Dbg( &sys.demuxer, "|   + Cluster" );
3972
3973             cluster = (KaxCluster*)el;
3974
3975             i_start_pos = cluster->GetElementPosition();
3976             ParseCluster( );
3977
3978             ep->Down();
3979             /* stop parsing the stream */
3980             break;
3981         }
3982         else if( MKV_IS_ID( el, KaxAttachments ) )
3983         {
3984             msg_Dbg( &sys.demuxer, "|   + Attachments FIXME (but probably never supported)" );
3985         }
3986         else if( MKV_IS_ID( el, KaxChapters ) )
3987         {
3988             msg_Dbg( &sys.demuxer, "|   + Chapters" );
3989             ParseChapters( static_cast<KaxChapters*>( el ) );
3990         }
3991         else if( MKV_IS_ID( el, KaxTag ) )
3992         {
3993             msg_Dbg( &sys.demuxer, "|   + Tags FIXME TODO" );
3994         }
3995         else
3996         {
3997             msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid(*el).name() );
3998         }
3999     }
4000
4001     b_preloaded = true;
4002
4003     return true;
4004 }
4005
4006 matroska_segment_c *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
4007 {
4008     for (size_t i=0; i<opened_segments.size(); i++)
4009     {
4010         if ( opened_segments[i]->segment_uid == uid )
4011             return opened_segments[i];
4012     }
4013     return NULL;
4014 }
4015
4016 chapter_item_c *demux_sys_t::BrowseCodecPrivate( unsigned int codec_id, 
4017                                         bool (*match)(const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size ), 
4018                                         const void *p_cookie, 
4019                                         size_t i_cookie_size, 
4020                                         virtual_segment_c * &p_segment_found )
4021 {
4022     chapter_item_c *p_result = NULL;
4023     for (size_t i=0; i<opened_segments.size(); i++)
4024     {
4025         p_result = used_segments[i]->BrowseCodecPrivate( codec_id, match, p_cookie, i_cookie_size );
4026         if ( p_result != NULL )
4027         {
4028             p_segment_found = used_segments[i];
4029             break;
4030         }
4031     }
4032     return p_result;
4033 }
4034
4035 void virtual_segment_c::Sort()
4036 {
4037     // keep the current segment index
4038     matroska_segment_c *p_segment = linked_segments[i_current_segment];
4039
4040     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_c::CompareSegmentUIDs );
4041
4042     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
4043         if ( linked_segments[i_current_segment] == p_segment )
4044             break;
4045 }
4046
4047 size_t virtual_segment_c::AddSegment( matroska_segment_c *p_segment )
4048 {
4049     size_t i;
4050     // check if it's not already in here
4051     for ( i=0; i<linked_segments.size(); i++ )
4052     {
4053         if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
4054             return 0;
4055     }
4056
4057     // find possible mates
4058     for ( i=0; i<linked_uids.size(); i++ )
4059     {
4060         if (   p_segment->segment_uid == linked_uids[i] 
4061             || p_segment->prev_segment_uid == linked_uids[i] 
4062             || p_segment->next_segment_uid == linked_uids[i] )
4063         {
4064             linked_segments.push_back( p_segment );
4065
4066             AppendUID( p_segment->prev_segment_uid );
4067             AppendUID( p_segment->next_segment_uid );
4068
4069             return 1;
4070         }
4071     }
4072     return 0;
4073 }
4074
4075 void virtual_segment_c::PreloadLinked( )
4076 {
4077     for ( size_t i=0; i<linked_segments.size(); i++ )
4078     {
4079         linked_segments[i]->Preload( );
4080     }
4081     i_current_edition = linked_segments[0]->i_default_edition;
4082 }
4083
4084 mtime_t virtual_segment_c::Duration() const
4085 {
4086     mtime_t i_duration;
4087     if ( linked_segments.size() == 0 )
4088         i_duration = 0;
4089     else {
4090         matroska_segment_c *p_last_segment = linked_segments[linked_segments.size()-1];
4091 //        p_last_segment->ParseCluster( );
4092
4093         i_duration = p_last_segment->i_start_time / 1000 + p_last_segment->i_duration;
4094     }
4095     return i_duration;
4096 }
4097
4098 void virtual_segment_c::LoadCues( )
4099 {
4100     for ( size_t i=0; i<linked_segments.size(); i++ )
4101     {
4102         linked_segments[i]->LoadCues();
4103     }
4104 }
4105
4106 void virtual_segment_c::AppendUID( const EbmlBinary & UID )
4107 {
4108     if ( UID.GetBuffer() == NULL )
4109         return;
4110
4111     for (size_t i=0; i<linked_uids.size(); i++)
4112     {
4113         if ( UID == linked_uids[i] )
4114             return;
4115     }
4116     linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
4117 }
4118
4119 void matroska_segment_c::Seek( mtime_t i_date, mtime_t i_time_offset )
4120 {
4121     KaxBlock    *block;
4122     int         i_track_skipping;
4123     int64_t     i_block_duration;
4124     int64_t     i_block_ref1;
4125     int64_t     i_block_ref2;
4126     size_t      i_track;
4127     int64_t     i_seek_position = i_start_pos;
4128     int64_t     i_seek_time = i_start_time;
4129
4130     if ( i_index > 0 )
4131     {
4132         int i_idx = 0;
4133
4134         for( ; i_idx < i_index; i_idx++ )
4135         {
4136             if( index[i_idx].i_time + i_time_offset > i_date )
4137             {
4138                 break;
4139             }
4140         }
4141
4142         if( i_idx > 0 )
4143         {
4144             i_idx--;
4145         }
4146
4147         i_seek_position = index[i_idx].i_position;
4148         i_seek_time = index[i_idx].i_time;
4149     }
4150
4151     msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
4152                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
4153
4154     es.I_O().setFilePointer( i_seek_position, seek_beginning );
4155
4156     delete ep;
4157     ep = new EbmlParser( &es, segment, &sys.demuxer );
4158     cluster = NULL;
4159
4160     sys.i_start_pts = i_date;
4161
4162     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
4163
4164     /* now parse until key frame */
4165 #define tk  tracks[i_track]
4166     i_track_skipping = 0;
4167     for( i_track = 0; i_track < tracks.size(); i_track++ )
4168     {
4169         if( tk->fmt.i_cat == VIDEO_ES )
4170         {
4171             tk->b_search_keyframe = VLC_TRUE;
4172             i_track_skipping++;
4173         }
4174         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
4175     }
4176
4177
4178     while( i_track_skipping > 0 )
4179     {
4180         if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
4181         {
4182             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
4183
4184             return;
4185         }
4186
4187         for( i_track = 0; i_track < tracks.size(); i_track++ )
4188         {
4189             if( tk->i_number == block->TrackNum() )
4190             {
4191                 break;
4192             }
4193         }
4194
4195         sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
4196
4197         if( i_track < tracks.size() )
4198         {
4199             if( sys.i_pts >= sys.i_start_pts )
4200             {
4201                 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4202                 i_track_skipping = 0;
4203             }
4204             else if( tk->fmt.i_cat == VIDEO_ES )
4205             {
4206                 if( i_block_ref1 == -1 && tk->b_search_keyframe )
4207                 {
4208                     tk->b_search_keyframe = VLC_FALSE;
4209                     i_track_skipping--;
4210                 }
4211                 if( !tk->b_search_keyframe )
4212                 {
4213                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
4214                 }
4215             } 
4216         }
4217
4218         delete block;
4219     }
4220 #undef tk
4221 }
4222
4223 void virtual_segment_c::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, chapter_item_c *psz_chapter )
4224 {
4225     demux_sys_t *p_sys = demuxer.p_sys;
4226     size_t i;
4227
4228     // find the actual time for an ordered edition
4229     if ( psz_chapter == NULL )
4230     {
4231         if ( Edition() && Edition()->b_ordered )
4232         {
4233             /* 1st, we need to know in which chapter we are */
4234             psz_chapter = (*p_editions)[i_current_edition]->FindTimecode( i_date );
4235         }
4236     }
4237
4238     if ( psz_chapter != NULL )
4239     {
4240         psz_current_chapter = psz_chapter;
4241         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
4242         if ( psz_chapter->i_seekpoint_num > 0 )
4243         {
4244             demuxer.info.i_update |= INPUT_UPDATE_TITLE | INPUT_UPDATE_SEEKPOINT;
4245             demuxer.info.i_title = p_sys->i_current_title = i_sys_title;
4246             demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
4247         }
4248     }
4249
4250     // find the best matching segment
4251     for ( i=0; i<linked_segments.size(); i++ )
4252     {
4253         if ( i_date < linked_segments[i]->i_start_time )
4254             break;
4255     }
4256
4257     if ( i > 0 )
4258         i--;
4259
4260     if ( i_current_segment != i  )
4261     {
4262         linked_segments[i_current_segment]->UnSelect();
4263         linked_segments[i]->Select( i_date );
4264         i_current_segment = i;
4265     }
4266
4267     linked_segments[i]->Seek( i_date, i_time_offset );
4268 }
4269
4270 void chapter_codec_cmds_c::AddCommand( const KaxChapterProcessCommand & command )
4271 {
4272     size_t i;
4273
4274     uint32 codec_time = uint32(-1);
4275     for( i = 0; i < command.ListSize(); i++ )
4276     {
4277         const EbmlElement *k = command[i];
4278
4279         if( MKV_IS_ID( k, KaxChapterProcessTime ) )
4280         {
4281             codec_time = uint32( *static_cast<const KaxChapterProcessTime*>( k ) );
4282             break;
4283         }
4284     }
4285
4286     for( i = 0; i < command.ListSize(); i++ )
4287     {
4288         const EbmlElement *k = command[i];
4289
4290         if( MKV_IS_ID( k, KaxChapterProcessData ) )
4291         {
4292             KaxChapterProcessData *p_data =  new KaxChapterProcessData( *static_cast<const KaxChapterProcessData*>( k ) );
4293             switch ( codec_time )
4294             {
4295             case 0:
4296                 during_cmds.push_back( *p_data );
4297                 break;
4298             case 1:
4299                 enter_cmds.push_back( *p_data );
4300                 break;
4301             case 2:
4302                 leave_cmds.push_back( *p_data );
4303                 break;
4304             default:
4305                 delete p_data;
4306             }
4307         }
4308     }
4309 }
4310
4311 bool chapter_item_c::Enter()
4312 {
4313     bool f_result = false;
4314     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4315     while ( index != codecs.end() )
4316     {
4317         f_result |= (*index)->Enter();
4318         index++;
4319     }
4320     std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4321     while ( index_ != sub_chapters.end() )
4322     {
4323         f_result |= (*index_)->Enter();
4324         index_++;
4325     }
4326     return f_result;
4327 }
4328
4329 bool chapter_item_c::Leave()
4330 {
4331     bool f_result = false;
4332     std::vector<chapter_codec_cmds_c*>::iterator index = codecs.begin();
4333     while ( index != codecs.end() )
4334     {
4335         f_result |= (*index)->Leave();
4336         index++;
4337     }
4338     std::vector<chapter_item_c*>::iterator index_ = sub_chapters.begin();
4339     while ( index_ != sub_chapters.end() )
4340     {
4341         f_result |= (*index_)->Leave();
4342         index_++;
4343     }
4344     return f_result;
4345 }
4346
4347 bool dvd_chapter_codec_c::Enter()
4348 {
4349     bool f_result = false;
4350     std::vector<KaxChapterProcessData>::iterator index = enter_cmds.begin();
4351     while ( index != enter_cmds.end() )
4352     {
4353         if ( (*index).GetSize() )
4354         {
4355             binary *p_data = (*index).GetBuffer();
4356             size_t i_size = *p_data++;
4357             // avoid reading too much from the buffer
4358             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4359             for ( ; i_size > 0; i_size--, p_data += 8 )
4360             {
4361                 f_result |= interpretor.Interpret( p_data );
4362             }
4363         }
4364         index++;
4365     }
4366     return f_result;
4367 }
4368
4369 bool dvd_chapter_codec_c::Leave()
4370 {
4371     bool f_result = false;
4372     std::vector<KaxChapterProcessData>::iterator index = leave_cmds.begin();
4373     while ( index != leave_cmds.end() )
4374     {
4375         if ( (*index).GetSize() )
4376         {
4377             binary *p_data = (*index).GetBuffer();
4378             size_t i_size = *p_data++;
4379             // avoid reading too much from the buffer
4380             i_size = min( i_size, ((*index).GetSize() - 1) >> 3 );
4381             for ( ; i_size > 0; i_size--, p_data += 8 )
4382             {
4383                 f_result |= interpretor.Interpret( p_data );
4384             }
4385         }
4386         index++;
4387     }
4388     return f_result;
4389 }
4390
4391 // see http://www.dvd-replica.com/DVD/vmcmdset.php for a description of DVD commands
4392 bool dvd_command_interpretor_c::Interpret( const binary * p_command, size_t i_size )
4393 {
4394     if ( i_size != 8 )
4395         return false;
4396
4397     bool f_result = false;
4398     uint16 i_command = ( p_command[0] << 8 ) + p_command[1];
4399
4400     switch ( i_command )
4401     {
4402     case CMD_JUMP_TT:
4403         {
4404             uint8 i_title = p_command[5];
4405             msg_Dbg( &sys.demuxer, "DVD command: JumpTT %d", i_title );
4406
4407             // find in the ChapProcessPrivate matching this Title level
4408             virtual_segment_c *p_segment;
4409             chapter_item_c *p_chapter;
4410             p_chapter = sys.BrowseCodecPrivate( 1, MatchTitleNumber, &i_title, sizeof(i_title), p_segment );
4411             if ( p_chapter != NULL )
4412             {
4413                 // if the segment is not part of the current segment, select the new one
4414                 if ( p_segment != sys.p_current_segment )
4415                 {
4416                     sys.PreparePlayback( p_segment );
4417                 }
4418     
4419                 p_chapter->Enter();
4420                 
4421                 // jump to the location in the found segment
4422                 p_segment->Seek( sys.demuxer, p_chapter->i_user_start_time, -1, p_chapter );
4423                 f_result = true;
4424             }
4425
4426             break;
4427         }
4428     case CMD_CALLSS_VTSM:
4429         {
4430             msg_Dbg( &sys.demuxer, "DVD command: CallSS VTSM" );
4431             break;
4432         }
4433     default:
4434         {
4435             msg_Dbg( &sys.demuxer, "DVD command: unsupported %02X %02X %02X %02X %02X %02X %02X %02X"
4436                      ,p_command[0]
4437                      ,p_command[1]
4438                      ,p_command[2]
4439                      ,p_command[3]
4440                      ,p_command[4]
4441                      ,p_command[5]
4442                      ,p_command[6]
4443                      ,p_command[7]);
4444             break;
4445         }
4446     }
4447
4448     return f_result;
4449 }
4450
4451 bool dvd_command_interpretor_c::MatchTitleNumber( const chapter_codec_cmds_c &data, const void *p_cookie, size_t i_cookie_size )
4452 {
4453     if ( i_cookie_size != 1 || data.m_private_data.GetSize() < 4 )
4454         return false;
4455     
4456     if ( data.m_private_data.GetBuffer()[0] != 0x28 )
4457         return false;
4458
4459     uint16 i_gtitle = (data.m_private_data.GetBuffer()[1] << 8 ) + data.m_private_data.GetBuffer()[2];
4460     uint8 i_title = *(uint8*)p_cookie;
4461
4462     return (i_gtitle == i_title);
4463 }