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