]> git.sesse.net Git - vlc/blob - modules/demux/mkv/matroska_segment_parse.cpp
demux: mkv: ensure timescale is always valid
[vlc] / modules / demux / mkv / matroska_segment_parse.cpp
1 /*****************************************************************************
2  * matroska_segment_parse.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2010 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steve Lhomme <steve.lhomme@free.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24 #include "mkv.hpp"
25 #include "matroska_segment.hpp"
26 #include "chapters.hpp"
27 #include "demux.hpp"
28 #include "Ebml_parser.hpp"
29 #include "util.hpp"
30
31 extern "C" {
32 #include "../vobsub.h"
33 #include "../xiph.h"
34 #include "../windows_audio_commons.h"
35 }
36
37 #include <vlc_codecs.h>
38
39 /* GetFourCC helper */
40 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
41 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
42 {
43     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
44 }
45
46 static inline void fill_extra_data( mkv_track_t *p_tk, unsigned int offset )
47 {
48     if(p_tk->i_extra_data <= offset) return;
49     p_tk->fmt.i_extra = p_tk->i_extra_data - offset;
50     p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
51     if(!p_tk->fmt.p_extra) { p_tk->fmt.i_extra = 0; return; };
52     memcpy( p_tk->fmt.p_extra, p_tk->p_extra_data + offset, p_tk->fmt.i_extra );
53 }
54
55 /*****************************************************************************
56  * Some functions to manipulate memory
57  *****************************************************************************/
58 static inline char * ToUTF8( const UTFstring &u )
59 {
60     return strdup( u.GetUTF8().c_str() );
61 }
62
63 /*****************************************************************************
64  * ParseSeekHead:
65  *****************************************************************************/
66 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
67 {
68     EbmlParser  *ep;
69     EbmlElement *l;
70     bool b_seekable;
71
72     i_seekhead_count++;
73
74     stream_Control( sys.demuxer.s, STREAM_CAN_SEEK, &b_seekable );
75     if( !b_seekable )
76         return;
77
78     ep = new EbmlParser( &es, seekhead, &sys.demuxer );
79
80     while( ( l = ep->Get() ) != NULL )
81     {
82         if( MKV_IS_ID( l, KaxSeek ) )
83         {
84             EbmlId id = EBML_ID(EbmlVoid);
85             int64_t i_pos = -1;
86
87 #ifdef MKV_DEBUG
88             msg_Dbg( &sys.demuxer, "|   |   + Seek" );
89 #endif
90             ep->Down();
91             try
92             {
93                 while( ( l = ep->Get() ) != NULL )
94                 {
95                     if( unlikely( l->GetSize() >= SIZE_MAX ) )
96                     {
97                         msg_Err( &sys.demuxer,"%s too big... skipping it",  typeid(*l).name() );
98                         continue;
99                     }
100                     if( MKV_IS_ID( l, KaxSeekID ) )
101                     {
102                         KaxSeekID &sid = *(KaxSeekID*)l;
103                         sid.ReadData( es.I_O() );
104                         id = EbmlId( sid.GetBuffer(), sid.GetSize() );
105                     }
106                     else if( MKV_IS_ID( l, KaxSeekPosition ) )
107                     {
108                         KaxSeekPosition &spos = *(KaxSeekPosition*)l;
109                         spos.ReadData( es.I_O() );
110                         i_pos = (int64_t)segment->GetGlobalPosition( uint64( spos ) );
111                     }
112                     else
113                     {
114                         /* Many mkvmerge files hit this case. It seems to be a broken SeekHead */
115                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
116                     }
117                 }
118             }
119             catch(...)
120             {
121                 msg_Err( &sys.demuxer,"Error while reading %s",  typeid(*l).name() );
122             }
123             ep->Up();
124
125             if( i_pos >= 0 )
126             {
127                 if( id == EBML_ID(KaxCues) )
128                 {
129                     msg_Dbg( &sys.demuxer, "|   - cues at %"PRId64, i_pos );
130                     LoadSeekHeadItem( EBML_INFO(KaxCues), i_pos );
131                 }
132                 else if( id == EBML_ID(KaxInfo) )
133                 {
134                     msg_Dbg( &sys.demuxer, "|   - info at %"PRId64, i_pos );
135                     LoadSeekHeadItem( EBML_INFO(KaxInfo), i_pos );
136                 }
137                 else if( id == EBML_ID(KaxChapters) )
138                 {
139                     msg_Dbg( &sys.demuxer, "|   - chapters at %"PRId64, i_pos );
140                     LoadSeekHeadItem( EBML_INFO(KaxChapters), i_pos );
141                 }
142                 else if( id == EBML_ID(KaxTags) )
143                 {
144                     msg_Dbg( &sys.demuxer, "|   - tags at %"PRId64, i_pos );
145                     LoadSeekHeadItem( EBML_INFO(KaxTags), i_pos );
146                 }
147                 else if( id == EBML_ID(KaxSeekHead) )
148                 {
149                     msg_Dbg( &sys.demuxer, "|   - chained seekhead at %"PRId64, i_pos );
150                     LoadSeekHeadItem( EBML_INFO(KaxSeekHead), i_pos );
151                 }
152                 else if( id == EBML_ID(KaxTracks) )
153                 {
154                     msg_Dbg( &sys.demuxer, "|   - tracks at %"PRId64, i_pos );
155                     LoadSeekHeadItem( EBML_INFO(KaxTracks), i_pos );
156                 }
157                 else if( id == EBML_ID(KaxAttachments) )
158                 {
159                     msg_Dbg( &sys.demuxer, "|   - attachments at %"PRId64, i_pos );
160                     LoadSeekHeadItem( EBML_INFO(KaxAttachments), i_pos );
161                 }
162 #ifdef MKV_DEBUG
163                 else
164                     msg_Dbg( &sys.demuxer, "|   - unknown seekhead reference at %"PRId64, i_pos );
165 #endif
166             }
167         }
168         else
169             msg_Dbg( &sys.demuxer, "|   |   + ParseSeekHead Unknown (%s)", typeid(*l).name() );
170     }
171     delete ep;
172 }
173
174
175 /**
176  * Helper function to print the mkv parse tree
177  */
178 static void MkvTree( demux_t & demuxer, int i_level, const char *psz_format, ... )
179 {
180     va_list args;
181     if( i_level > 9 )
182     {
183         msg_Err( &demuxer, "MKV tree is too deep" );
184         return;
185     }
186     va_start( args, psz_format );
187     static const char psz_foo[] = "|   |   |   |   |   |   |   |   |   |";
188     char *psz_foo2 = (char*)malloc( i_level * 4 + 3 + strlen( psz_format ) );
189     strncpy( psz_foo2, psz_foo, 4 * i_level );
190     psz_foo2[ 4 * i_level ] = '+';
191     psz_foo2[ 4 * i_level + 1 ] = ' ';
192     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
193     msg_GenericVa( &demuxer,VLC_MSG_DBG, "mkv", psz_foo2, args );
194     free( psz_foo2 );
195     va_end( args );
196 }
197
198
199 /*****************************************************************************
200  * ParseTrackEntry:
201  *****************************************************************************/
202 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
203 {
204     bool bSupported = true;
205
206     /* Init the track */
207     mkv_track_t *tk = new mkv_track_t();
208     memset( tk, 0, sizeof( mkv_track_t ) );
209
210     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
211     tk->p_es = NULL;
212     tk->fmt.psz_language       = strdup("English");
213     tk->fmt.psz_description    = NULL;
214
215     tk->b_default              = true;
216     tk->b_enabled              = true;
217     tk->b_forced               = false;
218     tk->b_silent               = false;
219     tk->i_number               = tracks.size() - 1;
220     tk->i_extra_data           = 0;
221     tk->p_extra_data           = NULL;
222     tk->psz_codec              = NULL;
223     tk->b_dts_only             = false;
224     tk->i_default_duration     = 0;
225     tk->b_no_duration          = false;
226     tk->f_timecodescale        = 1.0;
227
228     tk->b_inited               = false;
229     tk->i_data_init            = 0;
230     tk->p_data_init            = NULL;
231
232     tk->psz_codec_name         = NULL;
233     tk->psz_codec_settings     = NULL;
234     tk->psz_codec_info_url     = NULL;
235     tk->psz_codec_download_url = NULL;
236
237     tk->i_compression_type     = MATROSKA_COMPRESSION_NONE;
238     tk->i_encoding_scope       = MATROSKA_ENCODING_SCOPE_ALL_FRAMES;
239     tk->p_compression_data     = NULL;
240
241     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
242
243     for( size_t i = 0; i < m->ListSize(); i++ )
244     {
245         EbmlElement *l = (*m)[i];
246
247         if( MKV_IS_ID( l, KaxTrackNumber ) )
248         {
249             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
250
251             tk->i_number = uint32( tnum );
252             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
253         }
254         else  if( MKV_IS_ID( l, KaxTrackUID ) )
255         {
256             KaxTrackUID &tuid = *(KaxTrackUID*)l;
257
258             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
259         }
260         else  if( MKV_IS_ID( l, KaxTrackType ) )
261         {
262             const char *psz_type;
263             KaxTrackType &ttype = *(KaxTrackType*)l;
264
265             switch( uint8(ttype) )
266             {
267                 case track_audio:
268                     psz_type = "audio";
269                     tk->fmt.i_cat = AUDIO_ES;
270                     tk->fmt.audio.i_channels = 1;
271                     tk->fmt.audio.i_rate = 8000;
272                     break;
273                 case track_video:
274                     psz_type = "video";
275                     tk->fmt.i_cat = VIDEO_ES;
276                     break;
277                 case track_subtitle:
278                     psz_type = "subtitle";
279                     tk->fmt.i_cat = SPU_ES;
280                     break;
281                 case track_buttons:
282                     psz_type = "buttons";
283                     tk->fmt.i_cat = SPU_ES;
284                     break;
285                 default:
286                     psz_type = "unknown";
287                     tk->fmt.i_cat = UNKNOWN_ES;
288                     break;
289             }
290
291             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
292         }
293         else  if( MKV_IS_ID( l, KaxTrackFlagEnabled ) ) // UNUSED
294         {
295             KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
296
297             tk->b_enabled = uint32( fenb );
298             msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u", uint32( fenb ) );
299         }
300         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
301         {
302             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
303
304             tk->b_default = uint32( fdef );
305             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef ) );
306         }
307         else  if( MKV_IS_ID( l, KaxTrackFlagForced ) ) // UNUSED
308         {
309             KaxTrackFlagForced &ffor = *(KaxTrackFlagForced*)l;
310             tk->b_forced = uint32( ffor );
311
312             msg_Dbg( &sys.demuxer, "|   |   |   + Track Forced=%u", uint32( ffor ) );
313         }
314         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) ) // UNUSED
315         {
316             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
317
318             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
319         }
320         else  if( MKV_IS_ID( l, KaxTrackMinCache ) ) // UNUSED
321         {
322             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
323
324             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
325         }
326         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) ) // UNUSED
327         {
328             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
329
330             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
331         }
332         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
333         {
334             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
335
336             tk->i_default_duration = uint64(defd);
337             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration=%"PRId64, uint64(defd) );
338         }
339         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
340         {
341             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
342
343             tk->f_timecodescale = float( ttcs );
344             if ( tk->f_timecodescale <= 0 ) tk->f_timecodescale = 1.0;
345             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
346         }
347         else  if( MKV_IS_ID( l, KaxMaxBlockAdditionID ) ) // UNUSED
348         {
349             KaxMaxBlockAdditionID &mbl = *(KaxMaxBlockAdditionID*)l;
350
351             msg_Dbg( &sys.demuxer, "|   |   |   + Track Max BlockAdditionID=%d", uint32( mbl ) );
352         }
353         else if( MKV_IS_ID( l, KaxTrackName ) )
354         {
355             KaxTrackName &tname = *(KaxTrackName*)l;
356
357             tk->fmt.psz_description = ToUTF8( UTFstring( tname ) );
358             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
359         }
360         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
361         {
362             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
363
364             free( tk->fmt.psz_language );
365             tk->fmt.psz_language = strdup( string( lang ).c_str() );
366             msg_Dbg( &sys.demuxer,
367                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
368         }
369         else  if( MKV_IS_ID( l, KaxCodecID ) )
370         {
371             KaxCodecID &codecid = *(KaxCodecID*)l;
372
373             tk->psz_codec = strdup( string( codecid ).c_str() );
374             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
375         }
376         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
377         {
378             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
379
380             tk->i_extra_data = cpriv.GetSize();
381             if( tk->i_extra_data > 0 )
382             {
383                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
384                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
385             }
386             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size=%"PRId64, cpriv.GetSize() );
387         }
388         else if( MKV_IS_ID( l, KaxCodecName ) )
389         {
390             KaxCodecName &cname = *(KaxCodecName*)l;
391
392             tk->psz_codec_name = ToUTF8( UTFstring( cname ) );
393             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
394         }
395         //AttachmentLink
396         else if( MKV_IS_ID( l, KaxCodecDecodeAll ) ) // UNUSED
397         {
398             KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
399
400             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u", uint8( cdall ) );
401         }
402         else if( MKV_IS_ID( l, KaxTrackOverlay ) ) // UNUSED
403         {
404             KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
405
406             msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u", uint32( tovr ) );
407         }
408 #if LIBMATROSKA_VERSION >= 0x010401
409         else if( MKV_IS_ID( l, KaxCodecDelay ) )
410         {
411             KaxCodecDelay &codecdelay = *(KaxCodecDelay*)l;
412             tk->i_codec_delay = uint64_t( codecdelay ) / 1000;
413             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Delay =%"PRIu64,
414                      tk->i_codec_delay );
415         }
416         else if( MKV_IS_ID( l, KaxSeekPreRoll ) )
417         {
418             KaxSeekPreRoll &spr = *(KaxSeekPreRoll*)l;
419             tk->i_seek_preroll = uint64_t(spr) / 1000;
420             msg_Dbg( &sys.demuxer, "|   |   |   + Track Seek Preroll =%"PRIu64, tk->i_seek_preroll );
421         }
422 #endif
423         else if( MKV_IS_ID( l, KaxContentEncodings ) )
424         {
425             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
426             MkvTree( sys.demuxer, 3, "Content Encodings" );
427             if ( cencs->ListSize() > 1 )
428             {
429                 msg_Err( &sys.demuxer, "Multiple Compression method not supported" );
430                 bSupported = false;
431             }
432             for( size_t j = 0; j < cencs->ListSize(); j++ )
433             {
434                 EbmlElement *l2 = (*cencs)[j];
435                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
436                 {
437                     MkvTree( sys.demuxer, 4, "Content Encoding" );
438                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
439                     for( size_t k = 0; k < cenc->ListSize(); k++ )
440                     {
441                         EbmlElement *l3 = (*cenc)[k];
442                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
443                         {
444                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
445                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
446                         }
447                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
448                         {
449                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
450                             tk->i_encoding_scope = uint32( encscope );
451                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
452                         }
453                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
454                         {
455                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
456                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
457                         }
458                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
459                         {
460                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
461                             MkvTree( sys.demuxer, 5, "Content Compression" );
462                             //Default compression type is 0 (Zlib)
463                             tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
464                             for( size_t n = 0; n < compr->ListSize(); n++ )
465                             {
466                                 EbmlElement *l4 = (*compr)[n];
467                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
468                                 {
469                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
470                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
471                                     tk->i_compression_type = uint32( compalg );
472                                     if ( ( tk->i_compression_type != MATROSKA_COMPRESSION_ZLIB ) &&
473                                          ( tk->i_compression_type != MATROSKA_COMPRESSION_HEADER ) )
474                                     {
475                                         msg_Err( &sys.demuxer, "Track Compression method %d not supported", tk->i_compression_type );
476                                         bSupported = false;
477                                     }
478                                 }
479                                 else if( MKV_IS_ID( l4, KaxContentCompSettings ) )
480                                 {
481                                     tk->p_compression_data = new KaxContentCompSettings( *(KaxContentCompSettings*)l4 );
482                                 }
483                                 else
484                                 {
485                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
486                                 }
487                             }
488                         }
489                         // ContentEncryption Unsupported
490                         else
491                         {
492                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
493                         }
494                     }
495                 }
496                 else
497                 {
498                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
499                 }
500             }
501         }
502 //        else if( MKV_IS_ID( l, KaxCodecSettings) ) DEPRECATED by matroska
503 //        {
504 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
505
506 //            tk->psz_codec_settings = ToUTF8( UTFstring( cset ) );
507 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
508 //        }
509 //        else if( MKV_IS_ID( l, KaxCodecInfoURL) ) DEPRECATED by matroska
510 //        {
511 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
512
513 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
514 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
515 //        }
516 //        else if( MKV_IS_ID( l, KaxCodecDownloadURL) ) DEPRECATED by matroska
517 //        {
518 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
519
520 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
521 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
522 //        }
523         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
524         {
525             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
526             unsigned int i_crop_right = 0, i_crop_left = 0, i_crop_top = 0, i_crop_bottom = 0;
527             unsigned int i_display_unit = 0, i_display_width = 0, i_display_height = 0;
528
529             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
530             tk->f_fps = 0.0;
531
532             tk->fmt.video.i_frame_rate_base = (unsigned int)(tk->i_default_duration / 1000);
533             tk->fmt.video.i_frame_rate = 1000000;
534
535             for( unsigned int j = 0; j < tkv->ListSize(); j++ )
536             {
537                 EbmlElement *l = (*tkv)[j];
538                 if( MKV_IS_ID( l, KaxVideoFlagInterlaced ) ) // UNUSED
539                 {
540                     KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)l;
541
542                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
543                 }
544                 else if( MKV_IS_ID( l, KaxVideoStereoMode ) ) // UNUSED
545                 {
546                     KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)l;
547
548                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
549                 }
550                 else if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
551                 {
552                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
553
554                     tk->fmt.video.i_width += uint16( vwidth );
555                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
556                 }
557                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
558                 {
559                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
560
561                     tk->fmt.video.i_height += uint16( vheight );
562                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
563                 }
564                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
565                 {
566                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
567
568                     i_display_width = uint16( vwidth );
569                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
570                 }
571                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
572                 {
573                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
574
575                     i_display_height = uint16( vheight );
576                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
577                 }
578                 else if( MKV_IS_ID( l, KaxVideoPixelCropBottom ) )
579                 {
580                     KaxVideoPixelCropBottom &cropval = *(KaxVideoPixelCropBottom*)l;
581
582                     i_crop_bottom = uint16( cropval );
583                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel bottom=%d", uint16( cropval ) );
584                 }
585                 else if( MKV_IS_ID( l, KaxVideoPixelCropTop ) )
586                 {
587                     KaxVideoPixelCropTop &cropval = *(KaxVideoPixelCropTop*)l;
588
589                     i_crop_top = uint16( cropval );
590                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel top=%d", uint16( cropval ) );
591                 }
592                 else if( MKV_IS_ID( l, KaxVideoPixelCropRight ) )
593                 {
594                     KaxVideoPixelCropRight &cropval = *(KaxVideoPixelCropRight*)l;
595
596                     i_crop_right = uint16( cropval );
597                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel right=%d", uint16( cropval ) );
598                 }
599                 else if( MKV_IS_ID( l, KaxVideoPixelCropLeft ) )
600                 {
601                     KaxVideoPixelCropLeft &cropval = *(KaxVideoPixelCropLeft*)l;
602
603                     i_crop_left = uint16( cropval );
604                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel left=%d", uint16( cropval ) );
605                 }
606                 else if( MKV_IS_ID( l, KaxVideoDisplayUnit ) )
607                 {
608                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
609
610                     i_display_unit = uint8( vdmode );
611                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
612                              i_display_unit == 0 ? "pixels" : ( i_display_unit == 1 ? "centimeters": "inches" ) );
613                 }
614                 else if( MKV_IS_ID( l, KaxVideoAspectRatio ) ) // UNUSED
615                 {
616                     KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
617
618                     msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
619                 }
620                 // ColourSpace UNUSED
621                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
622                 {
623                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
624
625                     tk->f_fps = float( vfps );
626                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
627                 }
628 //                else if( MKV_IS_ID( l, KaxVideoGamma) ) //DEPRECATED by Matroska
629 //                {
630 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
631
632 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + gamma=%f", float( gamma ) );
633 //                }
634                 else
635                 {
636                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
637                 }
638             }
639             if( i_display_height && i_display_width )
640             {
641                 tk->fmt.video.i_sar_num = i_display_width  * tk->fmt.video.i_height;
642                 tk->fmt.video.i_sar_den = i_display_height * tk->fmt.video.i_width;
643             }
644             if( i_crop_left || i_crop_right || i_crop_top || i_crop_bottom )
645             {
646                 tk->fmt.video.i_visible_width   = tk->fmt.video.i_width;
647                 tk->fmt.video.i_visible_height  = tk->fmt.video.i_height;
648                 tk->fmt.video.i_x_offset        = i_crop_left;
649                 tk->fmt.video.i_y_offset        = i_crop_top;
650                 tk->fmt.video.i_visible_width  -= i_crop_left + i_crop_right;
651                 tk->fmt.video.i_visible_height -= i_crop_top + i_crop_bottom;
652             }
653             /* FIXME: i_display_* allows you to not only set DAR, but also a zoom factor.
654                we do not support this atm */
655         }
656         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
657         {
658             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
659
660             /* Initialize default values */
661             tk->fmt.audio.i_channels = 1;
662             tk->fmt.audio.i_rate = 8000;
663
664             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
665
666             for( unsigned int j = 0; j < tka->ListSize(); j++ )
667             {
668                 EbmlElement *l = (*tka)[j];
669
670                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
671                 {
672                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
673
674                     tk->i_original_rate = tk->fmt.audio.i_rate = (int)float( afreq );
675                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
676                 }
677                 else if( MKV_IS_ID( l, KaxAudioOutputSamplingFreq ) )
678                 {
679                     KaxAudioOutputSamplingFreq &afreq = *(KaxAudioOutputSamplingFreq*)l;
680
681                     tk->fmt.audio.i_rate = (int)float( afreq );
682                     msg_Dbg( &sys.demuxer, "|   |   |   |   + aoutfreq=%d", tk->fmt.audio.i_rate );
683                 }
684                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
685                 {
686                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
687
688                     tk->fmt.audio.i_channels = uint8( achan );
689                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
690                 }
691                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
692                 {
693                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
694
695                     tk->fmt.audio.i_bitspersample = uint8( abits );
696                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
697                 }
698                 else
699                 {
700                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
701                 }
702             }
703         }
704         else
705         {
706             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
707                      typeid(*l).name() );
708         }
709     }
710
711     if ( bSupported )
712     {
713 #ifdef HAVE_ZLIB_H
714         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
715             tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_PRIVATE &&
716             tk->i_extra_data && tk->p_extra_data &&
717             zlib_decompress_extra( &sys.demuxer, tk) )
718             return;
719 #endif
720         if( TrackInit( tk ) )
721         {
722             msg_Err(&sys.demuxer, "Couldn't init track %d", tk->i_number );
723             free(tk->p_extra_data);
724             delete tk;
725             return;
726         }
727
728         tracks.push_back( tk );
729     }
730     else
731     {
732         msg_Err( &sys.demuxer, "Track Entry %d not supported", tk->i_number );
733         free(tk->p_extra_data);
734         delete tk;
735     }
736 }
737
738 /*****************************************************************************
739  * ParseTracks:
740  *****************************************************************************/
741 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
742 {
743     EbmlElement *el;
744     int i_upper_level = 0;
745
746     /* Master elements */
747     if( unlikely( tracks->GetSize() >= SIZE_MAX ) )
748     {
749         msg_Err( &sys.demuxer, "Track too big, aborting" );
750         return;
751     }
752     try
753     {
754         tracks->Read( es, EBML_CONTEXT(tracks), i_upper_level, el, true );
755     }
756     catch(...)
757     {
758         msg_Err( &sys.demuxer, "Couldn't read tracks" );
759         return;
760     }
761
762     for( size_t i = 0; i < tracks->ListSize(); i++ )
763     {
764         EbmlElement *l = (*tracks)[i];
765
766         if( MKV_IS_ID( l, KaxTrackEntry ) )
767         {
768             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
769         }
770         else
771         {
772             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
773         }
774     }
775 }
776
777 /*****************************************************************************
778  * ParseInfo:
779  *****************************************************************************/
780 void matroska_segment_c::ParseInfo( KaxInfo *info )
781 {
782     EbmlElement *el;
783     EbmlMaster  *m;
784     int i_upper_level = 0;
785
786     /* Master elements */
787     m = static_cast<EbmlMaster *>(info);
788     if( unlikely( m->GetSize() >= SIZE_MAX ) )
789     {
790         msg_Err( &sys.demuxer, "Info too big, aborting" );
791         return;
792     }
793     try
794     {
795         m->Read( es, EBML_CONTEXT(info), i_upper_level, el, true );
796     }
797     catch(...)
798     {
799         msg_Err( &sys.demuxer, "Couldn't read info" );
800         return;
801     }   
802
803     for( size_t i = 0; i < m->ListSize(); i++ )
804     {
805         EbmlElement *l = (*m)[i];
806
807         if( MKV_IS_ID( l, KaxSegmentUID ) )
808         {
809             if ( p_segment_uid == NULL )
810                 p_segment_uid = new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l));
811
812             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)p_segment_uid->GetBuffer() );
813         }
814         else if( MKV_IS_ID( l, KaxPrevUID ) )
815         {
816             if ( p_prev_segment_uid == NULL )
817             {
818                 p_prev_segment_uid = new KaxPrevUID(*static_cast<KaxPrevUID*>(l));
819                 b_ref_external_segments = true;
820             }
821
822             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)p_prev_segment_uid->GetBuffer() );
823         }
824         else if( MKV_IS_ID( l, KaxNextUID ) )
825         {
826             if ( p_next_segment_uid == NULL )
827             {
828                 p_next_segment_uid = new KaxNextUID(*static_cast<KaxNextUID*>(l));
829                 b_ref_external_segments = true;
830             }
831
832             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)p_next_segment_uid->GetBuffer() );
833         }
834         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
835         {
836             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
837
838             i_timescale = uint64(tcs);
839
840             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale=%"PRId64,
841                      i_timescale );
842         }
843         else if( MKV_IS_ID( l, KaxDuration ) )
844         {
845             KaxDuration &dur = *(KaxDuration*)l;
846
847             i_duration = mtime_t( double( dur ) );
848
849             msg_Dbg( &sys.demuxer, "|   |   + Duration=%"PRId64,
850                      i_duration );
851         }
852         else if( MKV_IS_ID( l, KaxMuxingApp ) )
853         {
854             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
855
856             psz_muxing_application = ToUTF8( UTFstring( mapp ) );
857
858             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
859                      psz_muxing_application );
860         }
861         else if( MKV_IS_ID( l, KaxWritingApp ) )
862         {
863             KaxWritingApp &wapp = *(KaxWritingApp*)l;
864
865             psz_writing_application = ToUTF8( UTFstring( wapp ) );
866
867             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
868                      psz_writing_application );
869         }
870         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
871         {
872             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
873
874             psz_segment_filename = ToUTF8( UTFstring( sfn ) );
875
876             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
877                      psz_segment_filename );
878         }
879         else if( MKV_IS_ID( l, KaxTitle ) )
880         {
881             KaxTitle &title = *(KaxTitle*)l;
882
883             psz_title = ToUTF8( UTFstring( title ) );
884
885             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
886         }
887         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
888         {
889             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
890
891             families.push_back( new KaxSegmentFamily(*uid) );
892
893             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
894         }
895         else if( MKV_IS_ID( l, KaxDateUTC ) )
896         {
897             KaxDateUTC &date = *(KaxDateUTC*)l;
898             time_t i_date;
899             struct tm tmres;
900             char   buffer[25];
901
902             i_date = date.GetEpochDate();
903             if( gmtime_r( &i_date, &tmres ) &&
904                 strftime( buffer, sizeof(buffer), "%a %b %d %H:%M:%S %Y",
905                           &tmres ) )
906             {
907                 psz_date_utc = strdup( buffer );
908                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", buffer );
909             }
910         }
911         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
912         {
913             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
914             try
915             {
916                 if( unlikely( p_trans->GetSize() >= SIZE_MAX ) )
917                 {
918                     msg_Err( &sys.demuxer, "Chapter translate too big, aborting" );
919                     continue;
920                 }
921
922                 p_trans->Read( es, EBML_CONTEXT(p_trans), i_upper_level, el, true );
923                 chapter_translation_c *p_translate = new chapter_translation_c();
924
925                 for( size_t j = 0; j < p_trans->ListSize(); j++ )
926                 {
927                     EbmlElement *l = (*p_trans)[j];
928
929                     if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
930                     {
931                         p_translate->editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
932                     }
933                     else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
934                     {
935                         p_translate->codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
936                     }
937                     else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
938                     {
939                         p_translate->p_translated = new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) );
940                     }
941                 }
942
943                 translations.push_back( p_translate );
944             }
945             catch(...)
946             {
947                 msg_Err( &sys.demuxer, "Error while reading Chapter Tranlate");
948             }
949         }
950         else
951         {
952             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
953         }
954     }
955
956     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
957     i_duration = mtime_t(f_dur);
958     if( !i_duration ) i_duration = -1;
959 }
960
961
962 /*****************************************************************************
963  * ParseChapterAtom
964  *****************************************************************************/
965 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
966 {
967     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
968     for( size_t i = 0; i < ca->ListSize(); i++ )
969     {
970         EbmlElement *l = (*ca)[i];
971
972         if( MKV_IS_ID( l, KaxChapterUID ) )
973         {
974             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
975             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %"PRIu64"", chapters.i_uid );
976         }
977         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
978         {
979             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
980             chapters.b_display_seekpoint = uint8( flag ) == 0;
981
982             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
983         }
984         else if( MKV_IS_ID( l, KaxChapterSegmentUID ) )
985         {
986             chapters.p_segment_uid = new KaxChapterSegmentUID( *static_cast<KaxChapterSegmentUID*>(l) );
987             b_ref_external_segments = true;
988             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterSegmentUID= %u", *(uint32*)chapters.p_segment_uid->GetBuffer() );
989         }
990         else if( MKV_IS_ID( l, KaxChapterSegmentEditionUID ) )
991         {
992             chapters.p_segment_edition_uid = new KaxChapterSegmentEditionUID( *static_cast<KaxChapterSegmentEditionUID*>(l) );
993             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterSegmentEditionUID= %u",
994 #if LIBMATROSKA_VERSION < 0x010300
995                      *(uint32*)chapters.p_segment_edition_uid->GetBuffer()
996 #else
997                      *(uint32*)chapters.p_segment_edition_uid
998 #endif
999                    );
1000         }
1001         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
1002         {
1003             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
1004             chapters.i_start_time = uint64( start ) / INT64_C(1000);
1005
1006             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %"PRId64"", chapters.i_start_time );
1007         }
1008         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
1009         {
1010             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
1011             chapters.i_end_time = uint64( end ) / INT64_C(1000);
1012
1013             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %"PRId64"", chapters.i_end_time );
1014         }
1015         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
1016         {
1017             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
1018
1019             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
1020             for( size_t j = 0; j < cd->ListSize(); j++ )
1021             {
1022                 EbmlElement *l= (*cd)[j];
1023
1024                 if( MKV_IS_ID( l, KaxChapterString ) )
1025                 {
1026                     KaxChapterString &name =*(KaxChapterString*)l;
1027                     for ( int k = 0; k < i_level; k++)
1028                         chapters.psz_name += '+';
1029                     chapters.psz_name += ' ';
1030                     char *psz_tmp_utf8 = ToUTF8( UTFstring( name ) );
1031                     chapters.psz_name += psz_tmp_utf8;
1032                     chapters.b_user_display = true;
1033
1034                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", psz_tmp_utf8 );
1035                     free( psz_tmp_utf8 );
1036                 }
1037                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
1038                 {
1039                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
1040                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'",
1041                              string( lang ).c_str() );
1042                 }
1043                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
1044                 {
1045                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
1046                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'",
1047                              string( ct ).c_str() );
1048                 }
1049             }
1050         }
1051         else if( MKV_IS_ID( l, KaxChapterProcess ) )
1052         {
1053             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterProcess" );
1054
1055             KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
1056             chapter_codec_cmds_c *p_ccodec = NULL;
1057
1058             for( size_t j = 0; j < cp->ListSize(); j++ )
1059             {
1060                 EbmlElement *k= (*cp)[j];
1061
1062                 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
1063                 {
1064                     KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
1065                     if ( uint32(*p_codec_id) == 0 )
1066                         p_ccodec = new matroska_script_codec_c( sys );
1067                     else if ( uint32(*p_codec_id) == 1 )
1068                         p_ccodec = new dvd_chapter_codec_c( sys );
1069                     break;
1070                 }
1071             }
1072
1073             if ( p_ccodec != NULL )
1074             {
1075                 for( size_t j = 0; j < cp->ListSize(); j++ )
1076                 {
1077                     EbmlElement *k= (*cp)[j];
1078
1079                     if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
1080                     {
1081                         KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
1082                         p_ccodec->SetPrivate( *p_private );
1083                     }
1084                     else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
1085                     {
1086                         p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
1087                     }
1088                 }
1089                 chapters.codecs.push_back( p_ccodec );
1090             }
1091         }
1092         else if( MKV_IS_ID( l, KaxChapterAtom ) )
1093         {
1094             chapter_item_c *new_sub_chapter = new chapter_item_c();
1095             ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
1096             new_sub_chapter->p_parent = &chapters;
1097             chapters.sub_chapters.push_back( new_sub_chapter );
1098         }
1099     }
1100 }
1101
1102 /*****************************************************************************
1103  * ParseAttachments:
1104  *****************************************************************************/
1105 void matroska_segment_c::ParseAttachments( KaxAttachments *attachments )
1106 {
1107     EbmlElement *el;
1108     int i_upper_level = 0;
1109
1110     if( unlikely( attachments->GetSize() >= SIZE_MAX ) )
1111     {
1112         msg_Err( &sys.demuxer, "Attachments too big, aborting" );
1113         return;
1114     }
1115     try
1116     {
1117         attachments->Read( es, EBML_CONTEXT(attachments), i_upper_level, el, true );
1118     }
1119     catch(...)
1120     {
1121         msg_Err( &sys.demuxer, "Error while reading attachments" );
1122         return;
1123     }
1124
1125     KaxAttached *attachedFile = FindChild<KaxAttached>( *attachments );
1126
1127     while( attachedFile && ( attachedFile->GetSize() > 0 ) )
1128     {
1129         KaxFileData  &img_data     = GetChild<KaxFileData>( *attachedFile );
1130         char *psz_tmp_utf8 =  ToUTF8( UTFstring( GetChild<KaxFileName>( *attachedFile ) ) );
1131         std::string attached_filename(psz_tmp_utf8);
1132         free(psz_tmp_utf8);
1133         attachment_c *new_attachment = new attachment_c( attached_filename,
1134                                                          GetChild<KaxMimeType>( *attachedFile ),
1135                                                          img_data.GetSize() );
1136
1137         msg_Dbg( &sys.demuxer, "|   |   - %s (%s)", new_attachment->fileName(), new_attachment->mimeType() );
1138
1139         if( new_attachment->init() )
1140         {
1141             memcpy( new_attachment->p_data, img_data.GetBuffer(), img_data.GetSize() );
1142             sys.stored_attachments.push_back( new_attachment );
1143             if( !strncmp( new_attachment->mimeType(), "image/", 6 ) )
1144             {
1145                 char *psz_url;
1146                 if( asprintf( &psz_url, "attachment://%s",
1147                               new_attachment->fileName() ) == -1 )
1148                     continue;
1149                 if( !sys.meta )
1150                     sys.meta = vlc_meta_New();
1151                 vlc_meta_SetArtURL( sys.meta, psz_url );
1152                 free( psz_url );
1153             }
1154         }
1155         else
1156         {
1157             delete new_attachment;
1158         }
1159
1160         attachedFile = &GetNextChild<KaxAttached>( *attachments, *attachedFile );
1161     }
1162 }
1163
1164 /*****************************************************************************
1165  * ParseChapters:
1166  *****************************************************************************/
1167 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
1168 {
1169     EbmlElement *el;
1170     int i_upper_level = 0;
1171
1172     /* Master elements */
1173     if( unlikely( chapters->GetSize() >= SIZE_MAX ) )
1174     {
1175         msg_Err( &sys.demuxer, "Chapters too big, aborting" );
1176         return;
1177     }
1178     try
1179     {
1180         chapters->Read( es, EBML_CONTEXT(chapters), i_upper_level, el, true );
1181     }
1182     catch(...)
1183     {
1184         msg_Err( &sys.demuxer, "Error while reading chapters" );
1185         return;
1186     }
1187
1188     for( size_t i = 0; i < chapters->ListSize(); i++ )
1189     {
1190         EbmlElement *l = (*chapters)[i];
1191
1192         if( MKV_IS_ID( l, KaxEditionEntry ) )
1193         {
1194             chapter_edition_c *p_edition = new chapter_edition_c();
1195
1196             EbmlMaster *E = static_cast<EbmlMaster *>(l );
1197             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
1198             for( size_t j = 0; j < E->ListSize(); j++ )
1199             {
1200                 EbmlElement *l = (*E)[j];
1201
1202                 if( MKV_IS_ID( l, KaxChapterAtom ) )
1203                 {
1204                     chapter_item_c *new_sub_chapter = new chapter_item_c();
1205                     ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
1206                     p_edition->sub_chapters.push_back( new_sub_chapter );
1207                 }
1208                 else if( MKV_IS_ID( l, KaxEditionUID ) )
1209                 {
1210                     p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
1211                 }
1212                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
1213                 {
1214                     p_edition->b_ordered = var_InheritBool( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
1215                 }
1216                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
1217                 {
1218                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
1219                         i_default_edition = stored_editions.size();
1220                 }
1221                 else if( MKV_IS_ID( l, KaxEditionFlagHidden ) )
1222                 {
1223                     // FIXME to implement
1224                 }
1225                 else
1226                 {
1227                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
1228                 }
1229             }
1230             stored_editions.push_back( p_edition );
1231         }
1232         else
1233         {
1234             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
1235         }
1236     }
1237 }
1238
1239 void matroska_segment_c::ParseCluster( bool b_update_start_time )
1240 {
1241     EbmlElement *el;
1242     EbmlMaster  *m;
1243     int i_upper_level = 0;
1244
1245     /* Master elements */
1246     m = static_cast<EbmlMaster *>( cluster );
1247     if( unlikely( m->GetSize() >= SIZE_MAX ) )
1248     {
1249         msg_Err( &sys.demuxer, "Cluster too big, aborting" );
1250         return;
1251     }
1252     try
1253     {
1254         m->Read( es, EBML_CONTEXT(cluster), i_upper_level, el, true );
1255     }
1256     catch(...)
1257     {
1258         msg_Err( &sys.demuxer, "Error while reading cluster" );
1259         return;
1260     }
1261
1262     for( unsigned int i = 0; i < m->ListSize(); i++ )
1263     {
1264         EbmlElement *l = (*m)[i];
1265
1266         if( MKV_IS_ID( l, KaxClusterTimecode ) )
1267         {
1268             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
1269
1270             cluster->InitTimecode( uint64( ctc ), i_timescale );
1271             break;
1272         }
1273     }
1274
1275     if( b_update_start_time )
1276         i_start_time = cluster->GlobalTimecode() / 1000;
1277 }
1278
1279
1280 int32_t matroska_segment_c::TrackInit( mkv_track_t * p_tk )
1281 {
1282     es_format_t *p_fmt = &p_tk->fmt;
1283
1284     if( p_tk->psz_codec == NULL )
1285     {
1286         msg_Err( &sys.demuxer, "Empty codec id" );
1287         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1288         return 0;
1289     }
1290
1291     if( !strcmp( p_tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1292     {
1293         if( p_tk->i_extra_data < (int)sizeof( VLC_BITMAPINFOHEADER ) )
1294         {
1295             msg_Err( &sys.demuxer, "missing/invalid VLC_BITMAPINFOHEADER" );
1296             p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1297         }
1298         else
1299         {
1300             VLC_BITMAPINFOHEADER *p_bih = (VLC_BITMAPINFOHEADER*)p_tk->p_extra_data;
1301
1302             p_tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1303             p_tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1304             p_tk->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
1305
1306             p_tk->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( VLC_BITMAPINFOHEADER );
1307             if( p_tk->fmt.i_extra > 0 )
1308             {
1309                 /* Very unlikely yet possible: bug #5659*/
1310                 size_t maxlen = p_tk->i_extra_data - sizeof( VLC_BITMAPINFOHEADER );
1311                 p_tk->fmt.i_extra = ( (unsigned)p_tk->fmt.i_extra < maxlen )?
1312                     p_tk->fmt.i_extra : maxlen;
1313
1314                 p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1315                 memcpy( p_tk->fmt.p_extra, &p_bih[1], p_tk->fmt.i_extra );
1316             }
1317         }
1318         p_tk->b_dts_only = true;
1319     }
1320     else if( !strcmp( p_tk->psz_codec, "V_MPEG1" ) ||
1321              !strcmp( p_tk->psz_codec, "V_MPEG2" ) )
1322     {
1323         p_tk->fmt.i_codec = VLC_CODEC_MPGV;
1324         if( p_tk->i_extra_data )
1325             fill_extra_data( p_tk, 0 );
1326     }
1327     else if( !strncmp( p_tk->psz_codec, "V_THEORA", 8 ) )
1328     {
1329         p_tk->fmt.i_codec = VLC_CODEC_THEORA;
1330         fill_extra_data( p_tk, 0 );
1331         p_tk->b_pts_only = true;
1332     }
1333     else if( !strncmp( p_tk->psz_codec, "V_REAL/RV", 9 ) )
1334     {
1335         uint8_t *p = p_tk->p_extra_data;
1336
1337         if( !strcmp( p_tk->psz_codec, "V_REAL/RV10" ) )
1338             p_fmt->i_codec = VLC_CODEC_RV10;
1339         else if( !strcmp( p_tk->psz_codec, "V_REAL/RV20" ) )
1340             p_fmt->i_codec = VLC_CODEC_RV20;
1341         else if( !strcmp( p_tk->psz_codec, "V_REAL/RV30" ) )
1342             p_fmt->i_codec = VLC_CODEC_RV30;
1343         else if( !strcmp( p_tk->psz_codec, "V_REAL/RV40" ) )
1344             p_fmt->i_codec = VLC_CODEC_RV40;
1345
1346         /* Extract the framerate from the header */
1347         if( p_tk->i_extra_data >= 26 &&
1348             p[4] == 'V' && p[5] == 'I' && p[6] == 'D' && p[7] == 'O' &&
1349             p[8] == 'R' && p[9] == 'V' &&
1350             (p[10] == '3' || p[10] == '4') && p[11] == '0' )
1351         {
1352             p_tk->fmt.video.i_frame_rate =
1353                 p[22] << 24 | p[23] << 16 | p[24] << 8 | p[25] << 0;
1354             p_tk->fmt.video.i_frame_rate_base = 65536;
1355         }
1356
1357         fill_extra_data( p_tk, 26 );
1358         p_tk->b_dts_only = true;
1359     }
1360     else if( !strncmp( p_tk->psz_codec, "V_DIRAC", 7 ) )
1361     {
1362         p_tk->fmt.i_codec = VLC_CODEC_DIRAC;
1363     }
1364     else if( !strncmp( p_tk->psz_codec, "V_VP8", 5 ) )
1365     {
1366         p_tk->fmt.i_codec = VLC_CODEC_VP8;
1367         p_tk->b_pts_only = true;
1368     }
1369     else if( !strncmp( p_tk->psz_codec, "V_VP9", 5 ) )
1370     {
1371         p_tk->fmt.i_codec = VLC_CODEC_VP9;
1372         fill_extra_data( p_tk, 0 );
1373     }
1374     else if( !strncmp( p_tk->psz_codec, "V_MPEG4", 7 ) )
1375     {
1376         if( !strcmp( p_tk->psz_codec, "V_MPEG4/MS/V3" ) )
1377         {
1378             p_tk->fmt.i_codec = VLC_CODEC_DIV3;
1379         }
1380         else if( !strncmp( p_tk->psz_codec, "V_MPEG4/ISO", 11 ) )
1381         {
1382             /* A MPEG 4 codec, SP, ASP, AP or AVC */
1383             if( !strcmp( p_tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1384                 p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1385             else
1386                 p_tk->fmt.i_codec = VLC_CODEC_MP4V;
1387             fill_extra_data( p_tk, 0 );
1388         }
1389     }
1390     else if( !strncmp( p_tk->psz_codec, "V_MPEGH/ISO/HEVC", 16) )
1391     {
1392         p_tk->fmt.i_codec = VLC_CODEC_HEVC;
1393         fill_extra_data( p_tk, 0 );
1394     } 
1395     else if( !strcmp( p_tk->psz_codec, "V_QUICKTIME" ) )
1396     {
1397         MP4_Box_t *p_box = (MP4_Box_t*)xmalloc( sizeof( MP4_Box_t ) );
1398         stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1399                                                    p_tk->p_extra_data,
1400                                                    p_tk->i_extra_data,
1401                                                    true );
1402         if( MP4_ReadBoxCommon( p_mp4_stream, p_box ) &&
1403             MP4_ReadBox_sample_vide( p_mp4_stream, p_box ) )
1404         {
1405             p_tk->fmt.i_codec = p_box->i_type;
1406             p_tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1407             p_tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1408             p_tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1409             p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1410             memcpy( p_tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, p_tk->fmt.i_extra );
1411             MP4_FreeBox_sample_vide( p_box );
1412         }
1413         else
1414         {
1415             free( p_box );
1416         }
1417         stream_Delete( p_mp4_stream );
1418     }
1419     else if( !strcmp( p_tk->psz_codec, "V_MJPEG" ) )
1420     {
1421         p_tk->fmt.i_codec = VLC_CODEC_MJPG;
1422     }
1423     else if( !strcmp( p_tk->psz_codec, "A_MS/ACM" ) )
1424     {
1425         if( p_tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1426         {
1427             msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1428             p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1429         }
1430         else
1431         {
1432             WAVEFORMATEX *p_wf = (WAVEFORMATEX*)p_tk->p_extra_data;
1433
1434             p_tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
1435             p_tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1436             p_tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1437             p_tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1438             p_tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1439
1440             p_tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
1441             if( p_tk->fmt.i_extra > 0 )
1442             {
1443                 p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1444                 if( p_tk->fmt.p_extra )
1445                     memcpy( p_tk->fmt.p_extra, &p_wf[1], p_tk->fmt.i_extra );
1446                 else
1447                     p_tk->fmt.i_extra = 0;
1448             }
1449
1450             if( p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE && 
1451                 p_tk->i_extra_data >= sizeof(WAVEFORMATEXTENSIBLE) )
1452             {
1453                 WAVEFORMATEXTENSIBLE * p_wext = (WAVEFORMATEXTENSIBLE*) p_wf;
1454                 sf_tag_to_fourcc( &p_wext->SubFormat,  &p_tk->fmt.i_codec, NULL);
1455                 /* FIXME should we use Samples */
1456
1457                 if( p_tk->fmt.audio.i_channels > 2 &&
1458                     ( p_tk->fmt.i_codec != VLC_FOURCC( 'u', 'n', 'd', 'f' ) ) ) 
1459                 {
1460                     uint32_t wfextcm = GetDWLE( &p_wext->dwChannelMask );
1461                     int match;
1462                     unsigned i_channel_mask = getChannelMask( &wfextcm,
1463                                                               p_tk->fmt.audio.i_channels,
1464                                                               &match );
1465                     p_tk->fmt.i_codec = vlc_fourcc_GetCodecAudio( p_tk->fmt.i_codec,
1466                                                                   p_tk->fmt.audio.i_bitspersample );
1467                     if( i_channel_mask )
1468                     {
1469                         p_tk->i_chans_to_reorder = aout_CheckChannelReorder(
1470                             pi_channels_aout, NULL,
1471                             i_channel_mask,
1472                             p_tk->pi_chan_table );
1473
1474                         p_tk->fmt.audio.i_physical_channels =
1475                         p_tk->fmt.audio.i_original_channels = i_channel_mask;
1476                     }
1477                 }
1478             }
1479             else
1480                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &p_tk->fmt.i_codec, NULL );
1481
1482             if( p_tk->fmt.i_codec == VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
1483                 msg_Err( &sys.demuxer, "Unrecognized wf tag: 0x%x", GetWLE( &p_wf->wFormatTag ) );
1484         }
1485     }
1486     else if( !strcmp( p_tk->psz_codec, "A_MPEG/L3" ) ||
1487              !strcmp( p_tk->psz_codec, "A_MPEG/L2" ) ||
1488              !strcmp( p_tk->psz_codec, "A_MPEG/L1" ) )
1489     {
1490         p_tk->fmt.i_codec = VLC_CODEC_MPGA;
1491     }
1492     else if( !strcmp( p_tk->psz_codec, "A_AC3" ) )
1493     {
1494         p_tk->fmt.i_codec = VLC_CODEC_A52;
1495     }
1496     else if( !strcmp( p_tk->psz_codec, "A_EAC3" ) )
1497     {
1498         p_tk->fmt.i_codec = VLC_CODEC_EAC3;
1499     }
1500     else if( !strcmp( p_tk->psz_codec, "A_DTS" ) )
1501     {
1502         p_tk->fmt.i_codec = VLC_CODEC_DTS;
1503     }
1504     else if( !strcmp( p_tk->psz_codec, "A_MLP" ) )
1505     {
1506         p_tk->fmt.i_codec = VLC_CODEC_MLP;
1507     }
1508     else if( !strcmp( p_tk->psz_codec, "A_TRUEHD" ) )
1509     {
1510         /* FIXME when more samples arrive */
1511         p_tk->fmt.i_codec = VLC_CODEC_TRUEHD;
1512         p_fmt->b_packetized = false;
1513     }
1514     else if( !strcmp( p_tk->psz_codec, "A_FLAC" ) )
1515     {
1516         p_tk->fmt.i_codec = VLC_CODEC_FLAC;
1517         fill_extra_data( p_tk, 8 );
1518     }
1519     else if( !strcmp( p_tk->psz_codec, "A_VORBIS" ) )
1520     {
1521         p_tk->fmt.i_codec = VLC_CODEC_VORBIS;
1522         fill_extra_data( p_tk, 0 );
1523     }
1524     else if( !strncmp( p_tk->psz_codec, "A_OPUS", 6 ) )
1525     {
1526         p_tk->fmt.i_codec = VLC_CODEC_OPUS;
1527         if( !p_tk->fmt.audio.i_rate )
1528         {
1529             msg_Err( &sys.demuxer,"No sampling rate, defaulting to 48kHz");
1530             p_tk->fmt.audio.i_rate = 48000;
1531         }
1532         const uint8_t tags[16] = {'O','p','u','s','T','a','g','s',
1533                                    0, 0, 0, 0, 0, 0, 0, 0};
1534         unsigned ps[2] = { p_tk->i_extra_data, 16 };
1535         const void *pkt[2] = { (const void *)p_tk->p_extra_data,
1536                               (const void *) tags };
1537
1538         if( xiph_PackHeaders( &p_tk->fmt.i_extra,
1539                               &p_tk->fmt.p_extra,
1540                               ps, pkt, 2 ) )
1541             msg_Err( &sys.demuxer, "Couldn't pack OPUS headers");
1542
1543     }
1544     else if( !strncmp( p_tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1545              !strncmp( p_tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1546     {
1547         int i_profile, i_srate, sbr = 0;
1548         static const unsigned int i_sample_rates[] =
1549         {
1550             96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1551             16000, 12000, 11025,  8000,  7350,     0,     0,     0
1552         };
1553
1554         p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1555         /* create data for faad (MP4DecSpecificDescrTag)*/
1556
1557         if( !strcmp( &p_tk->psz_codec[12], "MAIN" ) )
1558         {
1559             i_profile = 0;
1560         }
1561         else if( !strcmp( &p_tk->psz_codec[12], "LC" ) )
1562         {
1563             i_profile = 1;
1564         }
1565         else if( !strcmp( &p_tk->psz_codec[12], "SSR" ) )
1566         {
1567             i_profile = 2;
1568         }
1569         else if( !strcmp( &p_tk->psz_codec[12], "LC/SBR" ) )
1570         {
1571             i_profile = 1;
1572             sbr = 1;
1573         }
1574         else
1575         {
1576             i_profile = 3;
1577         }
1578
1579         for( i_srate = 0; i_srate < 13; i_srate++ )
1580         {
1581             if( i_sample_rates[i_srate] == p_tk->i_original_rate )
1582             {
1583                 break;
1584             }
1585         }
1586         msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1587
1588         p_tk->fmt.i_extra = sbr ? 5 : 2;
1589         p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1590         ((uint8_t*)p_tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1591         ((uint8_t*)p_tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (p_tk->fmt.audio.i_channels << 3);
1592         if (sbr != 0)
1593         {
1594             int syncExtensionType = 0x2B7;
1595             int iDSRI;
1596             for (iDSRI=0; iDSRI<13; iDSRI++)
1597                 if( i_sample_rates[iDSRI] == p_tk->fmt.audio.i_rate )
1598                     break;
1599             ((uint8_t*)p_tk->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
1600             ((uint8_t*)p_tk->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
1601             ((uint8_t*)p_tk->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
1602         }
1603     }
1604     else if( !strcmp( p_tk->psz_codec, "A_AAC" ) )
1605     {
1606         p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1607         fill_extra_data( p_tk, 0 );
1608     }
1609     else if( !strcmp( p_tk->psz_codec, "A_ALAC" ) )
1610     {
1611         p_tk->fmt.i_codec =  VLC_CODEC_ALAC;
1612         fill_extra_data( p_tk, 0 );
1613     }
1614     else if( !strcmp( p_tk->psz_codec, "A_WAVPACK4" ) )
1615     {
1616         p_tk->fmt.i_codec = VLC_CODEC_WAVPACK;
1617         fill_extra_data( p_tk, 0 );
1618     }
1619     else if( !strcmp( p_tk->psz_codec, "A_TTA1" ) )
1620     {
1621         p_fmt->i_codec = VLC_CODEC_TTA;
1622         if( p_tk->i_extra_data > 0 )
1623         {
1624             fill_extra_data( p_tk, 0 );
1625         }
1626         else
1627         {
1628             p_fmt->i_extra = 30;
1629             p_fmt->p_extra = xmalloc( p_fmt->i_extra );
1630             uint8_t *p_extra = (uint8_t*)p_fmt->p_extra;
1631             memcpy( &p_extra[ 0], "TTA1", 4 );
1632             SetWLE( &p_extra[ 4], 1 );
1633             SetWLE( &p_extra[ 6], p_fmt->audio.i_channels );
1634             SetWLE( &p_extra[ 8], p_fmt->audio.i_bitspersample );
1635             SetDWLE( &p_extra[10], p_fmt->audio.i_rate );
1636             SetDWLE( &p_extra[14], 0xffffffff );
1637             memset( &p_extra[18], 0, 30  - 18 );
1638         }
1639     }
1640     else if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) ||
1641              !strcmp( p_tk->psz_codec, "A_PCM/INT/LIT" ) ||
1642              !strcmp( p_tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1643     {
1644         if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) )
1645         {
1646             p_tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1647         }
1648         else
1649         {
1650             p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1651         }
1652         p_tk->fmt.audio.i_blockalign = ( p_tk->fmt.audio.i_bitspersample + 7 ) / 8 * p_tk->fmt.audio.i_channels;
1653     }
1654     else if( !strncmp( p_tk->psz_codec, "A_REAL/", 7 ) )
1655     {
1656         if( !strcmp( p_tk->psz_codec, "A_REAL/14_4" ) )
1657         {
1658             p_fmt->i_codec = VLC_CODEC_RA_144;
1659             p_fmt->audio.i_channels = 1;
1660             p_fmt->audio.i_rate = 8000;
1661             p_fmt->audio.i_blockalign = 0x14;
1662         }
1663         else if( p_tk->i_extra_data > 28 )
1664         {
1665             uint8_t *p = p_tk->p_extra_data;
1666             if( memcmp( p, ".ra", 3 ) ) {
1667                 msg_Err( &sys.demuxer, "Invalid Real ExtraData 0x%4.4s", (char *)p );
1668                 p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1669             }
1670             else
1671             {
1672                 real_audio_private * priv = (real_audio_private*) p_tk->p_extra_data;
1673                 if( !strcmp( p_tk->psz_codec, "A_REAL/COOK" ) )
1674                 {
1675                     p_tk->fmt.i_codec = VLC_CODEC_COOK;
1676                     p_tk->fmt.audio.i_blockalign = hton16(priv->sub_packet_size);
1677                 }
1678                 else if( !strcmp( p_tk->psz_codec, "A_REAL/ATRC" ) )
1679                     p_tk->fmt.i_codec = VLC_CODEC_ATRAC3;
1680                 else if( !strcmp( p_tk->psz_codec, "A_REAL/28_8" ) )
1681                     p_tk->fmt.i_codec = VLC_CODEC_RA_288;
1682                 /* FIXME RALF and SIPR */
1683                 uint16_t version = (uint16_t) hton16(priv->version);
1684                 p_tk->p_sys =
1685                     new Cook_PrivateTrackData( hton16(priv->sub_packet_h),
1686                                                hton16(priv->frame_size),
1687                                                hton16(priv->sub_packet_size));
1688                 if( unlikely( !p_tk->p_sys ) )
1689                     return 1;
1690
1691                 if( unlikely( p_tk->p_sys->Init() ) )
1692                     return 1;
1693
1694                 if( version == 4 )
1695                 {
1696                     real_audio_private_v4 * v4 = (real_audio_private_v4*) priv;
1697                     p_tk->fmt.audio.i_channels = hton16(v4->channels);
1698                     p_tk->fmt.audio.i_bitspersample = hton16(v4->sample_size);
1699                     p_tk->fmt.audio.i_rate = hton16(v4->sample_rate);
1700                 }
1701                 else if( version == 5 )
1702                 {
1703                     real_audio_private_v5 * v5 = (real_audio_private_v5*) priv;
1704                     p_tk->fmt.audio.i_channels = hton16(v5->channels);
1705                     p_tk->fmt.audio.i_bitspersample = hton16(v5->sample_size);
1706                     p_tk->fmt.audio.i_rate = hton16(v5->sample_rate);
1707                 }
1708                 msg_Dbg(&sys.demuxer, "%d channels %d bits %d Hz",p_tk->fmt.audio.i_channels, p_tk->fmt.audio.i_bitspersample, p_tk->fmt.audio.i_rate);
1709
1710                 fill_extra_data( p_tk, p_tk->fmt.i_codec == VLC_CODEC_RA_288 ? 0 : 78);
1711             }
1712         }
1713     }
1714     else if( !strcmp( p_tk->psz_codec, "S_KATE" ) )
1715     {
1716         p_tk->fmt.i_codec = VLC_CODEC_KATE;
1717         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1718
1719         fill_extra_data( p_tk, 0 );
1720     }
1721     else if( !strcmp( p_tk->psz_codec, "S_TEXT/ASCII" ) )
1722     {
1723         p_fmt->i_codec = VLC_CODEC_SUBT;
1724         p_fmt->subs.psz_encoding = strdup( "ASCII" );
1725     }
1726     else if( !strcmp( p_tk->psz_codec, "S_TEXT/UTF8" ) )
1727     {
1728         p_tk->fmt.i_codec = VLC_CODEC_SUBT;
1729         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1730     }
1731     else if( !strcmp( p_tk->psz_codec, "S_TEXT/USF" ) )
1732     {
1733         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
1734         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1735         if( p_tk->i_extra_data )
1736             fill_extra_data( p_tk, 0 );
1737     }
1738     else if( !strcmp( p_tk->psz_codec, "S_TEXT/SSA" ) ||
1739              !strcmp( p_tk->psz_codec, "S_TEXT/ASS" ) ||
1740              !strcmp( p_tk->psz_codec, "S_SSA" ) ||
1741              !strcmp( p_tk->psz_codec, "S_ASS" ))
1742     {
1743         p_tk->fmt.i_codec = VLC_CODEC_SSA;
1744         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1745         if( p_tk->i_extra_data )
1746             fill_extra_data( p_tk, 0 );
1747     }
1748     else if( !strcmp( p_tk->psz_codec, "S_VOBSUB" ) )
1749     {
1750         p_tk->fmt.i_codec = VLC_CODEC_SPU;
1751         p_tk->b_no_duration = true;
1752         if( p_tk->i_extra_data )
1753         {
1754             char *psz_start;
1755             char *psz_buf = (char *)malloc( p_tk->i_extra_data + 1);
1756             if( psz_buf != NULL )
1757             {
1758                 memcpy( psz_buf, p_tk->p_extra_data , p_tk->i_extra_data );
1759                 psz_buf[p_tk->i_extra_data] = '\0';
1760
1761                 psz_start = strstr( psz_buf, "size:" );
1762                 if( psz_start &&
1763                     vobsub_size_parse( psz_start,
1764                                        &p_tk->fmt.subs.spu.i_original_frame_width,
1765                                        &p_tk->fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
1766                 {
1767                     msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d",
1768                              p_tk->fmt.subs.spu.i_original_frame_width,
1769                              p_tk->fmt.subs.spu.i_original_frame_height );
1770                 }
1771                 else
1772                 {
1773                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1774                 }
1775
1776                 psz_start = strstr( psz_buf, "palette:" );
1777                 if( psz_start &&
1778                     vobsub_palette_parse( psz_start, &p_tk->fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
1779                 {
1780                     p_tk->fmt.subs.spu.palette[0] =  0xBeef;
1781                     msg_Dbg( &sys.demuxer, "vobsub palette read" );
1782                 }
1783                 else
1784                 {
1785                     msg_Warn( &sys.demuxer, "reading original palette failed" );
1786                 }
1787                 free( psz_buf );
1788             }
1789         }
1790     }
1791     else if( !strcmp( p_tk->psz_codec, "S_HDMV/PGS" ) )
1792     {
1793         p_tk->fmt.i_codec = VLC_CODEC_BD_PG;
1794     }
1795     else if( !strcmp( p_tk->psz_codec, "B_VOBBTN" ) )
1796     {
1797         p_tk->fmt.i_cat = NAV_ES;
1798     }
1799     else
1800     {
1801         msg_Err( &sys.demuxer, "unknown codec id=`%s'", p_tk->psz_codec );
1802         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1803     }
1804     return 0;
1805 }