]> git.sesse.net Git - vlc/blob - modules/demux/mkv/matroska_segment_parse.cpp
Check element size before reading it
[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     if( !strcmp( p_tk->psz_codec, "V_MS/VFW/FOURCC" ) )
1267     {
1268         if( p_tk->i_extra_data < (int)sizeof( VLC_BITMAPINFOHEADER ) )
1269         {
1270             msg_Err( &sys.demuxer, "missing/invalid VLC_BITMAPINFOHEADER" );
1271             p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1272         }
1273         else
1274         {
1275             VLC_BITMAPINFOHEADER *p_bih = (VLC_BITMAPINFOHEADER*)p_tk->p_extra_data;
1276
1277             p_tk->fmt.video.i_width = GetDWLE( &p_bih->biWidth );
1278             p_tk->fmt.video.i_height= GetDWLE( &p_bih->biHeight );
1279             p_tk->fmt.i_codec       = GetFOURCC( &p_bih->biCompression );
1280
1281             p_tk->fmt.i_extra       = GetDWLE( &p_bih->biSize ) - sizeof( VLC_BITMAPINFOHEADER );
1282             if( p_tk->fmt.i_extra > 0 )
1283             {
1284                 /* Very unlikely yet possible: bug #5659*/
1285                 size_t maxlen = p_tk->i_extra_data - sizeof( VLC_BITMAPINFOHEADER );
1286                 p_tk->fmt.i_extra = ( (unsigned)p_tk->fmt.i_extra < maxlen )?
1287                     p_tk->fmt.i_extra : maxlen;
1288
1289                 p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1290                 memcpy( p_tk->fmt.p_extra, &p_bih[1], p_tk->fmt.i_extra );
1291             }
1292         }
1293         p_tk->b_dts_only = true;
1294     }
1295     else if( !strcmp( p_tk->psz_codec, "V_MPEG1" ) ||
1296              !strcmp( p_tk->psz_codec, "V_MPEG2" ) )
1297     {
1298         p_tk->fmt.i_codec = VLC_CODEC_MPGV;
1299         if( p_tk->i_extra_data )
1300             fill_extra_data( p_tk, 0 );
1301     }
1302     else if( !strncmp( p_tk->psz_codec, "V_THEORA", 8 ) )
1303     {
1304         p_tk->fmt.i_codec = VLC_CODEC_THEORA;
1305         fill_extra_data( p_tk, 0 );
1306         p_tk->b_pts_only = true;
1307     }
1308     else if( !strncmp( p_tk->psz_codec, "V_REAL/RV", 9 ) )
1309     {
1310         uint8_t *p = p_tk->p_extra_data;
1311
1312         if( !strcmp( p_tk->psz_codec, "V_REAL/RV10" ) )
1313             p_fmt->i_codec = VLC_CODEC_RV10;
1314         else if( !strcmp( p_tk->psz_codec, "V_REAL/RV20" ) )
1315             p_fmt->i_codec = VLC_CODEC_RV20;
1316         else if( !strcmp( p_tk->psz_codec, "V_REAL/RV30" ) )
1317             p_fmt->i_codec = VLC_CODEC_RV30;
1318         else if( !strcmp( p_tk->psz_codec, "V_REAL/RV40" ) )
1319             p_fmt->i_codec = VLC_CODEC_RV40;
1320
1321         /* Extract the framerate from the header */
1322         if( p_tk->i_extra_data >= 26 &&
1323             p[4] == 'V' && p[5] == 'I' && p[6] == 'D' && p[7] == 'O' &&
1324             p[8] == 'R' && p[9] == 'V' &&
1325             (p[10] == '3' || p[10] == '4') && p[11] == '0' )
1326         {
1327             p_tk->fmt.video.i_frame_rate =
1328                 p[22] << 24 | p[23] << 16 | p[24] << 8 | p[25] << 0;
1329             p_tk->fmt.video.i_frame_rate_base = 65536;
1330         }
1331
1332         fill_extra_data( p_tk, 26 );
1333         p_tk->b_dts_only = true;
1334     }
1335     else if( !strncmp( p_tk->psz_codec, "V_DIRAC", 7 ) )
1336     {
1337         p_tk->fmt.i_codec = VLC_CODEC_DIRAC;
1338     }
1339     else if( !strncmp( p_tk->psz_codec, "V_VP8", 5 ) )
1340     {
1341         p_tk->fmt.i_codec = VLC_CODEC_VP8;
1342         p_tk->b_pts_only = true;
1343     }
1344     else if( !strncmp( p_tk->psz_codec, "V_MPEG4", 7 ) )
1345     {
1346         if( !strcmp( p_tk->psz_codec, "V_MPEG4/MS/V3" ) )
1347         {
1348             p_tk->fmt.i_codec = VLC_CODEC_DIV3;
1349         }
1350         else if( !strncmp( p_tk->psz_codec, "V_MPEG4/ISO", 11 ) )
1351         {
1352             /* A MPEG 4 codec, SP, ASP, AP or AVC */
1353             if( !strcmp( p_tk->psz_codec, "V_MPEG4/ISO/AVC" ) )
1354                 p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'v', 'c', '1' );
1355             else
1356                 p_tk->fmt.i_codec = VLC_CODEC_MP4V;
1357             fill_extra_data( p_tk, 0 );
1358         }
1359     }
1360     else if( !strcmp( p_tk->psz_codec, "V_QUICKTIME" ) )
1361     {
1362         MP4_Box_t *p_box = (MP4_Box_t*)xmalloc( sizeof( MP4_Box_t ) );
1363         stream_t *p_mp4_stream = stream_MemoryNew( VLC_OBJECT(&sys.demuxer),
1364                                                    p_tk->p_extra_data,
1365                                                    p_tk->i_extra_data,
1366                                                    true );
1367         if( MP4_ReadBoxCommon( p_mp4_stream, p_box ) &&
1368             MP4_ReadBox_sample_vide( p_mp4_stream, p_box ) )
1369         {
1370             p_tk->fmt.i_codec = p_box->i_type;
1371             p_tk->fmt.video.i_width = p_box->data.p_sample_vide->i_width;
1372             p_tk->fmt.video.i_height = p_box->data.p_sample_vide->i_height;
1373             p_tk->fmt.i_extra = p_box->data.p_sample_vide->i_qt_image_description;
1374             p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1375             memcpy( p_tk->fmt.p_extra, p_box->data.p_sample_vide->p_qt_image_description, p_tk->fmt.i_extra );
1376             MP4_FreeBox_sample_vide( p_box );
1377         }
1378         else
1379         {
1380             free( p_box );
1381         }
1382         stream_Delete( p_mp4_stream );
1383     }
1384     else if( !strcmp( p_tk->psz_codec, "V_MJPEG" ) )
1385     {
1386         p_tk->fmt.i_codec = VLC_CODEC_MJPG;
1387     }
1388     else if( !strcmp( p_tk->psz_codec, "A_MS/ACM" ) )
1389     {
1390         if( p_tk->i_extra_data < (int)sizeof( WAVEFORMATEX ) )
1391         {
1392             msg_Err( &sys.demuxer, "missing/invalid WAVEFORMATEX" );
1393             p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1394         }
1395         else
1396         {
1397             WAVEFORMATEX *p_wf = (WAVEFORMATEX*)p_tk->p_extra_data;
1398             if( p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE && 
1399                 p_tk->i_extra_data >= sizeof(WAVEFORMATEXTENSIBLE) )
1400             {
1401                 WAVEFORMATEXTENSIBLE * p_wext = (WAVEFORMATEXTENSIBLE*) p_wf;
1402                 sf_tag_to_fourcc( &p_wext->SubFormat,  &p_tk->fmt.i_codec, NULL);
1403                 /* FIXME should we use Samples and dwChannelMask?*/
1404             }
1405             else
1406                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &p_tk->fmt.i_codec, NULL );
1407
1408             if( p_tk->fmt.i_codec == VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
1409                 msg_Err( &sys.demuxer, "Unrecognized wf tag: 0x%x", GetWLE( &p_wf->wFormatTag ) );
1410             p_tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
1411             p_tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1412             p_tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1413             p_tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1414             p_tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1415
1416             p_tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
1417             if( p_tk->fmt.i_extra > 0 )
1418             {
1419                 p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1420                 memcpy( p_tk->fmt.p_extra, &p_wf[1], p_tk->fmt.i_extra );
1421             }
1422         }
1423     }
1424     else if( !strcmp( p_tk->psz_codec, "A_MPEG/L3" ) ||
1425              !strcmp( p_tk->psz_codec, "A_MPEG/L2" ) ||
1426              !strcmp( p_tk->psz_codec, "A_MPEG/L1" ) )
1427     {
1428         p_tk->fmt.i_codec = VLC_CODEC_MPGA;
1429     }
1430     else if( !strcmp( p_tk->psz_codec, "A_AC3" ) )
1431     {
1432         p_tk->fmt.i_codec = VLC_CODEC_A52;
1433     }
1434     else if( !strcmp( p_tk->psz_codec, "A_EAC3" ) )
1435     {
1436         p_tk->fmt.i_codec = VLC_CODEC_EAC3;
1437     }
1438     else if( !strcmp( p_tk->psz_codec, "A_DTS" ) )
1439     {
1440         p_tk->fmt.i_codec = VLC_CODEC_DTS;
1441     }
1442     else if( !strcmp( p_tk->psz_codec, "A_MLP" ) )
1443     {
1444         p_tk->fmt.i_codec = VLC_CODEC_MLP;
1445     }
1446     else if( !strcmp( p_tk->psz_codec, "A_TRUEHD" ) )
1447     {
1448         /* FIXME when more samples arrive */
1449         p_tk->fmt.i_codec = VLC_CODEC_TRUEHD;
1450         p_fmt->b_packetized = false;
1451     }
1452     else if( !strcmp( p_tk->psz_codec, "A_FLAC" ) )
1453     {
1454         p_tk->fmt.i_codec = VLC_CODEC_FLAC;
1455         fill_extra_data( p_tk, 8 );
1456     }
1457     else if( !strcmp( p_tk->psz_codec, "A_VORBIS" ) )
1458     {
1459         p_tk->fmt.i_codec = VLC_CODEC_VORBIS;
1460         fill_extra_data( p_tk, 0 );
1461     }
1462     else if( !strncmp( p_tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1463              !strncmp( p_tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1464     {
1465         int i_profile, i_srate, sbr = 0;
1466         static const unsigned int i_sample_rates[] =
1467         {
1468             96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1469             16000, 12000, 11025,  8000,  7350,     0,     0,     0
1470         };
1471
1472         p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1473         /* create data for faad (MP4DecSpecificDescrTag)*/
1474
1475         if( !strcmp( &p_tk->psz_codec[12], "MAIN" ) )
1476         {
1477             i_profile = 0;
1478         }
1479         else if( !strcmp( &p_tk->psz_codec[12], "LC" ) )
1480         {
1481             i_profile = 1;
1482         }
1483         else if( !strcmp( &p_tk->psz_codec[12], "SSR" ) )
1484         {
1485             i_profile = 2;
1486         }
1487         else if( !strcmp( &p_tk->psz_codec[12], "LC/SBR" ) )
1488         {
1489             i_profile = 1;
1490             sbr = 1;
1491         }
1492         else
1493         {
1494             i_profile = 3;
1495         }
1496
1497         for( i_srate = 0; i_srate < 13; i_srate++ )
1498         {
1499             if( i_sample_rates[i_srate] == p_tk->i_original_rate )
1500             {
1501                 break;
1502             }
1503         }
1504         msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1505
1506         p_tk->fmt.i_extra = sbr ? 5 : 2;
1507         p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1508         ((uint8_t*)p_tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1509         ((uint8_t*)p_tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (p_tk->fmt.audio.i_channels << 3);
1510         if (sbr != 0)
1511         {
1512             int syncExtensionType = 0x2B7;
1513             int iDSRI;
1514             for (iDSRI=0; iDSRI<13; iDSRI++)
1515                 if( i_sample_rates[iDSRI] == p_tk->fmt.audio.i_rate )
1516                     break;
1517             ((uint8_t*)p_tk->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
1518             ((uint8_t*)p_tk->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
1519             ((uint8_t*)p_tk->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
1520         }
1521     }
1522     else if( !strcmp( p_tk->psz_codec, "A_AAC" ) )
1523     {
1524         p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1525         fill_extra_data( p_tk, 0 );
1526     }
1527     else if( !strcmp( p_tk->psz_codec, "A_WAVPACK4" ) )
1528     {
1529         p_tk->fmt.i_codec = VLC_CODEC_WAVPACK;
1530         fill_extra_data( p_tk, 0 );
1531     }
1532     else if( !strcmp( p_tk->psz_codec, "A_TTA1" ) )
1533     {
1534         p_fmt->i_codec = VLC_CODEC_TTA;
1535         if( p_tk->i_extra_data > 0 )
1536         {
1537             fill_extra_data( p_tk, 0 );
1538         }
1539         else
1540         {
1541             p_fmt->i_extra = 30;
1542             p_fmt->p_extra = xmalloc( p_fmt->i_extra );
1543             uint8_t *p_extra = (uint8_t*)p_fmt->p_extra;
1544             memcpy( &p_extra[ 0], "TTA1", 4 );
1545             SetWLE( &p_extra[ 4], 1 );
1546             SetWLE( &p_extra[ 6], p_fmt->audio.i_channels );
1547             SetWLE( &p_extra[ 8], p_fmt->audio.i_bitspersample );
1548             SetDWLE( &p_extra[10], p_fmt->audio.i_rate );
1549             SetDWLE( &p_extra[14], 0xffffffff );
1550             memset( &p_extra[18], 0, 30  - 18 );
1551         }
1552     }
1553     else if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) ||
1554              !strcmp( p_tk->psz_codec, "A_PCM/INT/LIT" ) ||
1555              !strcmp( p_tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1556     {
1557         if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) )
1558         {
1559             p_tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1560         }
1561         else
1562         {
1563             p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1564         }
1565         p_tk->fmt.audio.i_blockalign = ( p_tk->fmt.audio.i_bitspersample + 7 ) / 8 * p_tk->fmt.audio.i_channels;
1566     }
1567     else if( !strncmp( p_tk->psz_codec, "A_REAL/", 7 ) )
1568     {
1569         if( !strcmp( p_tk->psz_codec, "A_REAL/14_4" ) )
1570         {
1571             p_fmt->i_codec = VLC_CODEC_RA_144;
1572             p_fmt->audio.i_channels = 1;
1573             p_fmt->audio.i_rate = 8000;
1574             p_fmt->audio.i_blockalign = 0x14;
1575         }
1576         else if( p_tk->i_extra_data > 28 )
1577         {
1578             uint8_t *p = p_tk->p_extra_data;
1579             if( memcmp( p, ".ra", 3 ) ) {
1580                 msg_Err( &sys.demuxer, "Invalid Real ExtraData 0x%4.4s", (char *)p );
1581                 p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1582             }
1583             else
1584             {
1585                 real_audio_private * priv = (real_audio_private*) p_tk->p_extra_data;
1586                 if( !strcmp( p_tk->psz_codec, "A_REAL/COOK" ) )
1587                 {
1588                     p_tk->fmt.i_codec = VLC_CODEC_COOK;
1589                     p_tk->fmt.audio.i_blockalign = hton16(priv->sub_packet_size);
1590                 }
1591                 else if( !strcmp( p_tk->psz_codec, "A_REAL/ATRC" ) )
1592                     p_tk->fmt.i_codec = VLC_CODEC_ATRAC3;
1593                 else if( !strcmp( p_tk->psz_codec, "A_REAL/28_8" ) )
1594                     p_tk->fmt.i_codec = VLC_CODEC_RA_288;
1595                 /* FIXME RALF and SIPR */
1596                 uint16_t version = (uint16_t) hton16(priv->version);
1597                 p_tk->p_sys =
1598                     new Cook_PrivateTrackData( hton16(priv->sub_packet_h),
1599                                                hton16(priv->frame_size),
1600                                                hton16(priv->sub_packet_size));
1601                 if( unlikely( !p_tk->p_sys ) )
1602                     return 1;
1603
1604                 if( unlikely( p_tk->p_sys->Init() ) )
1605                     return 1;
1606
1607                 if( version == 4 )
1608                 {
1609                     real_audio_private_v4 * v4 = (real_audio_private_v4*) priv;
1610                     p_tk->fmt.audio.i_channels = hton16(v4->channels);
1611                     p_tk->fmt.audio.i_bitspersample = hton16(v4->sample_size);
1612                     p_tk->fmt.audio.i_rate = hton16(v4->sample_rate);
1613                 }
1614                 else if( version == 5 )
1615                 {
1616                     real_audio_private_v5 * v5 = (real_audio_private_v5*) priv;
1617                     p_tk->fmt.audio.i_channels = hton16(v5->channels);
1618                     p_tk->fmt.audio.i_bitspersample = hton16(v5->sample_size);
1619                     p_tk->fmt.audio.i_rate = hton16(v5->sample_rate);
1620                 }
1621                 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);
1622
1623                 fill_extra_data( p_tk, p_tk->fmt.i_codec == VLC_CODEC_RA_288 ? 0 : 78);
1624             }
1625         }
1626     }
1627     else if( !strcmp( p_tk->psz_codec, "S_KATE" ) )
1628     {
1629         p_tk->fmt.i_codec = VLC_CODEC_KATE;
1630         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1631
1632         fill_extra_data( p_tk, 0 );
1633     }
1634     else if( !strcmp( p_tk->psz_codec, "S_TEXT/ASCII" ) )
1635     {
1636         p_fmt->i_codec = VLC_CODEC_SUBT;
1637         p_fmt->subs.psz_encoding = strdup( "ASCII" );
1638     }
1639     else if( !strcmp( p_tk->psz_codec, "S_TEXT/UTF8" ) )
1640     {
1641         p_tk->fmt.i_codec = VLC_CODEC_SUBT;
1642         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1643     }
1644     else if( !strcmp( p_tk->psz_codec, "S_TEXT/USF" ) )
1645     {
1646         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
1647         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1648         if( p_tk->i_extra_data )
1649             fill_extra_data( p_tk, 0 );
1650     }
1651     else if( !strcmp( p_tk->psz_codec, "S_TEXT/SSA" ) ||
1652              !strcmp( p_tk->psz_codec, "S_TEXT/ASS" ) ||
1653              !strcmp( p_tk->psz_codec, "S_SSA" ) ||
1654              !strcmp( p_tk->psz_codec, "S_ASS" ))
1655     {
1656         p_tk->fmt.i_codec = VLC_CODEC_SSA;
1657         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1658         if( p_tk->i_extra_data )
1659             fill_extra_data( p_tk, 0 );
1660     }
1661     else if( !strcmp( p_tk->psz_codec, "S_VOBSUB" ) )
1662     {
1663         p_tk->fmt.i_codec = VLC_CODEC_SPU;
1664         if( p_tk->i_extra_data )
1665         {
1666             char *psz_start;
1667             char *psz_buf = (char *)malloc( p_tk->i_extra_data + 1);
1668             if( psz_buf != NULL )
1669             {
1670                 memcpy( psz_buf, p_tk->p_extra_data , p_tk->i_extra_data );
1671                 psz_buf[p_tk->i_extra_data] = '\0';
1672
1673                 psz_start = strstr( psz_buf, "size:" );
1674                 if( psz_start &&
1675                     vobsub_size_parse( psz_start,
1676                                        &p_tk->fmt.subs.spu.i_original_frame_width,
1677                                        &p_tk->fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
1678                 {
1679                     msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d",
1680                              p_tk->fmt.subs.spu.i_original_frame_width,
1681                              p_tk->fmt.subs.spu.i_original_frame_height );
1682                 }
1683                 else
1684                 {
1685                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1686                     return 1;
1687                 }
1688
1689                 psz_start = strstr( psz_buf, "palette:" );
1690                 if( psz_start &&
1691                     vobsub_palette_parse( psz_start, &p_tk->fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
1692                 {
1693                     p_tk->fmt.subs.spu.palette[0] =  0xBeef;
1694                     msg_Dbg( &sys.demuxer, "vobsub palette read" );
1695                 }
1696                 else
1697                 {
1698                     msg_Warn( &sys.demuxer, "reading original palette failed" );
1699                 }
1700                 free( psz_buf );
1701             }
1702         }
1703     }
1704     else if( !strcmp( p_tk->psz_codec, "S_HDMV/PGS" ) )
1705     {
1706         p_tk->fmt.i_codec = VLC_CODEC_BD_PG;
1707     }
1708     else if( !strcmp( p_tk->psz_codec, "B_VOBBTN" ) )
1709     {
1710         p_tk->fmt.i_cat = NAV_ES;
1711     }
1712     else
1713     {
1714         msg_Err( &sys.demuxer, "unknown codec id=`%s'", p_tk->psz_codec );
1715         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1716     }
1717     return 0;
1718 }