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