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