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