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