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