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