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