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