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