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