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