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