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