]> git.sesse.net Git - vlc/blob - modules/demux/mkv.cpp
mkv.cpp: finer granularity for seeking (useful for long files)
[vlc] / modules / demux / mkv.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2004 VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steve Lhomme <steve.lhomme@free.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
23  *****************************************************************************/
24
25 /*****************************************************************************
26  * Preamble
27  *****************************************************************************/
28 #include <stdlib.h>                                      /* malloc(), free() */
29
30 #include <vlc/vlc.h>
31
32 #ifdef HAVE_TIME_H
33 #   include <time.h>                                               /* time() */
34 #endif
35
36 #include <vlc/input.h>
37
38 #include <codecs.h>                        /* BITMAPINFOHEADER, WAVEFORMATEX */
39 #include "iso_lang.h"
40 #include "vlc_meta.h"
41
42 #include <iostream>
43 #include <cassert>
44 #include <typeinfo>
45 #include <string>
46 #include <vector>
47
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         return;
1398     }
1399     if( f_percent > 1.0 ) f_percent = 1.0;
1400
1401     delete p_sys->ep;
1402     p_sys->ep = new EbmlParser( p_sys->es, p_sys->segment );
1403     p_sys->cluster = NULL;
1404
1405     /* seek without index or without date */
1406     if( f_percent >= 0 && (config_GetInt( p_demux, "mkv-seek-percent" ) || !p_sys->b_cues || i_date < 0 ))
1407     {
1408         if (p_sys->f_duration >= 0)
1409         {
1410             i_date = f_percent * p_sys->f_duration * 1000;
1411         }
1412         else
1413         {
1414             int64_t i_pos = f_percent * stream_Size( p_demux->s );
1415
1416             msg_Dbg( p_demux, "inacurate way of seeking" );
1417             for( i_index = 0; i_index < p_sys->i_index; i_index++ )
1418             {
1419                 if( p_sys->index[i_index].i_position >= i_pos)
1420                 {
1421                     break;
1422                 }
1423             }
1424             if( i_index == p_sys->i_index )
1425             {
1426                 i_index--;
1427             }
1428
1429             i_date = p_sys->index[i_index].i_time;
1430
1431 #if 0
1432             if( p_sys->index[i_index].i_position < i_pos )
1433             {
1434                 EbmlElement *el;
1435
1436                 msg_Warn( p_demux, "searching for cluster, could take some time" );
1437
1438                 /* search a cluster */
1439                 while( ( el = p_sys->ep->Get() ) != NULL )
1440                 {
1441                     if( MKV_IS_ID( el, KaxCluster ) )
1442                     {
1443                         KaxCluster *cluster = (KaxCluster*)el;
1444
1445                         /* add it to the index */
1446                         IndexAppendCluster( p_demux, cluster );
1447
1448                         if( (int64_t)cluster->GetElementPosition() >= i_pos )
1449                         {
1450                             p_sys->cluster = cluster;
1451                             p_sys->ep->Down();
1452                             break;
1453                         }
1454                     }
1455                 }
1456             }
1457 #endif
1458         }
1459     }
1460
1461     for( ; i_index < p_sys->i_index; i_index++ )
1462     {
1463         if( p_sys->index[i_index].i_time > i_date )
1464         {
1465             break;
1466         }
1467     }
1468
1469     if( i_index > 0 )
1470     {
1471         i_index--;
1472     }
1473
1474     msg_Dbg( p_demux, "seek got "I64Fd" (%d%%)",
1475                 p_sys->index[i_index].i_time,
1476                 (int)( 100 * p_sys->index[i_index].i_position /
1477                     stream_Size( p_demux->s ) ) );
1478
1479     p_sys->in->setFilePointer( p_sys->index[i_index].i_position,
1480                                 seek_beginning );
1481
1482
1483     /* now parse until key frame */
1484 #define tk  p_sys->track[i_track]
1485     i_track_skipping = 0;
1486     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1487     {
1488         if( tk.fmt.i_cat == VIDEO_ES )
1489         {
1490             tk.b_search_keyframe = VLC_TRUE;
1491             i_track_skipping++;
1492         }
1493     }
1494
1495     p_sys->i_start_pts = i_date;
1496
1497     while( i_track_skipping > 0 )
1498     {
1499         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1500         {
1501             msg_Warn( p_demux, "cannot get block EOF?" );
1502
1503             return;
1504         }
1505
1506         p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
1507
1508         for( i_track = 0; i_track < p_sys->i_track; i_track++ )
1509         {
1510             if( tk.i_number == block->TrackNum() )
1511             {
1512                 break;
1513             }
1514         }
1515
1516         if( i_track < p_sys->i_track )
1517         {
1518             if( tk.fmt.i_cat == VIDEO_ES )
1519             {
1520                 if( i_block_ref1 == -1 && tk.b_search_keyframe )
1521                 {
1522                     tk.b_search_keyframe = VLC_FALSE;
1523                     i_track_skipping--;
1524                 }
1525                 if( !tk.b_search_keyframe )
1526                 {
1527                     BlockDecode( p_demux, block, 0, 0 );
1528 /*                    es_out_Control( p_demux->out, ES_OUT_SET_PCR, block->GlobalTimecode() / (mtime_t) 1000 );*/
1529                 }
1530             }
1531         }
1532
1533         delete block;
1534     }
1535 #undef tk
1536 }
1537
1538 /*****************************************************************************
1539  * Demux: reads and demuxes data packets
1540  *****************************************************************************
1541  * Returns -1 in case of error, 0 in case of EOF, 1 otherwise
1542  *****************************************************************************/
1543 static int Demux( demux_t *p_demux)
1544 {
1545     demux_sys_t *p_sys = p_demux->p_sys;
1546     mtime_t        i_start_pts;
1547     int            i_block_count = 0;
1548
1549     KaxBlock *block;
1550     int64_t i_block_duration;
1551     int64_t i_block_ref1;
1552     int64_t i_block_ref2;
1553
1554     i_start_pts = -1;
1555
1556     for( ;; )
1557     {
1558         if( BlockGet( p_demux, &block, &i_block_ref1, &i_block_ref2, &i_block_duration ) )
1559         {
1560             msg_Warn( p_demux, "cannot get block EOF?" );
1561
1562             return 0;
1563         }
1564
1565         p_sys->i_pts = block->GlobalTimecode() / (mtime_t) 1000;
1566
1567         if( p_sys->i_pts >= p_sys->i_start_pts  )
1568         {
1569             es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_sys->i_pts );
1570         }
1571
1572         BlockDecode( p_demux, block, p_sys->i_pts, i_block_duration );
1573
1574         delete block;
1575         i_block_count++;
1576
1577         if( p_sys->i_pts > i_start_pts + (mtime_t)100000 || i_block_count > 5 )
1578         {
1579             return 1;
1580         }
1581     }
1582 }
1583
1584
1585
1586 /*****************************************************************************
1587  * Stream managment
1588  *****************************************************************************/
1589 vlc_stream_io_callback::vlc_stream_io_callback( stream_t *s_ )
1590 {
1591     s = s_;
1592     mb_eof = VLC_FALSE;
1593 }
1594
1595 uint32 vlc_stream_io_callback::read( void *p_buffer, size_t i_size )
1596 {
1597     if( i_size <= 0 || mb_eof )
1598     {
1599         return 0;
1600     }
1601
1602     return stream_Read( s, p_buffer, i_size );
1603 }
1604 void vlc_stream_io_callback::setFilePointer(int64_t i_offset, seek_mode mode )
1605 {
1606     int64_t i_pos;
1607
1608     switch( mode )
1609     {
1610         case seek_beginning:
1611             i_pos = i_offset;
1612             break;
1613         case seek_end:
1614             i_pos = stream_Size( s ) - i_offset;
1615             break;
1616         default:
1617             i_pos= stream_Tell( s ) + i_offset;
1618             break;
1619     }
1620
1621     if( i_pos < 0 || i_pos >= stream_Size( s ) )
1622     {
1623         mb_eof = VLC_TRUE;
1624         return;
1625     }
1626
1627     mb_eof = VLC_FALSE;
1628     if( stream_Seek( s, i_pos ) )
1629     {
1630         mb_eof = VLC_TRUE;
1631     }
1632     return;
1633 }
1634 size_t vlc_stream_io_callback::write( const void *p_buffer, size_t i_size )
1635 {
1636     return 0;
1637 }
1638 uint64 vlc_stream_io_callback::getFilePointer( void )
1639 {
1640     return stream_Tell( s );
1641 }
1642 void vlc_stream_io_callback::close( void )
1643 {
1644     return;
1645 }
1646
1647
1648 /*****************************************************************************
1649  * Ebml Stream parser
1650  *****************************************************************************/
1651 EbmlParser::EbmlParser( EbmlStream *es, EbmlElement *el_start )
1652 {
1653     int i;
1654
1655     m_es = es;
1656     m_got = NULL;
1657     m_el[0] = el_start;
1658
1659     for( i = 1; i < 6; i++ )
1660     {
1661         m_el[i] = NULL;
1662     }
1663     mi_level = 1;
1664     mi_user_level = 1;
1665     mb_keep = VLC_FALSE;
1666 }
1667
1668 EbmlParser::~EbmlParser( void )
1669 {
1670     int i;
1671
1672     for( i = 1; i < mi_level; i++ )
1673     {
1674         if( !mb_keep )
1675         {
1676             delete m_el[i];
1677         }
1678         mb_keep = VLC_FALSE;
1679     }
1680 }
1681
1682 void EbmlParser::Up( void )
1683 {
1684     if( mi_user_level == mi_level )
1685     {
1686         fprintf( stderr," arrrrrrrrrrrrrg Up cannot escape itself\n" );
1687     }
1688
1689     mi_user_level--;
1690 }
1691
1692 void EbmlParser::Down( void )
1693 {
1694     mi_user_level++;
1695     mi_level++;
1696 }
1697
1698 void EbmlParser::Keep( void )
1699 {
1700     mb_keep = VLC_TRUE;
1701 }
1702
1703 int EbmlParser::GetLevel( void )
1704 {
1705     return mi_user_level;
1706 }
1707
1708 EbmlElement *EbmlParser::Get( void )
1709 {
1710     int i_ulev = 0;
1711
1712     if( mi_user_level != mi_level )
1713     {
1714         return NULL;
1715     }
1716     if( m_got )
1717     {
1718         EbmlElement *ret = m_got;
1719         m_got = NULL;
1720
1721         return ret;
1722     }
1723
1724     if( m_el[mi_level] )
1725     {
1726         m_el[mi_level]->SkipData( *m_es, m_el[mi_level]->Generic().Context );
1727         if( !mb_keep )
1728         {
1729             delete m_el[mi_level];
1730         }
1731         mb_keep = VLC_FALSE;
1732     }
1733
1734     m_el[mi_level] = m_es->FindNextElement( m_el[mi_level - 1]->Generic().Context, i_ulev, 0xFFFFFFFFL, true, 1 );
1735     if( i_ulev > 0 )
1736     {
1737         while( i_ulev > 0 )
1738         {
1739             if( mi_level == 1 )
1740             {
1741                 mi_level = 0;
1742                 return NULL;
1743             }
1744
1745             delete m_el[mi_level - 1];
1746             m_got = m_el[mi_level -1] = m_el[mi_level];
1747             m_el[mi_level] = NULL;
1748
1749             mi_level--;
1750             i_ulev--;
1751         }
1752         return NULL;
1753     }
1754     else if( m_el[mi_level] == NULL )
1755     {
1756         fprintf( stderr," m_el[mi_level] == NULL\n" );
1757     }
1758
1759     return m_el[mi_level];
1760 }
1761
1762
1763 /*****************************************************************************
1764  * Tools
1765  *  * LoadCues : load the cues element and update index
1766  *
1767  *  * LoadTags : load ... the tags element
1768  *
1769  *  * InformationCreate : create all information, load tags if present
1770  *
1771  *****************************************************************************/
1772 static void LoadCues( demux_t *p_demux )
1773 {
1774     demux_sys_t *p_sys = p_demux->p_sys;
1775     int64_t     i_sav_position = p_sys->in->getFilePointer();
1776     EbmlParser  *ep;
1777     EbmlElement *el, *cues;
1778
1779     msg_Dbg( p_demux, "loading cues" );
1780     p_sys->in->setFilePointer( p_sys->i_cues_position, seek_beginning );
1781     cues = p_sys->es->FindNextID( KaxCues::ClassInfos, 0xFFFFFFFFL);
1782
1783     if( cues == NULL )
1784     {
1785         msg_Err( p_demux, "cannot load cues (broken seekhead or file)" );
1786         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1787         return;
1788     }
1789
1790     ep = new EbmlParser( p_sys->es, cues );
1791     while( ( el = ep->Get() ) != NULL )
1792     {
1793         if( MKV_IS_ID( el, KaxCuePoint ) )
1794         {
1795 #define idx p_sys->index[p_sys->i_index]
1796
1797             idx.i_track       = -1;
1798             idx.i_block_number= -1;
1799             idx.i_position    = -1;
1800             idx.i_time        = 0;
1801             idx.b_key         = VLC_TRUE;
1802
1803             ep->Down();
1804             while( ( el = ep->Get() ) != NULL )
1805             {
1806                 if( MKV_IS_ID( el, KaxCueTime ) )
1807                 {
1808                     KaxCueTime &ctime = *(KaxCueTime*)el;
1809
1810                     ctime.ReadData( p_sys->es->I_O() );
1811
1812                     idx.i_time = uint64( ctime ) * p_sys->i_timescale / (mtime_t)1000;
1813                 }
1814                 else if( MKV_IS_ID( el, KaxCueTrackPositions ) )
1815                 {
1816                     ep->Down();
1817                     while( ( el = ep->Get() ) != NULL )
1818                     {
1819                         if( MKV_IS_ID( el, KaxCueTrack ) )
1820                         {
1821                             KaxCueTrack &ctrack = *(KaxCueTrack*)el;
1822
1823                             ctrack.ReadData( p_sys->es->I_O() );
1824                             idx.i_track = uint16( ctrack );
1825                         }
1826                         else if( MKV_IS_ID( el, KaxCueClusterPosition ) )
1827                         {
1828                             KaxCueClusterPosition &ccpos = *(KaxCueClusterPosition*)el;
1829
1830                             ccpos.ReadData( p_sys->es->I_O() );
1831                             idx.i_position = p_sys->segment->GetGlobalPosition( uint64( ccpos ) );
1832                         }
1833                         else if( MKV_IS_ID( el, KaxCueBlockNumber ) )
1834                         {
1835                             KaxCueBlockNumber &cbnum = *(KaxCueBlockNumber*)el;
1836
1837                             cbnum.ReadData( p_sys->es->I_O() );
1838                             idx.i_block_number = uint32( cbnum );
1839                         }
1840                         else
1841                         {
1842                             msg_Dbg( p_demux, "         * Unknown (%s)", typeid(*el).name() );
1843                         }
1844                     }
1845                     ep->Up();
1846                 }
1847                 else
1848                 {
1849                     msg_Dbg( p_demux, "     * Unknown (%s)", typeid(*el).name() );
1850                 }
1851             }
1852             ep->Up();
1853
1854 #if 0
1855             msg_Dbg( p_demux, " * added time="I64Fd" pos="I64Fd
1856                      " track=%d bnum=%d", idx.i_time, idx.i_position,
1857                      idx.i_track, idx.i_block_number );
1858 #endif
1859
1860             p_sys->i_index++;
1861             if( p_sys->i_index >= p_sys->i_index_max )
1862             {
1863                 p_sys->i_index_max += 1024;
1864                 p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
1865             }
1866 #undef idx
1867         }
1868         else
1869         {
1870             msg_Dbg( p_demux, " * Unknown (%s)", typeid(*el).name() );
1871         }
1872     }
1873     delete ep;
1874     delete cues;
1875
1876     p_sys->b_cues = VLC_TRUE;
1877
1878     msg_Dbg( p_demux, "loading cues done." );
1879     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1880 }
1881
1882 static void LoadTags( demux_t *p_demux )
1883 {
1884     demux_sys_t *p_sys = p_demux->p_sys;
1885     int64_t     i_sav_position = p_sys->in->getFilePointer();
1886     EbmlParser  *ep;
1887     EbmlElement *el, *tags;
1888
1889     msg_Dbg( p_demux, "loading tags" );
1890     p_sys->in->setFilePointer( p_sys->i_tags_position, seek_beginning );
1891     tags = p_sys->es->FindNextID( KaxTags::ClassInfos, 0xFFFFFFFFL);
1892
1893     if( tags == NULL )
1894     {
1895         msg_Err( p_demux, "cannot load tags (broken seekhead or file)" );
1896         p_sys->in->setFilePointer( i_sav_position, seek_beginning );
1897         return;
1898     }
1899
1900     msg_Dbg( p_demux, "Tags" );
1901     ep = new EbmlParser( p_sys->es, tags );
1902     while( ( el = ep->Get() ) != NULL )
1903     {
1904         if( MKV_IS_ID( el, KaxTag ) )
1905         {
1906             msg_Dbg( p_demux, "+ Tag" );
1907             ep->Down();
1908             while( ( el = ep->Get() ) != NULL )
1909             {
1910                 if( MKV_IS_ID( el, KaxTagTargets ) )
1911                 {
1912                     msg_Dbg( p_demux, "|   + Targets" );
1913                     ep->Down();
1914                     while( ( el = ep->Get() ) != NULL )
1915                     {
1916                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1917                     }
1918                     ep->Up();
1919                 }
1920                 else if( MKV_IS_ID( el, KaxTagGeneral ) )
1921                 {
1922                     msg_Dbg( p_demux, "|   + General" );
1923                     ep->Down();
1924                     while( ( el = ep->Get() ) != NULL )
1925                     {
1926                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1927                     }
1928                     ep->Up();
1929                 }
1930                 else if( MKV_IS_ID( el, KaxTagGenres ) )
1931                 {
1932                     msg_Dbg( p_demux, "|   + Genres" );
1933                     ep->Down();
1934                     while( ( el = ep->Get() ) != NULL )
1935                     {
1936                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1937                     }
1938                     ep->Up();
1939                 }
1940                 else if( MKV_IS_ID( el, KaxTagAudioSpecific ) )
1941                 {
1942                     msg_Dbg( p_demux, "|   + Audio Specific" );
1943                     ep->Down();
1944                     while( ( el = ep->Get() ) != NULL )
1945                     {
1946                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1947                     }
1948                     ep->Up();
1949                 }
1950                 else if( MKV_IS_ID( el, KaxTagImageSpecific ) )
1951                 {
1952                     msg_Dbg( p_demux, "|   + Images Specific" );
1953                     ep->Down();
1954                     while( ( el = ep->Get() ) != NULL )
1955                     {
1956                         msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid( *el ).name() );
1957                     }
1958                     ep->Up();
1959                 }
1960                 else if( MKV_IS_ID( el, KaxTagMultiComment ) )
1961                 {
1962                     msg_Dbg( p_demux, "|   + Multi Comment" );
1963                 }
1964                 else if( MKV_IS_ID( el, KaxTagMultiCommercial ) )
1965                 {
1966                     msg_Dbg( p_demux, "|   + Multi Commercial" );
1967                 }
1968                 else if( MKV_IS_ID( el, KaxTagMultiDate ) )
1969                 {
1970                     msg_Dbg( p_demux, "|   + Multi Date" );
1971                 }
1972                 else if( MKV_IS_ID( el, KaxTagMultiEntity ) )
1973                 {
1974                     msg_Dbg( p_demux, "|   + Multi Entity" );
1975                 }
1976                 else if( MKV_IS_ID( el, KaxTagMultiIdentifier ) )
1977                 {
1978                     msg_Dbg( p_demux, "|   + Multi Identifier" );
1979                 }
1980                 else if( MKV_IS_ID( el, KaxTagMultiLegal ) )
1981                 {
1982                     msg_Dbg( p_demux, "|   + Multi Legal" );
1983                 }
1984                 else if( MKV_IS_ID( el, KaxTagMultiTitle ) )
1985                 {
1986                     msg_Dbg( p_demux, "|   + Multi Title" );
1987                 }
1988                 else
1989                 {
1990                     msg_Dbg( p_demux, "|   + Unknown (%s)", typeid( *el ).name() );
1991                 }
1992             }
1993             ep->Up();
1994         }
1995         else
1996         {
1997             msg_Dbg( p_demux, "+ Unknown (%s)", typeid( *el ).name() );
1998         }
1999     }
2000     delete ep;
2001     delete tags;
2002
2003     msg_Dbg( p_demux, "loading tags done." );
2004     p_sys->in->setFilePointer( i_sav_position, seek_beginning );
2005 }
2006
2007 /*****************************************************************************
2008  * ParseInfo:
2009  *****************************************************************************/
2010 static void ParseSeekHead( demux_t *p_demux, EbmlElement *seekhead )
2011 {
2012     demux_sys_t *p_sys = p_demux->p_sys;
2013     EbmlElement *el;
2014     EbmlMaster  *m;
2015     unsigned int i;
2016     int i_upper_level = 0;
2017
2018     msg_Dbg( p_demux, "|   + Seek head" );
2019
2020     /* Master elements */
2021     m = static_cast<EbmlMaster *>(seekhead);
2022     m->Read( *p_sys->es, seekhead->Generic().Context, i_upper_level, el, true );
2023
2024     for( i = 0; i < m->ListSize(); i++ )
2025     {
2026         EbmlElement *l = (*m)[i];
2027
2028         if( MKV_IS_ID( l, KaxSeek ) )
2029         {
2030             EbmlMaster *sk = static_cast<EbmlMaster *>(l);
2031             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
2032             int64_t i_pos = -1;
2033
2034             unsigned int j;
2035
2036             for( j = 0; j < sk->ListSize(); j++ )
2037             {
2038                 EbmlElement *l = (*sk)[j];
2039
2040                 if( MKV_IS_ID( l, KaxSeekID ) )
2041                 {
2042                     KaxSeekID &sid = *(KaxSeekID*)l;
2043                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
2044                 }
2045                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
2046                 {
2047                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
2048                     i_pos = uint64( spos );
2049                 }
2050                 else
2051                 {
2052                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2053                 }
2054             }
2055
2056             if( i_pos >= 0 )
2057             {
2058                 if( id == KaxCues::ClassInfos.GlobalId )
2059                 {
2060                     msg_Dbg( p_demux, "|   |   |   = cues at "I64Fd, i_pos );
2061                     p_sys->i_cues_position = p_sys->segment->GetGlobalPosition( i_pos );
2062                 }
2063                 else if( id == KaxChapters::ClassInfos.GlobalId )
2064                 {
2065                     msg_Dbg( p_demux, "|   |   |   = chapters at "I64Fd, i_pos );
2066                     p_sys->i_chapters_position = p_sys->segment->GetGlobalPosition( i_pos );
2067                 }
2068                 else if( id == KaxTags::ClassInfos.GlobalId )
2069                 {
2070                     msg_Dbg( p_demux, "|   |   |   = tags at "I64Fd, i_pos );
2071                     p_sys->i_tags_position = p_sys->segment->GetGlobalPosition( i_pos );
2072                 }
2073             }
2074         }
2075         else
2076         {
2077             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2078         }
2079     }
2080 }
2081
2082 /*****************************************************************************
2083  * ParseTracks:
2084  *****************************************************************************/
2085 static void ParseTrackEntry( demux_t *p_demux, EbmlMaster *m )
2086 {
2087     demux_sys_t *p_sys = p_demux->p_sys;
2088     unsigned int i;
2089
2090     mkv_track_t *tk;
2091
2092     msg_Dbg( p_demux, "|   |   + Track Entry" );
2093
2094     p_sys->i_track++;
2095     p_sys->track = (mkv_track_t*)realloc( p_sys->track, sizeof( mkv_track_t ) * (p_sys->i_track + 1 ) );
2096
2097     /* Init the track */
2098     tk = &p_sys->track[p_sys->i_track - 1];
2099
2100     memset( tk, 0, sizeof( mkv_track_t ) );
2101
2102     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
2103     tk->fmt.psz_language = strdup("English");
2104     tk->fmt.psz_description = NULL;
2105
2106     tk->b_default = VLC_TRUE;
2107     tk->b_enabled = VLC_TRUE;
2108     tk->i_number = p_sys->i_track - 1;
2109     tk->i_extra_data = 0;
2110     tk->p_extra_data = NULL;
2111     tk->psz_codec = NULL;
2112     tk->i_default_duration = 0;
2113     tk->f_timecodescale = 1.0;
2114
2115     tk->b_inited = VLC_FALSE;
2116     tk->i_data_init = 0;
2117     tk->p_data_init = NULL;
2118
2119     tk->psz_codec_name = NULL;
2120     tk->psz_codec_settings = NULL;
2121     tk->psz_codec_info_url = NULL;
2122     tk->psz_codec_download_url = NULL;
2123     
2124     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
2125
2126     for( i = 0; i < m->ListSize(); i++ )
2127     {
2128         EbmlElement *l = (*m)[i];
2129
2130         if( MKV_IS_ID( l, KaxTrackNumber ) )
2131         {
2132             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
2133
2134             tk->i_number = uint32( tnum );
2135             msg_Dbg( p_demux, "|   |   |   + Track Number=%u", uint32( tnum ) );
2136         }
2137         else  if( MKV_IS_ID( l, KaxTrackUID ) )
2138         {
2139             KaxTrackUID &tuid = *(KaxTrackUID*)l;
2140
2141             msg_Dbg( p_demux, "|   |   |   + Track UID=%u",  uint32( tuid ) );
2142         }
2143         else  if( MKV_IS_ID( l, KaxTrackType ) )
2144         {
2145             char *psz_type;
2146             KaxTrackType &ttype = *(KaxTrackType*)l;
2147
2148             switch( uint8(ttype) )
2149             {
2150                 case track_audio:
2151                     psz_type = "audio";
2152                     tk->fmt.i_cat = AUDIO_ES;
2153                     break;
2154                 case track_video:
2155                     psz_type = "video";
2156                     tk->fmt.i_cat = VIDEO_ES;
2157                     break;
2158                 case track_subtitle:
2159                     psz_type = "subtitle";
2160                     tk->fmt.i_cat = SPU_ES;
2161                     break;
2162                 default:
2163                     psz_type = "unknown";
2164                     tk->fmt.i_cat = UNKNOWN_ES;
2165                     break;
2166             }
2167
2168             msg_Dbg( p_demux, "|   |   |   + Track Type=%s", psz_type );
2169         }
2170 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
2171 //        {
2172 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
2173
2174 //            tk->b_enabled = uint32( fenb );
2175 //            msg_Dbg( p_demux, "|   |   |   + Track Enabled=%u",
2176 //                     uint32( fenb )  );
2177 //        }
2178         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
2179         {
2180             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
2181
2182             tk->b_default = uint32( fdef );
2183             msg_Dbg( p_demux, "|   |   |   + Track Default=%u", uint32( fdef )  );
2184         }
2185         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
2186         {
2187             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
2188
2189             msg_Dbg( p_demux, "|   |   |   + Track Lacing=%d", uint32( lac ) );
2190         }
2191         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
2192         {
2193             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
2194
2195             msg_Dbg( p_demux, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
2196         }
2197         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
2198         {
2199             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
2200
2201             msg_Dbg( p_demux, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
2202         }
2203         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
2204         {
2205             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
2206
2207             tk->i_default_duration = uint64(defd);
2208             msg_Dbg( p_demux, "|   |   |   + Track Default Duration="I64Fd, uint64(defd) );
2209         }
2210         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
2211         {
2212             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
2213
2214             tk->f_timecodescale = float( ttcs );
2215             msg_Dbg( p_demux, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
2216         }
2217         else if( MKV_IS_ID( l, KaxTrackName ) )
2218         {
2219             KaxTrackName &tname = *(KaxTrackName*)l;
2220
2221             tk->fmt.psz_description = UTF8ToStr( UTFstring( tname ) );
2222             msg_Dbg( p_demux, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
2223         }
2224         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
2225         {
2226             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
2227
2228             tk->fmt.psz_language = strdup( string( lang ).c_str() );
2229             msg_Dbg( p_demux,
2230                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
2231         }
2232         else  if( MKV_IS_ID( l, KaxCodecID ) )
2233         {
2234             KaxCodecID &codecid = *(KaxCodecID*)l;
2235
2236             tk->psz_codec = strdup( string( codecid ).c_str() );
2237             msg_Dbg( p_demux, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
2238         }
2239         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
2240         {
2241             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
2242
2243             tk->i_extra_data = cpriv.GetSize();
2244             if( tk->i_extra_data > 0 )
2245             {
2246                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
2247                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
2248             }
2249             msg_Dbg( p_demux, "|   |   |   + Track CodecPrivate size="I64Fd, cpriv.GetSize() );
2250         }
2251         else if( MKV_IS_ID( l, KaxCodecName ) )
2252         {
2253             KaxCodecName &cname = *(KaxCodecName*)l;
2254
2255             tk->psz_codec_name = UTF8ToStr( UTFstring( cname ) );
2256             msg_Dbg( p_demux, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
2257         }
2258         else if( MKV_IS_ID( l, KaxContentEncodings ) )
2259         {
2260             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
2261             MkvTree( p_demux, 3, "Content Encodings" );
2262             for( unsigned int i = 0; i < cencs->ListSize(); i++ )
2263             {
2264                 EbmlElement *l2 = (*cencs)[i];
2265                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
2266                 {
2267                     MkvTree( p_demux, 4, "Content Encoding" );
2268                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
2269                     for( unsigned int i = 0; i < cenc->ListSize(); i++ )
2270                     {
2271                         EbmlElement *l3 = (*cenc)[i];
2272                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
2273                         {
2274                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
2275                             MkvTree( p_demux, 5, "Order: %i", uint32( encord ) );
2276                         }
2277                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
2278                         {
2279                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
2280                             MkvTree( p_demux, 5, "Scope: %i", uint32( encscope ) );
2281                         }
2282                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
2283                         {
2284                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
2285                             MkvTree( p_demux, 5, "Type: %i", uint32( enctype ) );
2286                         }
2287                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
2288                         {
2289                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
2290                             MkvTree( p_demux, 5, "Content Compression" );
2291                             for( unsigned int i = 0; i < compr->ListSize(); i++ )
2292                             {
2293                                 EbmlElement *l4 = (*compr)[i];
2294                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
2295                                 {
2296                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
2297                                     MkvTree( p_demux, 6, "Compression Algorithm: %i", uint32(compalg) );
2298                                     if( uint32( compalg ) == 0 )
2299                                     {
2300                                         tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
2301                                     }
2302                                 }
2303                                 else
2304                                 {
2305                                     MkvTree( p_demux, 6, "Unknown (%s)", typeid(*l4).name() );
2306                                 }
2307                             }
2308                         }
2309
2310                         else
2311                         {
2312                             MkvTree( p_demux, 5, "Unknown (%s)", typeid(*l3).name() );
2313                         }
2314                     }
2315                     
2316                 }
2317                 else
2318                 {
2319                     MkvTree( p_demux, 4, "Unknown (%s)", typeid(*l2).name() );
2320                 }
2321             }
2322                 
2323         }
2324 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
2325 //        {
2326 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
2327
2328 //            tk->psz_codec_settings = UTF8ToStr( UTFstring( cset ) );
2329 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
2330 //        }
2331 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
2332 //        {
2333 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
2334
2335 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
2336 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
2337 //        }
2338 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
2339 //        {
2340 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
2341
2342 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
2343 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
2344 //        }
2345 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
2346 //        {
2347 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
2348
2349 //            msg_Dbg( p_demux, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
2350 //        }
2351 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
2352 //        {
2353 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
2354
2355 //            msg_Dbg( p_demux, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
2356 //        }
2357         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
2358         {
2359             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
2360             unsigned int j;
2361
2362             msg_Dbg( p_demux, "|   |   |   + Track Video" );
2363             tk->f_fps = 0.0;
2364
2365             for( j = 0; j < tkv->ListSize(); j++ )
2366             {
2367                 EbmlElement *l = (*tkv)[j];
2368 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
2369 //                {
2370 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
2371
2372 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
2373 //                }
2374 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
2375 //                {
2376 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
2377
2378 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
2379 //                }
2380 //                else
2381                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
2382                 {
2383                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
2384
2385                     tk->fmt.video.i_width = uint16( vwidth );
2386                     msg_Dbg( p_demux, "|   |   |   |   + width=%d", uint16( vwidth ) );
2387                 }
2388                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
2389                 {
2390                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
2391
2392                     tk->fmt.video.i_height = uint16( vheight );
2393                     msg_Dbg( p_demux, "|   |   |   |   + height=%d", uint16( vheight ) );
2394                 }
2395                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
2396                 {
2397                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
2398
2399                     tk->fmt.video.i_visible_width = uint16( vwidth );
2400                     msg_Dbg( p_demux, "|   |   |   |   + display width=%d", uint16( vwidth ) );
2401                 }
2402                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
2403                 {
2404                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
2405
2406                     tk->fmt.video.i_visible_height = uint16( vheight );
2407                     msg_Dbg( p_demux, "|   |   |   |   + display height=%d", uint16( vheight ) );
2408                 }
2409                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
2410                 {
2411                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
2412
2413                     tk->f_fps = float( vfps );
2414                     msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( vfps ) );
2415                 }
2416 //                else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
2417 //                {
2418 //                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
2419
2420 //                    msg_Dbg( p_demux, "|   |   |   |   + Track Video Display Unit=%s",
2421 //                             uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
2422 //                }
2423 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
2424 //                {
2425 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
2426
2427 //                    msg_Dbg( p_demux, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
2428 //                }
2429 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
2430 //                {
2431 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
2432
2433 //                    msg_Dbg( p_demux, "   |   |   |   + fps=%f", float( gamma ) );
2434 //                }
2435                 else
2436                 {
2437                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2438                 }
2439             }
2440         }
2441         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
2442         {
2443             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
2444             unsigned int j;
2445
2446             msg_Dbg( p_demux, "|   |   |   + Track Audio" );
2447
2448             for( j = 0; j < tka->ListSize(); j++ )
2449             {
2450                 EbmlElement *l = (*tka)[j];
2451
2452                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
2453                 {
2454                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
2455
2456                     tk->fmt.audio.i_rate = (int)float( afreq );
2457                     msg_Dbg( p_demux, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
2458                 }
2459                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
2460                 {
2461                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
2462
2463                     tk->fmt.audio.i_channels = uint8( achan );
2464                     msg_Dbg( p_demux, "|   |   |   |   + achan=%u", uint8( achan ) );
2465                 }
2466                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
2467                 {
2468                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
2469
2470                     tk->fmt.audio.i_bitspersample = uint8( abits );
2471                     msg_Dbg( p_demux, "|   |   |   |   + abits=%u", uint8( abits ) );
2472                 }
2473                 else
2474                 {
2475                     msg_Dbg( p_demux, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
2476                 }
2477             }
2478         }
2479         else
2480         {
2481             msg_Dbg( p_demux, "|   |   |   + Unknown (%s)",
2482                      typeid(*l).name() );
2483         }
2484     }
2485 }
2486
2487 static void ParseTracks( demux_t *p_demux, EbmlElement *tracks )
2488 {
2489     demux_sys_t *p_sys = p_demux->p_sys;
2490     EbmlElement *el;
2491     EbmlMaster  *m;
2492     unsigned int i;
2493     int i_upper_level = 0;
2494
2495     msg_Dbg( p_demux, "|   + Tracks" );
2496
2497     /* Master elements */
2498     m = static_cast<EbmlMaster *>(tracks);
2499     m->Read( *p_sys->es, tracks->Generic().Context, i_upper_level, el, true );
2500
2501     for( i = 0; i < m->ListSize(); i++ )
2502     {
2503         EbmlElement *l = (*m)[i];
2504
2505         if( MKV_IS_ID( l, KaxTrackEntry ) )
2506         {
2507             ParseTrackEntry( p_demux, static_cast<EbmlMaster *>(l) );
2508         }
2509         else
2510         {
2511             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2512         }
2513     }
2514 }
2515
2516 /*****************************************************************************
2517  * ParseInfo:
2518  *****************************************************************************/
2519 static void ParseInfo( demux_t *p_demux, EbmlElement *info )
2520 {
2521     demux_sys_t *p_sys = p_demux->p_sys;
2522     EbmlElement *el;
2523     EbmlMaster  *m;
2524     unsigned int i;
2525     int i_upper_level = 0;
2526
2527     msg_Dbg( p_demux, "|   + Information" );
2528
2529     /* Master elements */
2530     m = static_cast<EbmlMaster *>(info);
2531     m->Read( *p_sys->es, info->Generic().Context, i_upper_level, el, true );
2532
2533     for( i = 0; i < m->ListSize(); i++ )
2534     {
2535         EbmlElement *l = (*m)[i];
2536
2537         if( MKV_IS_ID( l, KaxSegmentUID ) )
2538         {
2539             p_sys->segment_uid = *(new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l)));
2540
2541             msg_Dbg( p_demux, "|   |   + UID=%d", *(uint32*)p_sys->segment_uid.GetBuffer() );
2542         }
2543         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
2544         {
2545             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
2546
2547             p_sys->i_timescale = uint64(tcs);
2548
2549             msg_Dbg( p_demux, "|   |   + TimecodeScale="I64Fd,
2550                      p_sys->i_timescale );
2551         }
2552         else if( MKV_IS_ID( l, KaxDuration ) )
2553         {
2554             KaxDuration &dur = *(KaxDuration*)l;
2555
2556             p_sys->f_duration = float(dur);
2557
2558             msg_Dbg( p_demux, "|   |   + Duration=%f",
2559                      p_sys->f_duration );
2560         }
2561         else if( MKV_IS_ID( l, KaxMuxingApp ) )
2562         {
2563             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
2564
2565             p_sys->psz_muxing_application = UTF8ToStr( UTFstring( mapp ) );
2566
2567             msg_Dbg( p_demux, "|   |   + Muxing Application=%s",
2568                      p_sys->psz_muxing_application );
2569         }
2570         else if( MKV_IS_ID( l, KaxWritingApp ) )
2571         {
2572             KaxWritingApp &wapp = *(KaxWritingApp*)l;
2573
2574             p_sys->psz_writing_application = UTF8ToStr( UTFstring( wapp ) );
2575
2576             msg_Dbg( p_demux, "|   |   + Writing Application=%s",
2577                      p_sys->psz_writing_application );
2578         }
2579         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
2580         {
2581             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
2582
2583             p_sys->psz_segment_filename = UTF8ToStr( UTFstring( sfn ) );
2584
2585             msg_Dbg( p_demux, "|   |   + Segment Filename=%s",
2586                      p_sys->psz_segment_filename );
2587         }
2588         else if( MKV_IS_ID( l, KaxTitle ) )
2589         {
2590             KaxTitle &title = *(KaxTitle*)l;
2591
2592             p_sys->psz_title = UTF8ToStr( UTFstring( title ) );
2593
2594             msg_Dbg( p_demux, "|   |   + Title=%s", p_sys->psz_title );
2595         }
2596         if( MKV_IS_ID( l, KaxSegmentFamily ) )
2597         {
2598             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
2599
2600             p_sys->families.push_back(*uid);
2601
2602             msg_Dbg( p_demux, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
2603         }
2604 #if defined( HAVE_GMTIME_R ) && !defined( SYS_DARWIN )
2605         else if( MKV_IS_ID( l, KaxDateUTC ) )
2606         {
2607             KaxDateUTC &date = *(KaxDateUTC*)l;
2608             time_t i_date;
2609             struct tm tmres;
2610             char   buffer[256];
2611
2612             i_date = date.GetEpochDate();
2613             memset( buffer, 0, 256 );
2614             if( gmtime_r( &i_date, &tmres ) &&
2615                 asctime_r( &tmres, buffer ) )
2616             {
2617                 buffer[strlen( buffer)-1]= '\0';
2618                 p_sys->psz_date_utc = strdup( buffer );
2619                 msg_Dbg( p_demux, "|   |   + Date=%s", p_sys->psz_date_utc );
2620             }
2621         }
2622 #endif
2623         else
2624         {
2625             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2626         }
2627     }
2628
2629     p_sys->f_duration *= p_sys->i_timescale / 1000000.0;
2630 }
2631
2632
2633 /*****************************************************************************
2634  * ParseChapterAtom
2635  *****************************************************************************/
2636 static void ParseChapterAtom( demux_t *p_demux, int i_level, EbmlMaster *ca )
2637 {
2638     demux_sys_t *p_sys = p_demux->p_sys;
2639     unsigned int i;
2640     seekpoint_t *sk;
2641     bool b_display_seekpoint = true;
2642
2643     if( p_sys->title == NULL )
2644     {
2645         p_sys->title = vlc_input_title_New();
2646     }
2647     sk = vlc_seekpoint_New();
2648
2649     sk->i_level = i_level;
2650
2651     msg_Dbg( p_demux, "|   |   |   + ChapterAtom (level=%d)", i_level );
2652     for( i = 0; i < ca->ListSize(); i++ )
2653     {
2654         EbmlElement *l = (*ca)[i];
2655
2656         if( MKV_IS_ID( l, KaxChapterUID ) )
2657         {
2658             KaxChapterUID &uid = *(KaxChapterUID*)l;
2659             uint32_t i_uid = uint32( uid );
2660             msg_Dbg( p_demux, "|   |   |   |   + ChapterUID: 0x%x", i_uid );
2661         }
2662         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
2663         {
2664             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
2665             b_display_seekpoint = uint8( flag ) == 0;
2666
2667             msg_Dbg( p_demux, "|   |   |   |   + ChapterFlagHidden: %s", b_display_seekpoint ? "no":"yes" );
2668         }
2669         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
2670         {
2671             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
2672             sk->i_time_offset = uint64( start ) / I64C(1000);
2673
2674             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeStart: %lld", sk->i_time_offset );
2675         }
2676         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
2677         {
2678             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
2679             int64_t i_end = uint64( end );
2680
2681             msg_Dbg( p_demux, "|   |   |   |   + ChapterTimeEnd: %lld", i_end );
2682         }
2683         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
2684         {
2685             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
2686             unsigned int j;
2687
2688             msg_Dbg( p_demux, "|   |   |   |   + ChapterDisplay" );
2689             for( j = 0; j < cd->ListSize(); j++ )
2690             {
2691                 EbmlElement *l= (*cd)[j];
2692
2693                 if( MKV_IS_ID( l, KaxChapterString ) )
2694                 {
2695                     std::string psz;
2696                     int k;
2697
2698                     KaxChapterString &name =*(KaxChapterString*)l;
2699                     for (k = 0; k < i_level; k++)
2700                         psz += '+';
2701                     psz += ' ';
2702                     psz += UTF8ToStr( UTFstring( name ) );
2703                     sk->psz_name = strdup( psz.c_str() );
2704                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterString '%s'", UTF8ToStr(UTFstring(name)) );
2705                 }
2706                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
2707                 {
2708                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
2709                     const char *psz = string( lang ).c_str();
2710
2711                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
2712                 }
2713                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
2714                 {
2715                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
2716                     const char *psz = string( ct ).c_str();
2717
2718                     msg_Dbg( p_demux, "|   |   |   |   |    + ChapterCountry '%s'", psz );
2719                 }
2720             }
2721         }
2722         else if( MKV_IS_ID( l, KaxChapterAtom ) )
2723         {
2724             ParseChapterAtom( p_demux, i_level+1, static_cast<EbmlMaster *>(l) );
2725         }
2726     }
2727
2728     if (b_display_seekpoint)
2729     {
2730         // A start time of '0' is ok. A missing ChapterTime element is ok, too, because '0' is its default value.
2731         p_sys->title->i_seekpoint++;
2732         p_sys->title->seekpoint = (seekpoint_t**)realloc( p_sys->title->seekpoint, p_sys->title->i_seekpoint * sizeof( seekpoint_t* ) );
2733         p_sys->title->seekpoint[p_sys->title->i_seekpoint-1] = sk;
2734     }
2735     else
2736     {
2737         vlc_seekpoint_Delete(sk);
2738     }
2739 }
2740
2741 /*****************************************************************************
2742  * ParseChapters:
2743  *****************************************************************************/
2744 static void ParseChapters( demux_t *p_demux, EbmlElement *chapters )
2745 {
2746     demux_sys_t *p_sys = p_demux->p_sys;
2747     EbmlElement *el;
2748     EbmlMaster  *m;
2749     unsigned int i;
2750     int i_upper_level = 0;
2751
2752
2753     /* Master elements */
2754     m = static_cast<EbmlMaster *>(chapters);
2755     m->Read( *p_sys->es, chapters->Generic().Context, i_upper_level, el, true );
2756
2757     for( i = 0; i < m->ListSize(); i++ )
2758     {
2759         EbmlElement *l = (*m)[i];
2760
2761         if( MKV_IS_ID( l, KaxEditionEntry ) )
2762         {
2763             EbmlMaster *E = static_cast<EbmlMaster *>(l );
2764             unsigned int j;
2765             msg_Dbg( p_demux, "|   |   + EditionEntry" );
2766             p_sys->edition_ordered = false;
2767             for( j = 0; j < E->ListSize(); j++ )
2768             {
2769                 EbmlElement *l = (*E)[j];
2770
2771                 if( MKV_IS_ID( l, KaxChapterAtom ) )
2772                 {
2773                     ParseChapterAtom( p_demux, 0, static_cast<EbmlMaster *>(l) );
2774                 }
2775                 else if( MKV_IS_ID( l, KaxEditionUID ) )
2776                 {
2777                     p_sys->edition_uid = uint64(*static_cast<KaxEditionUID *>(l));
2778                 }
2779                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
2780                 {
2781                     p_sys->edition_ordered = uint8(*static_cast<KaxEditionFlagOrdered *>(l)) != 0;
2782                 }
2783                 else
2784                 {
2785                     msg_Dbg( p_demux, "|   |   |   + Unknown (%s)", typeid(*l).name() );
2786                 }
2787             }
2788         }
2789         else
2790         {
2791             msg_Dbg( p_demux, "|   |   + Unknown (%s)", typeid(*l).name() );
2792         }
2793     }
2794 }
2795
2796 /*****************************************************************************
2797  * InformationCreate:
2798  *****************************************************************************/
2799 static void InformationCreate( demux_t *p_demux )
2800 {
2801     demux_sys_t *p_sys = p_demux->p_sys;
2802     int         i_track;
2803
2804     p_sys->meta = vlc_meta_New();
2805
2806     if( p_sys->psz_title )
2807     {
2808         vlc_meta_Add( p_sys->meta, VLC_META_TITLE, p_sys->psz_title );
2809     }
2810     if( p_sys->psz_date_utc )
2811     {
2812         vlc_meta_Add( p_sys->meta, VLC_META_DATE, p_sys->psz_date_utc );
2813     }
2814     if( p_sys->psz_segment_filename )
2815     {
2816         vlc_meta_Add( p_sys->meta, _("Segment filename"), p_sys->psz_segment_filename );
2817     }
2818     if( p_sys->psz_muxing_application )
2819     {
2820         vlc_meta_Add( p_sys->meta, _("Muxing application"), p_sys->psz_muxing_application );
2821     }
2822     if( p_sys->psz_writing_application )
2823     {
2824         vlc_meta_Add( p_sys->meta, _("Writing application"), p_sys->psz_writing_application );
2825     }
2826
2827     for( i_track = 0; i_track < p_sys->i_track; i_track++ )
2828     {
2829         mkv_track_t *tk = &p_sys->track[i_track];
2830         vlc_meta_t *mtk = vlc_meta_New();
2831
2832         p_sys->meta->track = (vlc_meta_t**)realloc( p_sys->meta->track,
2833                                                     sizeof( vlc_meta_t * ) * ( p_sys->meta->i_track + 1 ) );
2834         p_sys->meta->track[p_sys->meta->i_track++] = mtk;
2835
2836         if( tk->fmt.psz_description )
2837         {
2838             vlc_meta_Add( p_sys->meta, VLC_META_DESCRIPTION, tk->fmt.psz_description );
2839         }
2840         if( tk->psz_codec_name )
2841         {
2842             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_NAME, tk->psz_codec_name );
2843         }
2844         if( tk->psz_codec_settings )
2845         {
2846             vlc_meta_Add( p_sys->meta, VLC_META_SETTING, tk->psz_codec_settings );
2847         }
2848         if( tk->psz_codec_info_url )
2849         {
2850             vlc_meta_Add( p_sys->meta, VLC_META_CODEC_DESCRIPTION, tk->psz_codec_info_url );
2851         }
2852         if( tk->psz_codec_download_url )
2853         {
2854             vlc_meta_Add( p_sys->meta, VLC_META_URL, tk->psz_codec_download_url );
2855         }
2856     }
2857
2858     if( p_sys->i_tags_position >= 0 )
2859     {
2860         vlc_bool_t b_seekable;
2861
2862         stream_Control( p_demux->s, STREAM_CAN_FASTSEEK, &b_seekable );
2863         if( b_seekable )
2864         {
2865             LoadTags( p_demux );
2866         }
2867     }
2868 }
2869
2870
2871 /*****************************************************************************
2872  * Divers
2873  *****************************************************************************/
2874
2875 static void IndexAppendCluster( demux_t *p_demux, KaxCluster *cluster )
2876 {
2877     demux_sys_t *p_sys = p_demux->p_sys;
2878
2879 #define idx p_sys->index[p_sys->i_index]
2880     idx.i_track       = -1;
2881     idx.i_block_number= -1;
2882     idx.i_position    = cluster->GetElementPosition();
2883     idx.i_time        = -1;
2884     idx.b_key         = VLC_TRUE;
2885
2886     p_sys->i_index++;
2887     if( p_sys->i_index >= p_sys->i_index_max )
2888     {
2889         p_sys->i_index_max += 1024;
2890         p_sys->index = (mkv_index_t*)realloc( p_sys->index, sizeof( mkv_index_t ) * p_sys->i_index_max );
2891     }
2892 #undef idx
2893 }
2894
2895 static char * UTF8ToStr( const UTFstring &u )
2896 {
2897     int     i_src;
2898     const wchar_t *src;
2899     char *dst, *p;
2900
2901     i_src = u.length();
2902     src   = u.c_str();
2903
2904     p = dst = (char*)malloc( i_src + 1);
2905     while( i_src > 0 )
2906     {
2907         if( *src < 255 )
2908         {
2909             *p++ = (char)*src;
2910         }
2911         else
2912         {
2913             *p++ = '?';
2914         }
2915         src++;
2916         i_src--;
2917     }
2918     *p++= '\0';
2919
2920     return dst;
2921 }
2922