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