25720b7a9b98c2579873f78b331c7952536c29bd
[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             MP4_ReadBoxCommon( p_mp4_stream, p_box );
1339             MP4_ReadBox_sample_vide( p_mp4_stream, p_box );
1340             tk->fmt.i_codec = p_box->i_type;
1341             tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1342             tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1343             tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1344             tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1345             memcpy( tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, tk->fmt.i_extra );
1346             MP4_FreeBox_sample_vide( p_box );
1347             stream_MemoryDelete( p_mp4_stream, VLC_TRUE );
1348         }
1349         else if( !strcmp( tk->psz_codec, "A_MS/ACM" ) )
1350         {
1351             if( tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1352             {
1353                 msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1354                 tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1355             }
1356             else
1357             {
1358                 WAVEFORMATEX *p_wf = (WAVEFORMATEX*)tk->p_extra_data;
1359
1360                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &tk->fmt.i_codec, NULL );
1361
1362                 tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
1363                 tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1364                 tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1365                 tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1366                 tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1367
1368                 tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
1369                 if( tk->fmt.i_extra > 0 )
1370                 {
1371                     tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1372                     memcpy( tk->fmt.p_extra, &p_wf[1], tk->fmt.i_extra );
1373                 }
1374             }
1375         }
1376         else if( !strcmp( tk->psz_codec, "A_MPEG/L3" ) ||
1377                  !strcmp( tk->psz_codec, "A_MPEG/L2" ) ||
1378                  !strcmp( tk->psz_codec, "A_MPEG/L1" ) )
1379         {
1380             tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', 'g', 'a' );
1381         }
1382         else if( !strcmp( tk->psz_codec, "A_AC3" ) )
1383         {
1384             tk->fmt.i_codec = VLC_FOURCC( 'a', '5', '2', ' ' );
1385         }
1386         else if( !strcmp( tk->psz_codec, "A_DTS" ) )
1387         {
1388             tk->fmt.i_codec = VLC_FOURCC( 'd', 't', 's', ' ' );
1389         }
1390         else if( !strcmp( tk->psz_codec, "A_FLAC" ) )
1391         {
1392             tk->fmt.i_codec = VLC_FOURCC( 'f', 'l', 'a', 'c' );
1393             tk->fmt.i_extra = tk->i_extra_data;
1394             tk->fmt.p_extra = malloc( tk->i_extra_data );
1395             memcpy( tk->fmt.p_extra,tk->p_extra_data, tk->i_extra_data );
1396         }
1397         else if( !strcmp( tk->psz_codec, "A_VORBIS" ) )
1398         {
1399             int i, i_offset = 1, i_size[3], i_extra;
1400             uint8_t *p_extra;
1401
1402             tk->fmt.i_codec = VLC_FOURCC( 'v', 'o', 'r', 'b' );
1403
1404             /* Split the 3 headers */
1405             if( tk->p_extra_data[0] != 0x02 )
1406                 msg_Err( &sys.demuxer, "invalid vorbis header" );
1407
1408             for( i = 0; i < 2; i++ )
1409             {
1410                 i_size[i] = 0;
1411                 while( i_offset < tk->i_extra_data )
1412                 {
1413                     i_size[i] += tk->p_extra_data[i_offset];
1414                     if( tk->p_extra_data[i_offset++] != 0xff ) break;
1415                 }
1416             }
1417
1418             i_size[0] = __MIN(i_size[0], tk->i_extra_data - i_offset);
1419             i_size[1] = __MIN(i_size[1], tk->i_extra_data -i_offset -i_size[0]);
1420             i_size[2] = tk->i_extra_data - i_offset - i_size[0] - i_size[1];
1421
1422             tk->fmt.i_extra = 3 * 2 + i_size[0] + i_size[1] + i_size[2];
1423             tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1424             p_extra = (uint8_t *)tk->fmt.p_extra; i_extra = 0;
1425             for( i = 0; i < 3; i++ )
1426             {
1427                 *(p_extra++) = i_size[i] >> 8;
1428                 *(p_extra++) = i_size[i] & 0xFF;
1429                 memcpy( p_extra, tk->p_extra_data + i_offset + i_extra,
1430                         i_size[i] );
1431                 p_extra += i_size[i];
1432                 i_extra += i_size[i];
1433             }
1434         }
1435         else if( !strncmp( tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1436                  !strncmp( tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1437         {
1438             int i_profile, i_srate;
1439             static unsigned int i_sample_rates[] =
1440             {
1441                     96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1442                         16000, 12000, 11025, 8000,  7350,  0,     0,     0
1443             };
1444
1445             tk->fmt.i_codec = VLC_FOURCC( 'm', 'p', '4', 'a' );
1446             /* create data for faad (MP4DecSpecificDescrTag)*/
1447
1448             if( !strcmp( &tk->psz_codec[12], "MAIN" ) )
1449             {
1450                 i_profile = 0;
1451             }
1452             else if( !strcmp( &tk->psz_codec[12], "LC" ) )
1453             {
1454                 i_profile = 1;
1455             }
1456             else if( !strcmp( &tk->psz_codec[12], "SSR" ) )
1457             {
1458                 i_profile = 2;
1459             }
1460             else
1461             {
1462                 i_profile = 3;
1463             }
1464
1465             for( i_srate = 0; i_srate < 13; i_srate++ )
1466             {
1467                 if( i_sample_rates[i_srate] == tk->fmt.audio.i_rate )
1468                 {
1469                     break;
1470                 }
1471             }
1472             msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1473
1474             tk->fmt.i_extra = 2;
1475             tk->fmt.p_extra = malloc( tk->fmt.i_extra );
1476             ((uint8_t*)tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1477             ((uint8_t*)tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (tk->fmt.audio.i_channels << 3);
1478         }
1479         else if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) ||
1480                  !strcmp( tk->psz_codec, "A_PCM/INT/LIT" ) ||
1481                  !strcmp( tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1482         {
1483             if( !strcmp( tk->psz_codec, "A_PCM/INT/BIG" ) )
1484             {
1485                 tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1486             }
1487             else
1488             {
1489                 tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1490             }
1491             tk->fmt.audio.i_blockalign = ( tk->fmt.audio.i_bitspersample + 7 ) / 8 * tk->fmt.audio.i_channels;
1492         }
1493         else if( !strcmp( tk->psz_codec, "A_TTA1" ) )
1494         {
1495             /* FIXME: support this codec */
1496             msg_Err( &sys.demuxer, "TTA not supported yet[%d, n=%d]", i_track, tk->i_number );
1497             tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1498         }
1499         else if( !strcmp( tk->psz_codec, "A_WAVPACK4" ) )
1500         {
1501             /* FIXME: support this codec */
1502             msg_Err( &sys.demuxer, "Wavpack not supported yet[%d, n=%d]", i_track, tk->i_number );
1503             tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1504         }
1505         else if( !strcmp( tk->psz_codec, "S_TEXT/UTF8" ) )
1506         {
1507             tk->fmt.i_codec = VLC_FOURCC( 's', 'u', 'b', 't' );
1508             tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1509         }
1510         else if( !strcmp( tk->psz_codec, "S_TEXT/SSA" ) ||
1511                  !strcmp( tk->psz_codec, "S_TEXT/ASS" ) ||
1512                  !strcmp( tk->psz_codec, "S_SSA" ) ||
1513                  !strcmp( tk->psz_codec, "S_ASS" ))
1514         {
1515             tk->fmt.i_codec = VLC_FOURCC( 's', 's', 'a', ' ' );
1516             tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1517         }
1518         else if( !strcmp( tk->psz_codec, "S_VOBSUB" ) )
1519         {
1520             tk->fmt.i_codec = VLC_FOURCC( 's','p','u',' ' );
1521             if( tk->i_extra_data )
1522             {
1523                 char *p_start;
1524                 char *p_buf = (char *)malloc( tk->i_extra_data + 1);
1525                 memcpy( p_buf, tk->p_extra_data , tk->i_extra_data );
1526                 p_buf[tk->i_extra_data] = '\0';
1527                 
1528                 p_start = strstr( p_buf, "size:" );
1529                 if( sscanf( p_start, "size: %dx%d",
1530                         &tk->fmt.subs.spu.i_original_frame_width, &tk->fmt.subs.spu.i_original_frame_height ) == 2 )
1531                 {
1532                     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 );
1533                 }
1534                 else
1535                 {
1536                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1537                 }
1538                 free( p_buf );
1539             }
1540         }
1541         else if( !strcmp( tk->psz_codec, "B_VOBBTN" ) )
1542         {
1543             /* FIXME: support this codec */
1544             msg_Err( &sys.demuxer, "Vob Buttons not supported yet[%d, n=%d]", i_track, tk->i_number );
1545             tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1546         }
1547         else
1548         {
1549             msg_Err( &sys.demuxer, "unknow codec id=`%s'", tk->psz_codec );
1550             tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1551         }
1552         if( tk->b_default )
1553         {
1554             tk->fmt.i_priority = 1000;
1555         }
1556
1557         tk->p_es = es_out_Add( sys.demuxer.out, &tk->fmt );
1558
1559         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_start_time );
1560 #undef tk
1561     }
1562     
1563     sys.i_start_pts = i_start_time;
1564     ep->Reset();
1565
1566     // reset the stream reading to the first cluster of the segment used
1567     es.I_O().setFilePointer( i_start_pos );
1568
1569     return true;
1570 }
1571
1572 void matroska_segment_t::UnSelect( )
1573 {
1574     size_t i_track;
1575
1576     for( i_track = 0; i_track < tracks.size(); i_track++ )
1577     {
1578 #define tk  tracks[i_track]
1579         if ( tk->p_es != NULL )
1580         {
1581             es_out_Del( sys.demuxer.out, tk->p_es );
1582             tk->p_es = NULL;
1583         }
1584 #undef tk
1585     }
1586 }
1587
1588 void virtual_segment_t::UpdateCurrentToChapter( demux_t & demux )
1589 {
1590     demux_sys_t & sys = *demux.p_sys;
1591     const chapter_item_t *psz_curr_chapter;
1592
1593     /* update current chapter/seekpoint */
1594     if ( editions.size() )
1595     {
1596         /* 1st, we need to know in which chapter we are */
1597         psz_curr_chapter = editions[i_current_edition].FindTimecode( sys.i_pts );
1598
1599         /* we have moved to a new chapter */
1600         if (psz_curr_chapter != NULL && psz_current_chapter != psz_curr_chapter)
1601         {
1602             if (psz_current_chapter->i_seekpoint_num != psz_curr_chapter->i_seekpoint_num && psz_curr_chapter->i_seekpoint_num > 0)
1603             {
1604                 demux.info.i_update |= INPUT_UPDATE_SEEKPOINT;
1605                 demux.info.i_seekpoint = psz_curr_chapter->i_seekpoint_num - 1;
1606             }
1607
1608             if ( editions[i_current_edition].b_ordered )
1609             {
1610                 /* TODO check if we need to silently seek to a new location in the stream (switch to another chapter) */
1611                 if (psz_current_chapter->i_end_time != psz_curr_chapter->i_start_time)
1612                     Seek( demux, sys.i_pts, 0, psz_curr_chapter );
1613                 /* count the last duration time found for each track in a table (-1 not found, -2 silent) */
1614                 /* only seek after each duration >= end timecode of the current chapter */
1615             }
1616
1617 //            i_user_time = psz_curr_chapter->i_user_start_time - psz_curr_chapter->i_start_time;
1618 //            i_start_pts = psz_curr_chapter->i_user_start_time;
1619         }
1620         psz_current_chapter = psz_curr_chapter;
1621     }
1622 }
1623
1624 static void Seek( demux_t *p_demux, mtime_t i_date, double f_percent, const chapter_item_t *psz_chapter )
1625 {
1626     demux_sys_t        *p_sys = p_demux->p_sys;
1627     virtual_segment_t  *p_vsegment = p_sys->p_current_segment;
1628     matroska_segment_t *p_segment = p_vsegment->Segment();
1629     mtime_t            i_time_offset = 0;
1630
1631     int         i_index;
1632
1633     msg_Dbg( p_demux, "seek request to "I64Fd" (%f%%)", i_date, f_percent );
1634     if( i_date < 0 && f_percent < 0 )
1635     {
1636         msg_Warn( p_demux, "cannot seek nowhere !" );
1637         return;
1638     }
1639     if( f_percent > 1.0 )
1640     {
1641         msg_Warn( p_demux, "cannot seek so far !" );
1642         return;
1643     }
1644
1645     /* seek without index or without date */
1646     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_segment->b_cues || i_date < 0 ))
1647     {
1648         if (p_sys->f_duration >= 0)
1649         {
1650             i_date = int64_t( f_percent * p_sys->f_duration * 1000.0 );
1651         }
1652         else
1653         {
1654             int64_t i_pos = int64_t( f_percent * stream_Size( p_demux->s ) );
1655
1656             msg_Dbg( p_demux, "inacurate way of seeking" );
1657             for( i_index = 0; i_index < p_segment->i_index; i_index++ )
1658             {
1659                 if( p_segment->index[i_index].i_position >= i_pos)
1660                 {
1661                     break;
1662                 }
1663             }
1664             if( i_index == p_segment->i_index )
1665             {
1666                 i_index--;
1667             }
1668
1669             i_date = p_segment->index[i_index].i_time;
1670
1671 #if 0
1672             if( p_segment->index[i_index].i_position < i_pos )
1673             {
1674                 EbmlElement *el;
1675
1676                 msg_Warn( p_demux, "searching for cluster, could take some time" );
1677
1678                 /* search a cluster */
1679                 while( ( el = p_sys->ep->Get() ) != NULL )
1680                 {
1681                     if( MKV_IS_ID( el, KaxCluster ) )
1682                     {
1683                         KaxCluster *cluster = (KaxCluster*)el;
1684
1685                         /* add it to the index */
1686                         p_segment->IndexAppendCluster( cluster );
1687
1688                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
1689                         {
1690                             p_sys->cluster = cluster;
1691                             p_sys->ep->Down();
1692                             break;
1693                         }
1694                     }
1695                 }
1696             }
1697 #endif
1698         }
1699     }
1700
1701     p_vsegment->Seek( *p_demux, i_date, i_time_offset, psz_chapter );
1702 }
1703
1704 /*****************************************************************************
1705  * Demux: reads and demuxes data packets
1706  *****************************************************************************
1707  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1708  *****************************************************************************/
1709 static int Demux( demux_t *p_demux)
1710 {
1711     demux_sys_t        *p_sys = p_demux->p_sys;
1712     virtual_segment_t  *p_vsegment = p_sys->p_current_segment;
1713     matroska_segment_t *p_segmet = p_vsegment->Segment();
1714     if ( p_segmet == NULL ) return 0;
1715     int                i_block_count = 0;
1716
1717     KaxBlock *block;
1718     int64_t i_block_duration;
1719     int64_t i_block_ref1;
1720     int64_t i_block_ref2;
1721
1722     for( ;; )
1723     {
1724         if( p_sys->i_pts >= p_sys->i_start_pts  )
1725             p_vsegment->UpdateCurrentToChapter( *p_demux );
1726         
1727         if ( p_vsegment->EditionIsOrdered() && p_vsegment->CurrentChapter() == NULL )
1728         {
1729             /* nothing left to read in this ordered edition */
1730             if ( !p_vsegment->SelectNext() )
1731                 return 0;
1732             p_segmet->UnSelect( );
1733             
1734             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1735
1736             /* switch to the next segment */
1737             p_segmet = p_vsegment->Segment();
1738             if ( !p_segmet->Select( 0 ) )
1739             {
1740                 msg_Err( p_demux, "Failed to select new segment" );
1741                 return 0;
1742             }
1743             continue;
1744         }
1745
1746         if( p_segmet->BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1747         {
1748             if ( p_vsegment->EditionIsOrdered() )
1749             {
1750                 // check if there are more chapters to read
1751                 if ( p_vsegment->CurrentChapter() != NULL )
1752                 {
1753                     p_sys->i_pts = p_vsegment->CurrentChapter()->i_user_end_time;
1754                     return 1;
1755                 }
1756
1757                 return 0;
1758             }
1759             msg_Warn( p_demux, "cannot get block EOF?" );
1760             p_segmet->UnSelect( );
1761             
1762             es_out_Control( p_demux->out, ES_OUT_RESET_PCR );
1763
1764             /* switch to the next segment */
1765             if ( !p_vsegment->SelectNext() )
1766                 // no more segments in this stream
1767                 return 0;
1768             p_segmet = p_vsegment->Segment();
1769             if ( !p_segmet->Select( 0 ) )
1770             {
1771                 msg_Err( p_demux, "Failed to select new segment" );
1772                 return 0;
1773             }
1774
1775             continue;
1776         }
1777
1778         p_sys->i_pts = p_sys->i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
1779
1780         if( p_sys->i_pts >= p_sys->i_start_pts  )
1781         {
1782             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1783         }
1784
1785         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1786
1787         delete block;
1788         i_block_count++;
1789
1790         // TODO optimize when there is need to leave or when seeking has been called
1791         if( i_block_count > 5 )
1792         {
1793             return 1;
1794         }
1795     }
1796 }
1797
1798
1799
1800 /*****************************************************************************
1801  * Stream managment
1802  *****************************************************************************/
1803 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1804 {
1805     s = s_;
1806     mb_eof = VLC_FALSE;
1807 }
1808
1809 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1810 {
1811     if( i_size <= 0 || mb_eof )
1812     {
1813         return 0;
1814     }
1815
1816     return stream_Read( s, p_buffer, i_size );
1817 }
1818 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1819 {
1820     int64_t i_pos;
1821
1822     switch( mode )
1823     {
1824         case seek_beginning:
1825             i_pos = i_offset;
1826             break;
1827         case seek_end:
1828             i_pos = stream_Size( s ) - i_offset;
1829             break;
1830         default:
1831             i_pos= stream_Tell( s ) + i_offset;
1832             break;
1833     }
1834
1835     if( i_pos < 0 || i_pos >= stream_Size( s ) )
1836     {
1837         mb_eof = VLC_TRUE;
1838         return;
1839     }
1840
1841     mb_eof = VLC_FALSE;
1842     if( stream_Seek( s, i_pos ) )
1843     {
1844         mb_eof = VLC_TRUE;
1845     }
1846     return;
1847 }
1848 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1849 {
1850     return 0;
1851 }
1852 uint64 vlc_stream_io_callback::getFilePointer( void )
1853 {
1854     return stream_Tell( s );
1855 }
1856 void vlc_stream_io_callback::close( void )
1857 {
1858     return;
1859 }
1860
1861
1862 /*****************************************************************************
1863  * Ebml Stream parser
1864  *****************************************************************************/
1865 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1866 {
1867     int i;
1868
1869     m_es = es;
1870     m_got = NULL;
1871     m_el[0] = el_start;
1872
1873     for( i = 1; i < 6; i++ )
1874     {
1875         m_el[i] = NULL;
1876     }
1877     mi_level = 1;
1878     mi_user_level = 1;
1879     mb_keep = VLC_FALSE;
1880 }
1881
1882 EbmlParser::~EbmlParser( void )
1883 {
1884     int i;
1885
1886     for( i = 1; i < mi_level; i++ )
1887     {
1888         if( !mb_keep )
1889         {
1890             delete m_el[i];
1891         }
1892         mb_keep = VLC_FALSE;
1893     }
1894 }
1895
1896 void EbmlParser::Up( void )
1897 {
1898     if( mi_user_level == mi_level )
1899     {
1900         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1901     }
1902
1903     mi_user_level--;
1904 }
1905
1906 void EbmlParser::Down( void )
1907 {
1908     mi_user_level++;
1909     mi_level++;
1910 }
1911
1912 void EbmlParser::Keep( void )
1913 {
1914     mb_keep = VLC_TRUE;
1915 }
1916
1917 int EbmlParser::GetLevel( void )
1918 {
1919     return mi_user_level;
1920 }
1921
1922 void EbmlParser::Reset( void )
1923 {
1924     while ( mi_level > 0)
1925     {
1926         delete m_el[mi_level];
1927         m_el[mi_level] = NULL;
1928         mi_level--;
1929     }
1930     mi_user_level = mi_level = 1;
1931 #if LIBEBML_VERSION >= 0x000704
1932     // a little faster and cleaner
1933     m_es->I_O().setFilePointer( static_cast<KaxSegment*>(m_el[0])->GetGlobalPosition(0) );
1934 #else
1935     m_es->I_O().setFilePointer( m_el[0]->GetElementPosition() + m_el[0]->ElementSize(true) - m_el[0]->GetSize() );
1936 #endif
1937 }
1938
1939 EbmlElement *EbmlParser::Get( void )
1940 {
1941     int i_ulev = 0;
1942
1943     if( mi_user_level != mi_level )
1944     {
1945         return NULL;
1946     }
1947     if( m_got )
1948     {
1949         EbmlElement *ret = m_got;
1950         m_got = NULL;
1951
1952         return ret;
1953     }
1954
1955     if( m_el[mi_level] )
1956     {
1957         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1958         if( !mb_keep )
1959         {
1960             delete m_el[mi_level];
1961         }
1962         mb_keep = VLC_FALSE;
1963     }
1964
1965     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1966     if( i_ulev > 0 )
1967     {
1968         while( i_ulev > 0 )
1969         {
1970             if( mi_level == 1 )
1971             {
1972                 mi_level = 0;
1973                 return NULL;
1974             }
1975
1976             delete m_el[mi_level - 1];
1977             m_got = m_el[mi_level -1] = m_el[mi_level];
1978             m_el[mi_level] = NULL;
1979
1980             mi_level--;
1981             i_ulev--;
1982         }
1983         return NULL;
1984     }
1985     else if( m_el[mi_level] == NULL )
1986     {
1987         fprintf( stderr," m_el[mi_level] == NULL\n" );
1988     }
1989
1990     return m_el[mi_level];
1991 }
1992
1993
1994 /*****************************************************************************
1995  * Tools
1996  *  * LoadCues : load the cues element and update index
1997  *
1998  *  * LoadTags : load ... the tags element
1999  *
2000  *  * InformationCreate : create all information, load tags if present
2001  *
2002  *****************************************************************************/
2003 void matroska_segment_t::LoadCues( )
2004 {
2005     int64_t     i_sav_position = es.I_O().getFilePointer();
2006     EbmlParser  *ep;
2007     EbmlElement *el, *cues;
2008
2009     /* *** Load the cue if found *** */
2010     if( i_cues_position < 0 )
2011     {
2012         msg_Warn( &sys.demuxer, "no cues/empty cues found->seek won't be precise" );
2013
2014 //        IndexAppendCluster( cluster );
2015     }
2016
2017     vlc_bool_t b_seekable;
2018
2019     stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
2020     if( !b_seekable )
2021         return;
2022
2023     msg_Dbg( &sys.demuxer, "loading cues" );
2024     es.I_O().setFilePointer( i_cues_position, seek_beginning );
2025     cues = es.FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
2026
2027     if( cues == NULL )
2028     {
2029         msg_Err( &sys.demuxer, "cannot load cues (broken seekhead or file)" );
2030         es.I_O().setFilePointer( i_sav_position, seek_beginning );
2031         return;
2032     }
2033
2034     ep = new EbmlParser( &es, cues );
2035     while( ( el = ep->Get() ) != NULL )
2036     {
2037         if( MKV_IS_ID( el, KaxCuePoint ) )
2038         {
2039 #define idx index[i_index]
2040
2041             idx.i_track       = -1;
2042             idx.i_block_number= -1;
2043             idx.i_position    = -1;
2044             idx.i_time        = 0;
2045             idx.b_key         = VLC_TRUE;
2046
2047             ep->Down();
2048             while( ( el = ep->Get() ) != NULL )
2049             {
2050                 if( MKV_IS_ID( el, KaxCueTime ) )
2051                 {
2052                     KaxCueTime &ctime = *(KaxCueTime*)el;
2053
2054                     ctime.ReadData( es.I_O() );
2055
2056                     idx.i_time = uint64( ctime ) * i_timescale / (mtime_t)1000;
2057                 }
2058                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
2059                 {
2060                     ep->Down();
2061                     while( ( el = ep->Get() ) != NULL )
2062                     {
2063                         if( MKV_IS_ID( el, KaxCueTrack ) )
2064                         {
2065                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
2066
2067                             ctrack.ReadData( es.I_O() );
2068                             idx.i_track = uint16( ctrack );
2069                         }
2070                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
2071                         {
2072                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
2073
2074                             ccpos.ReadData( es.I_O() );
2075                             idx.i_position = segment->GetGlobalPosition( uint64( ccpos ) );
2076                         }
2077                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
2078                         {
2079                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
2080
2081                             cbnum.ReadData( es.I_O() );
2082                             idx.i_block_number = uint32( cbnum );
2083                         }
2084                         else
2085                         {
2086                             msg_Dbg( &sys.demuxer, "         * Unknown (%s)", typeid(*el).name() );
2087                         }
2088                     }
2089                     ep->Up();
2090                 }
2091                 else
2092                 {
2093                     msg_Dbg( &sys.demuxer, "     * Unknown (%s)", typeid(*el).name() );
2094                 }
2095             }
2096             ep->Up();
2097
2098 #if 0
2099             msg_Dbg( &sys.demuxer, " * added time="I64Fd" pos="I64Fd
2100                      " track=%d bnum=%d", idx.i_time, idx.i_position,
2101                      idx.i_track, idx.i_block_number );
2102 #endif
2103
2104             i_index++;
2105             if( i_index >= i_index_max )
2106             {
2107                 i_index_max += 1024;
2108                 index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
2109             }
2110 #undef idx
2111         }
2112         else
2113         {
2114             msg_Dbg( &sys.demuxer, " * Unknown (%s)", typeid(*el).name() );
2115         }
2116     }
2117     delete ep;
2118     delete cues;
2119
2120     b_cues = VLC_TRUE;
2121
2122     msg_Dbg( &sys.demuxer, "loading cues done." );
2123     es.I_O().setFilePointer( i_sav_position, seek_beginning );
2124 }
2125
2126 void matroska_segment_t::LoadTags( )
2127 {
2128     int64_t     i_sav_position = es.I_O().getFilePointer();
2129     EbmlParser  *ep;
2130     EbmlElement *el, *tags;
2131
2132     msg_Dbg( &sys.demuxer, "loading tags" );
2133     es.I_O().setFilePointer( i_tags_position, seek_beginning );
2134     tags = es.FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
2135
2136     if( tags == NULL )
2137     {
2138         msg_Err( &sys.demuxer, "cannot load tags (broken seekhead or file)" );
2139         es.I_O().setFilePointer( i_sav_position, seek_beginning );
2140         return;
2141     }
2142
2143     msg_Dbg( &sys.demuxer, "Tags" );
2144     ep = new EbmlParser( &es, tags );
2145     while( ( el = ep->Get() ) != NULL )
2146     {
2147         if( MKV_IS_ID( el, KaxTag ) )
2148         {
2149             msg_Dbg( &sys.demuxer, "+ Tag" );
2150             ep->Down();
2151             while( ( el = ep->Get() ) != NULL )
2152             {
2153                 if( MKV_IS_ID( el, KaxTagTargets ) )
2154                 {
2155                     msg_Dbg( &sys.demuxer, "|   + Targets" );
2156                     ep->Down();
2157                     while( ( el = ep->Get() ) != NULL )
2158                     {
2159                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2160                     }
2161                     ep->Up();
2162                 }
2163                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
2164                 {
2165                     msg_Dbg( &sys.demuxer, "|   + General" );
2166                     ep->Down();
2167                     while( ( el = ep->Get() ) != NULL )
2168                     {
2169                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2170                     }
2171                     ep->Up();
2172                 }
2173                 else if( MKV_IS_ID( el, KaxTagGenres ) )
2174                 {
2175                     msg_Dbg( &sys.demuxer, "|   + Genres" );
2176                     ep->Down();
2177                     while( ( el = ep->Get() ) != NULL )
2178                     {
2179                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2180                     }
2181                     ep->Up();
2182                 }
2183                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
2184                 {
2185                     msg_Dbg( &sys.demuxer, "|   + Audio Specific" );
2186                     ep->Down();
2187                     while( ( el = ep->Get() ) != NULL )
2188                     {
2189                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2190                     }
2191                     ep->Up();
2192                 }
2193                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
2194                 {
2195                     msg_Dbg( &sys.demuxer, "|   + Images Specific" );
2196                     ep->Down();
2197                     while( ( el = ep->Get() ) != NULL )
2198                     {
2199                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid( *el ).name() );
2200                     }
2201                     ep->Up();
2202                 }
2203                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
2204                 {
2205                     msg_Dbg( &sys.demuxer, "|   + Multi Comment" );
2206                 }
2207                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
2208                 {
2209                     msg_Dbg( &sys.demuxer, "|   + Multi Commercial" );
2210                 }
2211                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
2212                 {
2213                     msg_Dbg( &sys.demuxer, "|   + Multi Date" );
2214                 }
2215                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
2216                 {
2217                     msg_Dbg( &sys.demuxer, "|   + Multi Entity" );
2218                 }
2219                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
2220                 {
2221                     msg_Dbg( &sys.demuxer, "|   + Multi Identifier" );
2222                 }
2223                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
2224                 {
2225                     msg_Dbg( &sys.demuxer, "|   + Multi Legal" );
2226                 }
2227                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
2228                 {
2229                     msg_Dbg( &sys.demuxer, "|   + Multi Title" );
2230                 }
2231                 else
2232                 {
2233                     msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid( *el ).name() );
2234                 }
2235             }
2236             ep->Up();
2237         }
2238         else
2239         {
2240             msg_Dbg( &sys.demuxer, "+ Unknown (%s)", typeid( *el ).name() );
2241         }
2242     }
2243     delete ep;
2244     delete tags;
2245
2246     msg_Dbg( &sys.demuxer, "loading tags done." );
2247     es.I_O().setFilePointer( i_sav_position, seek_beginning );
2248 }
2249
2250 /*****************************************************************************
2251  * ParseSeekHead:
2252  *****************************************************************************/
2253 void matroska_segment_t::ParseSeekHead( EbmlElement *seekhead )
2254 {
2255     EbmlElement *el;
2256     EbmlMaster  *m;
2257     unsigned int i;
2258     int i_upper_level = 0;
2259
2260     msg_Dbg( &sys.demuxer, "|   + Seek head" );
2261
2262     /* Master elements */
2263     m = static_cast<EbmlMaster *>(seekhead);
2264     m->Read( es, seekhead->Generic().Context, i_upper_level, el, true );
2265
2266     for( i = 0; i < m->ListSize(); i++ )
2267     {
2268         EbmlElement *l = (*m)[i];
2269
2270         if( MKV_IS_ID( l, KaxSeek ) )
2271         {
2272             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2273             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2274             int64_t i_pos = -1;
2275
2276             unsigned int j;
2277
2278             for( j = 0; j < sk->ListSize(); j++ )
2279             {
2280                 EbmlElement *l = (*sk)[j];
2281
2282                 if( MKV_IS_ID( l, KaxSeekID ) )
2283                 {
2284                     KaxSeekID &sid = *(KaxSeekID*)l;
2285                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2286                 }
2287                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2288                 {
2289                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2290                     i_pos = uint64( spos );
2291                 }
2292                 else
2293                 {
2294                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2295                 }
2296             }
2297
2298             if( i_pos >= 0 )
2299             {
2300                 if( id == KaxCues::ClassInfos.GlobalId )
2301                 {
2302                     msg_Dbg( &sys.demuxer, "|   |   |   = cues at "I64Fd, i_pos );
2303                     i_cues_position = segment->GetGlobalPosition( i_pos );
2304                 }
2305                 else if( id == KaxChapters::ClassInfos.GlobalId )
2306                 {
2307                     msg_Dbg( &sys.demuxer, "|   |   |   = chapters at "I64Fd, i_pos );
2308                     i_chapters_position = segment->GetGlobalPosition( i_pos );
2309                 }
2310                 else if( id == KaxTags::ClassInfos.GlobalId )
2311                 {
2312                     msg_Dbg( &sys.demuxer, "|   |   |   = tags at "I64Fd, i_pos );
2313                     i_tags_position = segment->GetGlobalPosition( i_pos );
2314                 }
2315             }
2316         }
2317         else
2318         {
2319             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
2320         }
2321     }
2322 }
2323
2324 /*****************************************************************************
2325  * ParseTrackEntry:
2326  *****************************************************************************/
2327 void matroska_segment_t::ParseTrackEntry( EbmlMaster *m )
2328 {
2329     unsigned int i;
2330
2331     mkv_track_t *tk;
2332
2333     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
2334
2335     tk = new mkv_track_t();
2336     tracks.push_back( tk );
2337
2338     /* Init the track */
2339     memset( tk, 0, sizeof( mkv_track_t ) );
2340
2341     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2342     tk->fmt.psz_language = strdup("English");
2343     tk->fmt.psz_description = NULL;
2344
2345     tk->b_default = VLC_TRUE;
2346     tk->b_enabled = VLC_TRUE;
2347     tk->b_silent = VLC_FALSE;
2348     tk->i_number = tracks.size() - 1;
2349     tk->i_extra_data = 0;
2350     tk->p_extra_data = NULL;
2351     tk->psz_codec = NULL;
2352     tk->i_default_duration = 0;
2353     tk->f_timecodescale = 1.0;
2354
2355     tk->b_inited = VLC_FALSE;
2356     tk->i_data_init = 0;
2357     tk->p_data_init = NULL;
2358
2359     tk->psz_codec_name = NULL;
2360     tk->psz_codec_settings = NULL;
2361     tk->psz_codec_info_url = NULL;
2362     tk->psz_codec_download_url = NULL;
2363     
2364     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2365
2366     for( i = 0; i < m->ListSize(); i++ )
2367     {
2368         EbmlElement *l = (*m)[i];
2369
2370         if( MKV_IS_ID( l, KaxTrackNumber ) )
2371         {
2372             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2373
2374             tk->i_number = uint32( tnum );
2375             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
2376         }
2377         else  if( MKV_IS_ID( l, KaxTrackUID ) )
2378         {
2379             KaxTrackUID &tuid = *(KaxTrackUID*)l;
2380
2381             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
2382         }
2383         else  if( MKV_IS_ID( l, KaxTrackType ) )
2384         {
2385             char *psz_type;
2386             KaxTrackType &ttype = *(KaxTrackType*)l;
2387
2388             switch( uint8(ttype) )
2389             {
2390                 case track_audio:
2391                     psz_type = "audio";
2392                     tk->fmt.i_cat = AUDIO_ES;
2393                     break;
2394                 case track_video:
2395                     psz_type = "video";
2396                     tk->fmt.i_cat = VIDEO_ES;
2397                     break;
2398                 case track_subtitle:
2399                     psz_type = "subtitle";
2400                     tk->fmt.i_cat = SPU_ES;
2401                     break;
2402                 default:
2403                     psz_type = "unknown";
2404                     tk->fmt.i_cat = UNKNOWN_ES;
2405                     break;
2406             }
2407
2408             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
2409         }
2410 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2411 //        {
2412 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2413
2414 //            tk->b_enabled = uint32( fenb );
2415 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
2416 //                     uint32( fenb )  );
2417 //        }
2418         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2419         {
2420             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2421
2422             tk->b_default = uint32( fdef );
2423             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
2424         }
2425         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2426         {
2427             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2428
2429             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
2430         }
2431         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
2432         {
2433             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2434
2435             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
2436         }
2437         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2438         {
2439             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2440
2441             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
2442         }
2443         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2444         {
2445             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2446
2447             tk->i_default_duration = uint64(defd);
2448             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
2449         }
2450         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2451         {
2452             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2453
2454             tk->f_timecodescale = float( ttcs );
2455             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
2456         }
2457         else if( MKV_IS_ID( l, KaxTrackName ) )
2458         {
2459             KaxTrackName &tname = *(KaxTrackName*)l;
2460
2461             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2462             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
2463         }
2464         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
2465         {
2466             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2467
2468             tk->fmt.psz_language = strdup( string( lang ).c_str() );
2469             msg_Dbg( &sys.demuxer,
2470                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
2471         }
2472         else  if( MKV_IS_ID( l, KaxCodecID ) )
2473         {
2474             KaxCodecID &codecid = *(KaxCodecID*)l;
2475
2476             tk->psz_codec = strdup( string( codecid ).c_str() );
2477             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2478         }
2479         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2480         {
2481             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2482
2483             tk->i_extra_data = cpriv.GetSize();
2484             if( tk->i_extra_data > 0 )
2485             {
2486                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2487                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2488             }
2489             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2490         }
2491         else if( MKV_IS_ID( l, KaxCodecName ) )
2492         {
2493             KaxCodecName &cname = *(KaxCodecName*)l;
2494
2495             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2496             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2497         }
2498         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2499         {
2500             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2501             MkvTree( sys.demuxer, 3, "Content Encodings" );
2502             for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2503             {
2504                 EbmlElement *l2 = (*cencs)[i];
2505                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2506                 {
2507                     MkvTree( sys.demuxer, 4, "Content Encoding" );
2508                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2509                     for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2510                     {
2511                         EbmlElement *l3 = (*cenc)[i];
2512                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2513                         {
2514                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2515                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
2516                         }
2517                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2518                         {
2519                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2520                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
2521                         }
2522                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2523                         {
2524                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2525                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
2526                         }
2527                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
2528                         {
2529                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2530                             MkvTree( sys.demuxer, 5, "Content Compression" );
2531                             for( unsigned int i = 0; i < compr->ListSize(); i++ )
2532                             {
2533                                 EbmlElement *l4 = (*compr)[i];
2534                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2535                                 {
2536                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2537                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
2538                                     if( uint32( compalg ) == 0 )
2539                                     {
2540                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2541                                     }
2542                                 }
2543                                 else
2544                                 {
2545                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
2546                                 }
2547                             }
2548                         }
2549
2550                         else
2551                         {
2552                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
2553                         }
2554                     }
2555                     
2556                 }
2557                 else
2558                 {
2559                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
2560                 }
2561             }
2562                 
2563         }
2564 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2565 //        {
2566 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2567
2568 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2569 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
2570 //        }
2571 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2572 //        {
2573 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2574
2575 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2576 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
2577 //        }
2578 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2579 //        {
2580 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2581
2582 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2583 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
2584 //        }
2585 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2586 //        {
2587 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2588
2589 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2590 //        }
2591 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2592 //        {
2593 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2594
2595 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2596 //        }
2597         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
2598         {
2599             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2600             unsigned int j;
2601
2602             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
2603             tk->f_fps = 0.0;
2604
2605             for( j = 0; j < tkv->ListSize(); j++ )
2606             {
2607                 EbmlElement *l = (*tkv)[j];
2608 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2609 //                {
2610 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2611
2612 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
2613 //                }
2614 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2615 //                {
2616 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2617
2618 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
2619 //                }
2620 //                else
2621                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2622                 {
2623                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2624
2625                     tk->fmt.video.i_width = uint16( vwidth );
2626                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
2627                 }
2628                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2629                 {
2630                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2631
2632                     tk->fmt.video.i_height = uint16( vheight );
2633                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
2634                 }
2635                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2636                 {
2637                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2638
2639                     tk->fmt.video.i_visible_width = uint16( vwidth );
2640                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
2641                 }
2642                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2643                 {
2644                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2645
2646                     tk->fmt.video.i_visible_height = uint16( vheight );
2647                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
2648                 }
2649                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2650                 {
2651                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2652
2653                     tk->f_fps = float( vfps );
2654                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
2655                 }
2656 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2657 //                {
2658 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2659
2660 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
2661 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2662 //                }
2663 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2664 //                {
2665 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2666
2667 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2668 //                }
2669 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2670 //                {
2671 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2672
2673 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( gamma ) );
2674 //                }
2675                 else
2676                 {
2677                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2678                 }
2679             }
2680             if ( tk->fmt.video.i_visible_height && tk->fmt.video.i_visible_width )
2681                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * tk->fmt.video.i_visible_width / tk->fmt.video.i_visible_height;
2682         }
2683         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
2684         {
2685             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2686             unsigned int j;
2687
2688             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
2689
2690             for( j = 0; j < tka->ListSize(); j++ )
2691             {
2692                 EbmlElement *l = (*tka)[j];
2693
2694                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2695                 {
2696                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2697
2698                     tk->fmt.audio.i_rate = (int)float( afreq );
2699                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
2700                 }
2701                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2702                 {
2703                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2704
2705                     tk->fmt.audio.i_channels = uint8( achan );
2706                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
2707                 }
2708                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2709                 {
2710                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2711
2712                     tk->fmt.audio.i_bitspersample = uint8( abits );
2713                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
2714                 }
2715                 else
2716                 {
2717                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2718                 }
2719             }
2720         }
2721         else
2722         {
2723             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
2724                      typeid(*l).name() );
2725         }
2726     }
2727 }
2728
2729 /*****************************************************************************
2730  * ParseTracks:
2731  *****************************************************************************/
2732 void matroska_segment_t::ParseTracks( EbmlElement *tracks )
2733 {
2734     EbmlElement *el;
2735     EbmlMaster  *m;
2736     unsigned int i;
2737     int i_upper_level = 0;
2738
2739     msg_Dbg( &sys.demuxer, "|   + Tracks" );
2740
2741     /* Master elements */
2742     m = static_cast<EbmlMaster *>(tracks);
2743     m->Read( es, tracks->Generic().Context, i_upper_level, el, true );
2744
2745     for( i = 0; i < m->ListSize(); i++ )
2746     {
2747         EbmlElement *l = (*m)[i];
2748
2749         if( MKV_IS_ID( l, KaxTrackEntry ) )
2750         {
2751             ParseTrackEntry( static_cast<EbmlMaster *>(l) );
2752         }
2753         else
2754         {
2755             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
2756         }
2757     }
2758 }
2759
2760 /*****************************************************************************
2761  * ParseInfo:
2762  *****************************************************************************/
2763 void matroska_segment_t::ParseInfo( EbmlElement *info )
2764 {
2765     EbmlElement *el;
2766     EbmlMaster  *m;
2767     unsigned int i;
2768     int i_upper_level = 0;
2769
2770     msg_Dbg( &sys.demuxer, "|   + Information" );
2771
2772     /* Master elements */
2773     m = static_cast<EbmlMaster *>(info);
2774     m->Read( es, info->Generic().Context, i_upper_level, el, true );
2775
2776     for( i = 0; i < m->ListSize(); i++ )
2777     {
2778         EbmlElement *l = (*m)[i];
2779
2780         if( MKV_IS_ID( l, KaxSegmentUID ) )
2781         {
2782             segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2783
2784             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)segment_uid.GetBuffer() );
2785         }
2786         else if( MKV_IS_ID( l, KaxPrevUID ) )
2787         {
2788             prev_segment_uid = *(new KaxPrevUID(*static_cast<KaxPrevUID*>(l)));
2789
2790             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)prev_segment_uid.GetBuffer() );
2791         }
2792         else if( MKV_IS_ID( l, KaxNextUID ) )
2793         {
2794             next_segment_uid = *(new KaxNextUID(*static_cast<KaxNextUID*>(l)));
2795
2796             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)next_segment_uid.GetBuffer() );
2797         }
2798         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2799         {
2800             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2801
2802             i_timescale = uint64(tcs);
2803
2804             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale="I64Fd,
2805                      i_timescale );
2806         }
2807         else if( MKV_IS_ID( l, KaxDuration ) )
2808         {
2809             KaxDuration &dur = *(KaxDuration*)l;
2810
2811             f_duration = float(dur);
2812
2813             msg_Dbg( &sys.demuxer, "|   |   + Duration=%f",
2814                      f_duration );
2815         }
2816         else if( MKV_IS_ID( l, KaxMuxingApp ) )
2817         {
2818             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2819
2820             psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2821
2822             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
2823                      psz_muxing_application );
2824         }
2825         else if( MKV_IS_ID( l, KaxWritingApp ) )
2826         {
2827             KaxWritingApp &wapp = *(KaxWritingApp*)l;
2828
2829             psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2830
2831             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
2832                      psz_writing_application );
2833         }
2834         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2835         {
2836             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2837
2838             psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2839
2840             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
2841                      psz_segment_filename );
2842         }
2843         else if( MKV_IS_ID( l, KaxTitle ) )
2844         {
2845             KaxTitle &title = *(KaxTitle*)l;
2846
2847             psz_title = UTF8ToStr( UTFstring( title ) );
2848
2849             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
2850         }
2851         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
2852         {
2853             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2854
2855             families.push_back(*uid);
2856
2857             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
2858         }
2859 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2860         else if( MKV_IS_ID( l, KaxDateUTC ) )
2861         {
2862             KaxDateUTC &date = *(KaxDateUTC*)l;
2863             time_t i_date;
2864             struct tm tmres;
2865             char   buffer[256];
2866
2867             i_date = date.GetEpochDate();
2868             memset( buffer, 0, 256 );
2869             if( gmtime_r( &i_date, &tmres ) &&
2870                 asctime_r( &tmres, buffer ) )
2871             {
2872                 buffer[strlen( buffer)-1]= '\0';
2873                 psz_date_utc = strdup( buffer );
2874                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
2875             }
2876         }
2877 #endif
2878         else
2879         {
2880             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
2881         }
2882     }
2883
2884     f_duration *= i_timescale / 1000000.0;
2885 }
2886
2887
2888 /*****************************************************************************
2889  * ParseChapterAtom
2890  *****************************************************************************/
2891 void matroska_segment_t::ParseChapterAtom( int i_level, EbmlMaster *ca, chapter_item_t & chapters )
2892 {
2893     unsigned int i;
2894
2895     if( sys.title == NULL )
2896     {
2897         sys.title = vlc_input_title_New();
2898     }
2899
2900     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
2901     for( i = 0; i < ca->ListSize(); i++ )
2902     {
2903         EbmlElement *l = (*ca)[i];
2904
2905         if( MKV_IS_ID( l, KaxChapterUID ) )
2906         {
2907             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
2908             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
2909         }
2910         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2911         {
2912             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2913             chapters.b_display_seekpoint = uint8( flag ) == 0;
2914
2915             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
2916         }
2917         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2918         {
2919             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2920             chapters.i_start_time = uint64( start ) / I64C(1000);
2921
2922             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
2923         }
2924         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2925         {
2926             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2927             chapters.i_end_time = uint64( end ) / I64C(1000);
2928
2929             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
2930         }
2931         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2932         {
2933             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2934             unsigned int j;
2935
2936             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
2937             for( j = 0; j < cd->ListSize(); j++ )
2938             {
2939                 EbmlElement *l= (*cd)[j];
2940
2941                 if( MKV_IS_ID( l, KaxChapterString ) )
2942                 {
2943                     int k;
2944
2945                     KaxChapterString &name =*(KaxChapterString*)l;
2946                     for (k = 0; k < i_level; k++)
2947                         chapters.psz_name += '+';
2948                     chapters.psz_name += ' ';
2949                     chapters.psz_name += UTF8ToStr( UTFstring( name ) );
2950
2951                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2952                 }
2953                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2954                 {
2955                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2956                     const char *psz = string( lang ).c_str();
2957
2958                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
2959                 }
2960                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2961                 {
2962                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2963                     const char *psz = string( ct ).c_str();
2964
2965                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
2966                 }
2967             }
2968         }
2969         else if( MKV_IS_ID( l, KaxChapterAtom ) )
2970         {
2971             chapter_item_t new_sub_chapter;
2972             ParseChapterAtom( i_level+1, static_cast<EbmlMaster *>(l), new_sub_chapter );
2973             new_sub_chapter.psz_parent = &chapters;
2974             chapters.sub_chapters.push_back( new_sub_chapter );
2975         }
2976     }
2977 }
2978
2979 /*****************************************************************************
2980  * ParseChapters:
2981  *****************************************************************************/
2982 void matroska_segment_t::ParseChapters( EbmlElement *chapters )
2983 {
2984     EbmlElement *el;
2985     EbmlMaster  *m;
2986     unsigned int i;
2987     int i_upper_level = 0;
2988     float f_dur;
2989
2990     /* Master elements */
2991     m = static_cast<EbmlMaster *>(chapters);
2992     m->Read( es, chapters->Generic().Context, i_upper_level, el, true );
2993
2994     for( i = 0; i < m->ListSize(); i++ )
2995     {
2996         EbmlElement *l = (*m)[i];
2997
2998         if( MKV_IS_ID( l, KaxEditionEntry ) )
2999         {
3000             chapter_edition_t edition;
3001             
3002             EbmlMaster *E = static_cast<EbmlMaster *>(l );
3003             unsigned int j;
3004             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
3005             for( j = 0; j < E->ListSize(); j++ )
3006             {
3007                 EbmlElement *l = (*E)[j];
3008
3009                 if( MKV_IS_ID( l, KaxChapterAtom ) )
3010                 {
3011                     chapter_item_t new_sub_chapter;
3012                     ParseChapterAtom( 0, static_cast<EbmlMaster *>(l), new_sub_chapter );
3013                     edition.chapters.push_back( new_sub_chapter );
3014                 }
3015                 else if( MKV_IS_ID( l, KaxEditionUID ) )
3016                 {
3017                     edition.i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
3018                 }
3019                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
3020                 {
3021                     edition.b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
3022                 }
3023                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
3024                 {
3025                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
3026                         i_default_edition = stored_editions.size();
3027                 }
3028                 else
3029                 {
3030                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
3031                 }
3032             }
3033             stored_editions.push_back( edition );
3034         }
3035         else
3036         {
3037             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
3038         }
3039     }
3040
3041     for( i = 0; i < stored_editions.size(); i++ )
3042     {
3043         stored_editions[i].RefreshChapters( *sys.title );
3044     }
3045     
3046     if ( stored_editions[i_default_edition].b_ordered )
3047     {
3048         /* update the duration of the segment according to the sum of all sub chapters */
3049         f_dur = stored_editions[i_default_edition].Duration() / I64C(1000);
3050         if (f_dur > 0.0)
3051             f_duration = f_dur;
3052     }
3053 }
3054
3055 void matroska_segment_t::ParseCluster( )
3056 {
3057     EbmlElement *el;
3058     EbmlMaster  *m;
3059     unsigned int i;
3060     int i_upper_level = 0;
3061
3062     /* Master elements */
3063     m = static_cast<EbmlMaster *>( cluster );
3064     m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
3065
3066     for( i = 0; i < m->ListSize(); i++ )
3067     {
3068         EbmlElement *l = (*m)[i];
3069
3070         if( MKV_IS_ID( l, KaxClusterTimecode ) )
3071         {
3072             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
3073
3074             cluster->InitTimecode( uint64( ctc ), i_timescale );
3075             break;
3076         }
3077     }
3078
3079     f_start_time = cluster->GlobalTimecode() / 1000000.0;
3080 }
3081
3082 /*****************************************************************************
3083  * InformationCreate:
3084  *****************************************************************************/
3085 void matroska_segment_t::InformationCreate( )
3086 {
3087     size_t      i_track;
3088
3089     sys.meta = vlc_meta_New();
3090
3091     if( psz_title )
3092     {
3093         vlc_meta_Add( sys.meta, VLC_META_TITLE, psz_title );
3094     }
3095     if( psz_date_utc )
3096     {
3097         vlc_meta_Add( sys.meta, VLC_META_DATE, psz_date_utc );
3098     }
3099     if( psz_segment_filename )
3100     {
3101         vlc_meta_Add( sys.meta, _("Segment filename"), psz_segment_filename );
3102     }
3103     if( psz_muxing_application )
3104     {
3105         vlc_meta_Add( sys.meta, _("Muxing application"), psz_muxing_application );
3106     }
3107     if( psz_writing_application )
3108     {
3109         vlc_meta_Add( sys.meta, _("Writing application"), psz_writing_application );
3110     }
3111
3112     for( i_track = 0; i_track < tracks.size(); i_track++ )
3113     {
3114         mkv_track_t *tk = tracks[i_track];
3115         vlc_meta_t *mtk = vlc_meta_New();
3116
3117         sys.meta->track = (vlc_meta_t**)realloc( sys.meta->track,
3118                                                     sizeof( vlc_meta_t * ) * ( sys.meta->i_track + 1 ) );
3119         sys.meta->track[sys.meta->i_track++] = mtk;
3120
3121         if( tk->fmt.psz_description )
3122         {
3123             vlc_meta_Add( sys.meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
3124         }
3125         if( tk->psz_codec_name )
3126         {
3127             vlc_meta_Add( sys.meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
3128         }
3129         if( tk->psz_codec_settings )
3130         {
3131             vlc_meta_Add( sys.meta, VLC_META_SETTING, tk->psz_codec_settings );
3132         }
3133         if( tk->psz_codec_info_url )
3134         {
3135             vlc_meta_Add( sys.meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
3136         }
3137         if( tk->psz_codec_download_url )
3138         {
3139             vlc_meta_Add( sys.meta, VLC_META_URL, tk->psz_codec_download_url );
3140         }
3141     }
3142
3143     if( i_tags_position >= 0 )
3144     {
3145         vlc_bool_t b_seekable;
3146
3147         stream_Control( sys.demuxer.s, STREAM_CAN_FASTSEEK, &b_seekable );
3148         if( b_seekable )
3149         {
3150             LoadTags( );
3151         }
3152     }
3153 }
3154
3155
3156 /*****************************************************************************
3157  * Divers
3158  *****************************************************************************/
3159
3160 void matroska_segment_t::IndexAppendCluster( KaxCluster *cluster )
3161 {
3162 #define idx index[i_index]
3163     idx.i_track       = -1;
3164     idx.i_block_number= -1;
3165     idx.i_position    = cluster->GetElementPosition();
3166     idx.i_time        = -1;
3167     idx.b_key         = VLC_TRUE;
3168
3169     i_index++;
3170     if( i_index >= i_index_max )
3171     {
3172         i_index_max += 1024;
3173         index = (mkv_index_t*)realloc( index, sizeof( mkv_index_t ) * i_index_max );
3174     }
3175 #undef idx
3176 }
3177
3178 static char * UTF8ToStr( const UTFstring &u )
3179 {
3180     int     i_src;
3181     const wchar_t *src;
3182     char *dst, *p;
3183
3184     i_src = u.length();
3185     src   = u.c_str();
3186
3187     p = dst = (char*)malloc( i_src + 1);
3188     while( i_src > 0 )
3189     {
3190         if( *src < 255 )
3191         {
3192             *p++ = (char)*src;
3193         }
3194         else
3195         {
3196             *p++ = '?';
3197         }
3198         src++;
3199         i_src--;
3200     }
3201     *p++= '\0';
3202
3203     return dst;
3204 }
3205
3206 void chapter_edition_t::RefreshChapters( input_title_t & title )
3207 {
3208     int64_t i_prev_user_time = 0;
3209     std::vector<chapter_item_t>::iterator index = chapters.begin();
3210
3211     while ( index != chapters.end() )
3212     {
3213         i_prev_user_time = (*index).RefreshChapters( b_ordered, i_prev_user_time, title );
3214         index++;
3215     }
3216 }
3217
3218 int64_t chapter_item_t::RefreshChapters( bool b_ordered, int64_t i_prev_user_time, input_title_t & title )
3219 {
3220     int64_t i_user_time = i_prev_user_time;
3221     
3222     // first the sub-chapters, and then ourself
3223     std::vector<chapter_item_t>::iterator index = sub_chapters.begin();
3224     while ( index != sub_chapters.end() )
3225     {
3226         i_user_time = (*index).RefreshChapters( b_ordered, i_user_time, title );
3227         index++;
3228     }
3229
3230     if ( b_ordered )
3231     {
3232         i_user_start_time = i_prev_user_time;
3233         if ( i_end_time != -1 && i_user_time == i_prev_user_time )
3234         {
3235             i_user_end_time = i_user_start_time - i_start_time + i_end_time;
3236         }
3237         else
3238         {
3239             i_user_end_time = i_user_time;
3240         }
3241     }
3242     else
3243     {
3244         std::sort( sub_chapters.begin(), sub_chapters.end() );
3245         i_user_start_time = i_start_time;
3246         i_user_end_time = i_end_time;
3247     }
3248
3249     if (b_display_seekpoint)
3250     {
3251         seekpoint_t *sk = vlc_seekpoint_New();
3252
3253 //        sk->i_level = i_level;
3254         sk->i_time_offset = i_start_time;
3255         sk->psz_name = strdup( psz_name.c_str() );
3256
3257         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
3258         title.i_seekpoint++;
3259         title.seekpoint = (seekpoint_t**)realloc( title.seekpoint, title.i_seekpoint * sizeof( seekpoint_t* ) );
3260         title.seekpoint[title.i_seekpoint-1] = sk;
3261     }
3262
3263     i_seekpoint_num = title.i_seekpoint;
3264
3265     return i_user_end_time;
3266 }
3267
3268 double chapter_edition_t::Duration() const
3269 {
3270     double f_result = 0.0;
3271     
3272     if ( chapters.size() )
3273     {
3274         std::vector<chapter_item_t>::const_iterator index = chapters.end();
3275         index--;
3276         f_result = (*index).i_user_end_time;
3277     }
3278     
3279     return f_result;
3280 }
3281
3282 const chapter_item_t *chapter_item_t::FindTimecode( mtime_t i_user_timecode ) const
3283 {
3284     const chapter_item_t *psz_result = NULL;
3285
3286     if (i_user_timecode >= i_user_start_time && i_user_timecode < i_user_end_time)
3287     {
3288         std::vector<chapter_item_t>::const_iterator index = sub_chapters.begin();
3289         while ( index != sub_chapters.end() && psz_result == NULL )
3290         {
3291             psz_result = (*index).FindTimecode( i_user_timecode );
3292             index++;
3293         }
3294         
3295         if ( psz_result == NULL )
3296             psz_result = this;
3297     }
3298
3299     return psz_result;
3300 }
3301
3302 const chapter_item_t *chapter_edition_t::FindTimecode( mtime_t i_user_timecode ) const
3303 {
3304     const chapter_item_t *psz_result = NULL;
3305
3306     std::vector<chapter_item_t>::const_iterator index = chapters.begin();
3307     while ( index != chapters.end() && psz_result == NULL )
3308     {
3309         psz_result = (*index).FindTimecode( i_user_timecode );
3310         index++;
3311     }
3312
3313     return psz_result;
3314 }
3315
3316 void demux_sys_t::PreloadFamily( )
3317 {
3318 /* TODO enable family handling again
3319     matroska_stream_t *p_stream = Stream();
3320     if ( p_stream )
3321     {
3322         matroska_segment_t *p_segment = p_stream->Segment();
3323         if ( p_segment )
3324         {
3325             for (size_t i=0; i<streams.size(); i++)
3326             {
3327                 streams[i]->PreloadFamily( *p_segment );
3328             }
3329         }
3330     }
3331 */
3332 }
3333
3334 void matroska_stream_t::PreloadFamily( const matroska_segment_t & of_segment )
3335 {
3336     for (size_t i=0; i<segments.size(); i++)
3337     {
3338         segments[i]->PreloadFamily( of_segment );
3339     }
3340 }
3341
3342 bool matroska_segment_t::PreloadFamily( const matroska_segment_t & of_segment )
3343 {
3344     if ( b_preloaded )
3345         return false;
3346
3347     for (size_t i=0; i<families.size(); i++)
3348     {
3349         for (size_t j=0; j<of_segment.families.size(); j++)
3350         {
3351             if ( families[i] == of_segment.families[j] )
3352                 return Preload( );
3353         }
3354     }
3355
3356     return false;
3357 }
3358
3359 // preload all the linked segments for all preloaded segments
3360 void demux_sys_t::PreloadLinked( matroska_segment_t *p_segment )
3361 {
3362     size_t i_preloaded, i;
3363
3364     delete p_current_segment;
3365     p_current_segment = new virtual_segment_t( p_segment );
3366
3367     // fill our current virtual segment with all hard linked segments
3368     do {
3369         i_preloaded = 0;
3370         for ( i=0; i< opened_segments.size(); i++ )
3371         {
3372             i_preloaded += p_current_segment->AddSegment( opened_segments[i] );
3373         }
3374     } while ( i_preloaded ); // worst case: will stop when all segments are found as linked
3375
3376     p_current_segment->Sort( );
3377
3378     p_current_segment->PreloadLinked( );
3379 }
3380
3381 void demux_sys_t::PreparePlayback( )
3382 {
3383     p_current_segment->LoadCues();
3384     f_duration = p_current_segment->Duration();
3385 }
3386
3387 bool matroska_segment_t::CompareSegmentUIDs( const matroska_segment_t * p_item_a, const matroska_segment_t * p_item_b )
3388 {
3389     EbmlBinary * p_itema = (EbmlBinary *)(&p_item_a->segment_uid);
3390     if ( *p_itema == p_item_b->prev_segment_uid )
3391         return true;
3392
3393     p_itema = (EbmlBinary *)(&p_item_a->next_segment_uid);
3394     if ( *p_itema == p_item_b->segment_uid )
3395         return true;
3396
3397     if ( *p_itema == p_item_b->prev_segment_uid )
3398         return true;
3399
3400     return false;
3401 }
3402
3403 bool matroska_segment_t::Preload( )
3404 {
3405     if ( b_preloaded )
3406         return false;
3407
3408     EbmlElement *el = NULL;
3409
3410     ep->Reset();
3411
3412     while( ( el = ep->Get() ) != NULL )
3413     {
3414         if( MKV_IS_ID( el, KaxInfo ) )
3415         {
3416             ParseInfo( el );
3417         }
3418         else if( MKV_IS_ID( el, KaxTracks ) )
3419         {
3420             ParseTracks( el );
3421         }
3422         else if( MKV_IS_ID( el, KaxSeekHead ) )
3423         {
3424             ParseSeekHead( el );
3425         }
3426         else if( MKV_IS_ID( el, KaxCues ) )
3427         {
3428             msg_Dbg( &sys.demuxer, "|   + Cues" );
3429         }
3430         else if( MKV_IS_ID( el, KaxCluster ) )
3431         {
3432             msg_Dbg( &sys.demuxer, "|   + Cluster" );
3433
3434             cluster = (KaxCluster*)el;
3435
3436             i_start_pos = cluster->GetElementPosition();
3437             ParseCluster( );
3438
3439             ep->Down();
3440             /* stop parsing the stream */
3441             break;
3442         }
3443         else if( MKV_IS_ID( el, KaxAttachments ) )
3444         {
3445             msg_Dbg( &sys.demuxer, "|   + Attachments FIXME TODO (but probably never supported)" );
3446         }
3447         else if( MKV_IS_ID( el, KaxChapters ) )
3448         {
3449             msg_Dbg( &sys.demuxer, "|   + Chapters" );
3450             ParseChapters( el );
3451         }
3452         else if( MKV_IS_ID( el, KaxTag ) )
3453         {
3454             msg_Dbg( &sys.demuxer, "|   + Tags FIXME TODO" );
3455         }
3456         else
3457         {
3458             msg_Dbg( &sys.demuxer, "|   + Unknown (%s)", typeid(*el).name() );
3459         }
3460     }
3461
3462     b_preloaded = true;
3463
3464     return true;
3465 }
3466
3467 matroska_segment_t *demux_sys_t::FindSegment( const EbmlBinary & uid ) const
3468 {
3469     for (size_t i=0; i<opened_segments.size(); i++)
3470     {
3471         if ( opened_segments[i]->segment_uid == uid )
3472             return opened_segments[i];
3473     }
3474     return NULL;
3475 }
3476
3477 void virtual_segment_t::Sort()
3478 {
3479     // keep the current segment index
3480     matroska_segment_t *p_segment = linked_segments[i_current_segment];
3481
3482     std::sort( linked_segments.begin(), linked_segments.end(), matroska_segment_t::CompareSegmentUIDs );
3483
3484     for ( i_current_segment=0; i_current_segment<linked_segments.size(); i_current_segment++)
3485         if ( linked_segments[i_current_segment] == p_segment )
3486             break;
3487 }
3488
3489 size_t virtual_segment_t::AddSegment( matroska_segment_t *p_segment )
3490 {
3491     size_t i;
3492     // check if it's not already in here
3493     for ( i=0; i<linked_segments.size(); i++ )
3494     {
3495         if ( p_segment->segment_uid == linked_segments[i]->segment_uid )
3496             return 0;
3497     }
3498
3499     // find possible mates
3500     for ( i=0; i<linked_uids.size(); i++ )
3501     {
3502         if (   p_segment->segment_uid == linked_uids[i] 
3503             || p_segment->prev_segment_uid == linked_uids[i] 
3504             || p_segment->next_segment_uid == linked_uids[i] )
3505         {
3506             linked_segments.push_back( p_segment );
3507
3508             AppendUID( p_segment->prev_segment_uid );
3509             AppendUID( p_segment->next_segment_uid );
3510
3511             return 1;
3512         }
3513     }
3514     return 0;
3515 }
3516
3517 void virtual_segment_t::PreloadLinked( )
3518 {
3519     for ( size_t i=0; i<linked_segments.size(); i++ )
3520     {
3521         linked_segments[i]->Preload( );
3522     }
3523 }
3524
3525 float virtual_segment_t::Duration() const
3526 {
3527     float f_duration;
3528     if ( linked_segments.size() == 0 )
3529         f_duration = 0.0;
3530     else {
3531         matroska_segment_t *p_last_segment = linked_segments[linked_segments.size()-1];
3532 //        p_last_segment->ParseCluster( );
3533
3534         f_duration = p_last_segment->f_start_time + p_last_segment->f_duration;
3535     }
3536     return f_duration;
3537 }
3538
3539 void virtual_segment_t::LoadCues( )
3540 {
3541     for ( size_t i=0; i<linked_segments.size(); i++ )
3542     {
3543         linked_segments[i]->LoadCues();
3544     }
3545 }
3546
3547 void virtual_segment_t::AppendUID( const EbmlBinary & UID )
3548 {
3549     if ( UID.GetBuffer() == NULL )
3550         return;
3551
3552     for (size_t i=0; i<linked_uids.size(); i++)
3553     {
3554         if ( UID == linked_uids[i] )
3555             return;
3556     }
3557     linked_uids.push_back( *(KaxSegmentUID*)(&UID) );
3558 }
3559
3560 void matroska_segment_t::Seek( mtime_t i_date, mtime_t i_time_offset )
3561 {
3562     KaxBlock    *block;
3563     int         i_track_skipping;
3564     int64_t     i_block_duration;
3565     int64_t     i_block_ref1;
3566     int64_t     i_block_ref2;
3567     size_t      i_track;
3568     int64_t     i_seek_position = i_start_pos;
3569     int64_t     i_seek_time = f_start_time * 1000;
3570
3571     if ( i_index > 0 )
3572     {
3573         int i_idx = 0;
3574
3575         for( ; i_idx < i_index; i_idx++ )
3576         {
3577             if( index[i_idx].i_time + i_time_offset > i_date )
3578             {
3579                 break;
3580             }
3581         }
3582
3583         if( i_idx > 0 )
3584         {
3585             i_idx--;
3586         }
3587
3588         i_seek_position = index[i_idx].i_position;
3589         i_seek_time = index[i_idx].i_time;
3590     }
3591
3592     msg_Dbg( &sys.demuxer, "seek got "I64Fd" (%d%%)",
3593                 i_seek_time, (int)( 100 * i_seek_position / stream_Size( sys.demuxer.s ) ) );
3594
3595     delete ep;
3596     ep = new EbmlParser( &es, segment );
3597     cluster = NULL;
3598
3599     es.I_O().setFilePointer( i_seek_position, seek_beginning );
3600
3601     sys.i_start_pts = i_date;
3602
3603     es_out_Control( sys.demuxer.out, ES_OUT_RESET_PCR );
3604
3605     /* now parse until key frame */
3606 #define tk  tracks[i_track]
3607     i_track_skipping = 0;
3608     for( i_track = 0; i_track < tracks.size(); i_track++ )
3609     {
3610         if( tk->fmt.i_cat == VIDEO_ES )
3611         {
3612             tk->b_search_keyframe = VLC_TRUE;
3613             i_track_skipping++;
3614         }
3615         es_out_Control( sys.demuxer.out, ES_OUT_SET_NEXT_DISPLAY_TIME, tk->p_es, i_date );
3616     }
3617
3618
3619     while( i_track_skipping > 0 )
3620     {
3621         if( BlockGet( &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
3622         {
3623             msg_Warn( &sys.demuxer, "cannot get block EOF?" );
3624
3625             return;
3626         }
3627
3628         for( i_track = 0; i_track < tracks.size(); i_track++ )
3629         {
3630             if( tk->i_number == block->TrackNum() )
3631             {
3632                 break;
3633             }
3634         }
3635
3636         sys.i_pts = sys.i_chapter_time + block->GlobalTimecode() / (mtime_t) 1000;
3637
3638         if( i_track < tracks.size() )
3639         {
3640             if( sys.i_pts >= sys.i_start_pts )
3641             {
3642                 BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3643                 i_track_skipping = 0;
3644             }
3645             else if( tk->fmt.i_cat == VIDEO_ES )
3646             {
3647                 if( i_block_ref1 == -1 && tk->b_search_keyframe )
3648                 {
3649                     tk->b_search_keyframe = VLC_FALSE;
3650                     i_track_skipping--;
3651                 }
3652                 if( !tk->b_search_keyframe )
3653                 {
3654                     BlockDecode( &sys.demuxer, block, sys.i_pts, 0 );
3655                 }
3656             } 
3657         }
3658
3659         delete block;
3660     }
3661 #undef tk
3662 }
3663
3664 void virtual_segment_t::Seek( demux_t & demuxer, mtime_t i_date, mtime_t i_time_offset, const chapter_item_t *psz_chapter )
3665 {
3666     demux_sys_t *p_sys = demuxer.p_sys;
3667     size_t i;
3668
3669     // find the actual time for an ordered edition
3670     if ( psz_chapter == NULL )
3671     {
3672         if ( EditionIsOrdered() )
3673         {
3674             /* 1st, we need to know in which chapter we are */
3675             psz_chapter = editions[i_current_edition].FindTimecode( i_date );
3676         }
3677     }
3678
3679     if ( psz_chapter != NULL )
3680     {
3681         psz_current_chapter = psz_chapter;
3682         p_sys->i_chapter_time = i_time_offset = psz_chapter->i_user_start_time - psz_chapter->i_start_time;
3683         demuxer.info.i_update |= INPUT_UPDATE_SEEKPOINT;
3684         demuxer.info.i_seekpoint = psz_chapter->i_seekpoint_num - 1;
3685     }
3686
3687     // find the best matching segment
3688     for ( i=0; i<linked_segments.size(); i++ )
3689     {
3690         if ( i_date < linked_segments[i]->f_start_time * 1000.0 )
3691             break;
3692     }
3693
3694     if ( i > 0 )
3695         i--;
3696
3697     if ( i_current_segment != i  )
3698     {
3699         linked_segments[i_current_segment]->UnSelect();
3700         linked_segments[i]->Select( i_date );
3701         i_current_segment = i;
3702     }
3703
3704     linked_segments[i]->Seek( i_date, i_time_offset );
3705 }