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