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