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