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