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