]> git.sesse.net Git - vlc/blob - modules/demux/mkv/matroska_segment_parse.cpp
Implement basic Opus support in MKV
[vlc] / modules / demux / mkv / matroska_segment_parse.cpp
1 /*****************************************************************************
2  * matroska_segment_parse.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2010 VLC authors and VideoLAN
5  * $Id$
6  *
7  * Authors: Laurent Aimar <fenrir@via.ecp.fr>
8  *          Steve Lhomme <steve.lhomme@free.fr>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with this program; if not, write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24 #include "mkv.hpp"
25 #include "matroska_segment.hpp"
26 #include "chapters.hpp"
27 #include "demux.hpp"
28 #include "Ebml_parser.hpp"
29 #include "util.hpp"
30
31 extern "C" {
32 #include "../vobsub.h"
33 #include "../xiph.h"
34 }
35
36 #include <vlc_codecs.h>
37
38 /* GetFourCC helper */
39 #define GetFOURCC( p )  __GetFOURCC( (uint8_t*)p )
40 static vlc_fourcc_t __GetFOURCC( uint8_t *p )
41 {
42     return VLC_FOURCC( p[0], p[1], p[2], p[3] );
43 }
44
45 static inline void fill_extra_data( mkv_track_t *p_tk, unsigned int offset )
46 {
47     if(p_tk->i_extra_data <= offset) return;
48     p_tk->fmt.i_extra = p_tk->i_extra_data - offset;
49     p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
50     if(!p_tk->fmt.p_extra) { p_tk->fmt.i_extra = 0; return; };
51     memcpy( p_tk->fmt.p_extra, p_tk->p_extra_data + offset, p_tk->fmt.i_extra );
52 }
53
54 /*****************************************************************************
55  * Some functions to manipulate memory
56  *****************************************************************************/
57 static inline char * ToUTF8( const UTFstring &u )
58 {
59     return strdup( u.GetUTF8().c_str() );
60 }
61
62 /*****************************************************************************
63  * ParseSeekHead:
64  *****************************************************************************/
65 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
66 {
67     EbmlParser  *ep;
68     EbmlElement *l;
69     bool b_seekable;
70
71     i_seekhead_count++;
72
73     stream_Control( sys.demuxer.s, STREAM_CAN_SEEK, &b_seekable );
74     if( !b_seekable )
75         return;
76
77     ep = new EbmlParser( &es, seekhead, &sys.demuxer );
78
79     while( ( l = ep->Get() ) != NULL )
80     {
81         if( MKV_IS_ID( l, KaxSeek ) )
82         {
83             EbmlId id = EBML_ID(EbmlVoid);
84             int64_t i_pos = -1;
85
86 #ifdef MKV_DEBUG
87             msg_Dbg( &sys.demuxer, "|   |   + Seek" );
88 #endif
89             ep->Down();
90             try
91             {
92                 while( ( l = ep->Get() ) != NULL )
93                 {
94                     if( unlikely( l->GetSize() >= SIZE_MAX ) )
95                     {
96                         msg_Err( &sys.demuxer,"%s too big... skipping it",  typeid(*l).name() );
97                         continue;
98                     }
99                     if( MKV_IS_ID( l, KaxSeekID ) )
100                     {
101                         KaxSeekID &sid = *(KaxSeekID*)l;
102                         sid.ReadData( es.I_O() );
103                         id = EbmlId( sid.GetBuffer(), sid.GetSize() );
104                     }
105                     else if( MKV_IS_ID( l, KaxSeekPosition ) )
106                     {
107                         KaxSeekPosition &spos = *(KaxSeekPosition*)l;
108                         spos.ReadData( es.I_O() );
109                         i_pos = (int64_t)segment->GetGlobalPosition( uint64( spos ) );
110                     }
111                     else
112                     {
113                         /* Many mkvmerge files hit this case. It seems to be a broken SeekHead */
114                         msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
115                     }
116                 }
117             }
118             catch(...)
119             {
120                 msg_Err( &sys.demuxer,"Error while reading %s",  typeid(*l).name() );
121             }
122             ep->Up();
123
124             if( i_pos >= 0 )
125             {
126                 if( id == EBML_ID(KaxCues) )
127                 {
128                     msg_Dbg( &sys.demuxer, "|   - cues at %"PRId64, i_pos );
129                     LoadSeekHeadItem( EBML_INFO(KaxCues), i_pos );
130                 }
131                 else if( id == EBML_ID(KaxInfo) )
132                 {
133                     msg_Dbg( &sys.demuxer, "|   - info at %"PRId64, i_pos );
134                     LoadSeekHeadItem( EBML_INFO(KaxInfo), i_pos );
135                 }
136                 else if( id == EBML_ID(KaxChapters) )
137                 {
138                     msg_Dbg( &sys.demuxer, "|   - chapters at %"PRId64, i_pos );
139                     LoadSeekHeadItem( EBML_INFO(KaxChapters), i_pos );
140                 }
141                 else if( id == EBML_ID(KaxTags) )
142                 {
143                     msg_Dbg( &sys.demuxer, "|   - tags at %"PRId64, i_pos );
144                     LoadSeekHeadItem( EBML_INFO(KaxTags), i_pos );
145                 }
146                 else if( id == EBML_ID(KaxSeekHead) )
147                 {
148                     msg_Dbg( &sys.demuxer, "|   - chained seekhead at %"PRId64, i_pos );
149                     LoadSeekHeadItem( EBML_INFO(KaxSeekHead), i_pos );
150                 }
151                 else if( id == EBML_ID(KaxTracks) )
152                 {
153                     msg_Dbg( &sys.demuxer, "|   - tracks at %"PRId64, i_pos );
154                     LoadSeekHeadItem( EBML_INFO(KaxTracks), i_pos );
155                 }
156                 else if( id == EBML_ID(KaxAttachments) )
157                 {
158                     msg_Dbg( &sys.demuxer, "|   - attachments at %"PRId64, i_pos );
159                     LoadSeekHeadItem( EBML_INFO(KaxAttachments), i_pos );
160                 }
161 #ifdef MKV_DEBUG
162                 else
163                     msg_Dbg( &sys.demuxer, "|   - unknown seekhead reference at %"PRId64, i_pos );
164 #endif
165             }
166         }
167         else
168             msg_Dbg( &sys.demuxer, "|   |   + ParseSeekHead Unknown (%s)", typeid(*l).name() );
169     }
170     delete ep;
171 }
172
173
174 /**
175  * Helper function to print the mkv parse tree
176  */
177 static void MkvTree( demux_t & demuxer, int i_level, const char *psz_format, ... )
178 {
179     va_list args;
180     if( i_level > 9 )
181     {
182         msg_Err( &demuxer, "MKV tree is too deep" );
183         return;
184     }
185     va_start( args, psz_format );
186     static const char psz_foo[] = "|   |   |   |   |   |   |   |   |   |";
187     char *psz_foo2 = (char*)malloc( i_level * 4 + 3 + strlen( psz_format ) );
188     strncpy( psz_foo2, psz_foo, 4 * i_level );
189     psz_foo2[ 4 * i_level ] = '+';
190     psz_foo2[ 4 * i_level + 1 ] = ' ';
191     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
192     msg_GenericVa( &demuxer,VLC_MSG_DBG, "mkv", psz_foo2, args );
193     free( psz_foo2 );
194     va_end( args );
195 }
196
197
198 /*****************************************************************************
199  * ParseTrackEntry:
200  *****************************************************************************/
201 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
202 {
203     bool bSupported = true;
204
205     /* Init the track */
206     mkv_track_t *tk = new mkv_track_t();
207     memset( tk, 0, sizeof( mkv_track_t ) );
208
209     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
210     tk->p_es = NULL;
211     tk->fmt.psz_language       = strdup("English");
212     tk->fmt.psz_description    = NULL;
213
214     tk->b_default              = true;
215     tk->b_enabled              = true;
216     tk->b_forced               = false;
217     tk->b_silent               = false;
218     tk->i_number               = tracks.size() - 1;
219     tk->i_extra_data           = 0;
220     tk->p_extra_data           = NULL;
221     tk->psz_codec              = NULL;
222     tk->b_dts_only             = false;
223     tk->i_default_duration     = 0;
224     tk->f_timecodescale        = 1.0;
225
226     tk->b_inited               = false;
227     tk->i_data_init            = 0;
228     tk->p_data_init            = NULL;
229
230     tk->psz_codec_name         = NULL;
231     tk->psz_codec_settings     = NULL;
232     tk->psz_codec_info_url     = NULL;
233     tk->psz_codec_download_url = NULL;
234
235     tk->i_compression_type     = MATROSKA_COMPRESSION_NONE;
236     tk->i_encoding_scope       = MATROSKA_ENCODING_SCOPE_ALL_FRAMES;
237     tk->p_compression_data     = NULL;
238
239     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
240
241     for( size_t i = 0; i < m->ListSize(); i++ )
242     {
243         EbmlElement *l = (*m)[i];
244
245         if( MKV_IS_ID( l, KaxTrackNumber ) )
246         {
247             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
248
249             tk->i_number = uint32( tnum );
250             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
251         }
252         else  if( MKV_IS_ID( l, KaxTrackUID ) )
253         {
254             KaxTrackUID &tuid = *(KaxTrackUID*)l;
255
256             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
257         }
258         else  if( MKV_IS_ID( l, KaxTrackType ) )
259         {
260             const char *psz_type;
261             KaxTrackType &ttype = *(KaxTrackType*)l;
262
263             switch( uint8(ttype) )
264             {
265                 case track_audio:
266                     psz_type = "audio";
267                     tk->fmt.i_cat = AUDIO_ES;
268                     tk->fmt.audio.i_channels = 1;
269                     tk->fmt.audio.i_rate = 8000;
270                     break;
271                 case track_video:
272                     psz_type = "video";
273                     tk->fmt.i_cat = VIDEO_ES;
274                     break;
275                 case track_subtitle:
276                     psz_type = "subtitle";
277                     tk->fmt.i_cat = SPU_ES;
278                     break;
279                 case track_buttons:
280                     psz_type = "buttons";
281                     tk->fmt.i_cat = SPU_ES;
282                     break;
283                 default:
284                     psz_type = "unknown";
285                     tk->fmt.i_cat = UNKNOWN_ES;
286                     break;
287             }
288
289             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
290         }
291         else  if( MKV_IS_ID( l, KaxTrackFlagEnabled ) ) // UNUSED
292         {
293             KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
294
295             tk->b_enabled = uint32( fenb );
296             msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u", uint32( fenb ) );
297         }
298         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
299         {
300             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
301
302             tk->b_default = uint32( fdef );
303             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef ) );
304         }
305         else  if( MKV_IS_ID( l, KaxTrackFlagForced ) ) // UNUSED
306         {
307             KaxTrackFlagForced &ffor = *(KaxTrackFlagForced*)l;
308             tk->b_forced = uint32( ffor );
309
310             msg_Dbg( &sys.demuxer, "|   |   |   + Track Forced=%u", uint32( ffor ) );
311         }
312         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) ) // UNUSED
313         {
314             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
315
316             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
317         }
318         else  if( MKV_IS_ID( l, KaxTrackMinCache ) ) // UNUSED
319         {
320             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
321
322             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
323         }
324         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) ) // UNUSED
325         {
326             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
327
328             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
329         }
330         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
331         {
332             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
333
334             tk->i_default_duration = uint64(defd);
335             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration=%"PRId64, uint64(defd) );
336         }
337         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
338         {
339             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
340
341             tk->f_timecodescale = float( ttcs );
342             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
343         }
344         else  if( MKV_IS_ID( l, KaxMaxBlockAdditionID ) ) // UNUSED
345         {
346             KaxMaxBlockAdditionID &mbl = *(KaxMaxBlockAdditionID*)l;
347
348             msg_Dbg( &sys.demuxer, "|   |   |   + Track Max BlockAdditionID=%d", uint32( mbl ) );
349         }
350         else if( MKV_IS_ID( l, KaxTrackName ) )
351         {
352             KaxTrackName &tname = *(KaxTrackName*)l;
353
354             tk->fmt.psz_description = ToUTF8( UTFstring( tname ) );
355             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
356         }
357         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
358         {
359             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
360
361             free( tk->fmt.psz_language );
362             tk->fmt.psz_language = strdup( string( lang ).c_str() );
363             msg_Dbg( &sys.demuxer,
364                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
365         }
366         else  if( MKV_IS_ID( l, KaxCodecID ) )
367         {
368             KaxCodecID &codecid = *(KaxCodecID*)l;
369
370             tk->psz_codec = strdup( string( codecid ).c_str() );
371             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
372         }
373         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
374         {
375             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
376
377             tk->i_extra_data = cpriv.GetSize();
378             if( tk->i_extra_data > 0 )
379             {
380                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
381                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
382             }
383             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size=%"PRId64, cpriv.GetSize() );
384         }
385         else if( MKV_IS_ID( l, KaxCodecName ) )
386         {
387             KaxCodecName &cname = *(KaxCodecName*)l;
388
389             tk->psz_codec_name = ToUTF8( UTFstring( cname ) );
390             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
391         }
392         //AttachmentLink
393         else if( MKV_IS_ID( l, KaxCodecDecodeAll ) ) // UNUSED
394         {
395             KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
396
397             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u", uint8( cdall ) );
398         }
399         else if( MKV_IS_ID( l, KaxTrackOverlay ) ) // UNUSED
400         {
401             KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
402
403             msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u", uint32( tovr ) );
404         }
405 #if LIBMATROSKA_VERSION >= 0x010401
406         else if( MKV_IS_ID( l, KaxCodecDelay ) )
407         {
408             KaxCodecDelay &codecdelay = *(KaxCodecDelay*)l;
409             tk->i_codec_delay = uint64_t( codecdelay ) / 1000;
410             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Delay =%"PRIu64,
411                      tk->i_codec_delay );
412         }
413         else if( MKV_IS_ID( l, KaxSeekPreRoll ) )
414         {
415             KaxSeekPreRoll &spr = *(KaxSeekPreRoll*)l;
416             tk->i_seek_preroll = uint64_t(spr) / 1000;
417             msg_Dbg( &sys.demuxer, "|   |   |   + Track Seek Preroll =%"PRIu64, tk->i_seek_preroll );
418         }
419 #endif
420         else if( MKV_IS_ID( l, KaxContentEncodings ) )
421         {
422             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
423             MkvTree( sys.demuxer, 3, "Content Encodings" );
424             if ( cencs->ListSize() > 1 )
425             {
426                 msg_Err( &sys.demuxer, "Multiple Compression method not supported" );
427                 bSupported = false;
428             }
429             for( size_t j = 0; j < cencs->ListSize(); j++ )
430             {
431                 EbmlElement *l2 = (*cencs)[j];
432                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
433                 {
434                     MkvTree( sys.demuxer, 4, "Content Encoding" );
435                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
436                     for( size_t k = 0; k < cenc->ListSize(); k++ )
437                     {
438                         EbmlElement *l3 = (*cenc)[k];
439                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
440                         {
441                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
442                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
443                         }
444                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
445                         {
446                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
447                             tk->i_encoding_scope = uint32( encscope );
448                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
449                         }
450                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
451                         {
452                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
453                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
454                         }
455                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
456                         {
457                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
458                             MkvTree( sys.demuxer, 5, "Content Compression" );
459                             //Default compression type is 0 (Zlib)
460                             tk->i_compression_type = MATROSKA_COMPRESSION_ZLIB;
461                             for( size_t n = 0; n < compr->ListSize(); n++ )
462                             {
463                                 EbmlElement *l4 = (*compr)[n];
464                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
465                                 {
466                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
467                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
468                                     tk->i_compression_type = uint32( compalg );
469                                     if ( ( tk->i_compression_type != MATROSKA_COMPRESSION_ZLIB ) &&
470                                          ( tk->i_compression_type != MATROSKA_COMPRESSION_HEADER ) )
471                                     {
472                                         msg_Err( &sys.demuxer, "Track Compression method %d not supported", tk->i_compression_type );
473                                         bSupported = false;
474                                     }
475                                 }
476                                 else if( MKV_IS_ID( l4, KaxContentCompSettings ) )
477                                 {
478                                     tk->p_compression_data = new KaxContentCompSettings( *(KaxContentCompSettings*)l4 );
479                                 }
480                                 else
481                                 {
482                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
483                                 }
484                             }
485                         }
486                         // ContentEncryption Unsupported
487                         else
488                         {
489                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
490                         }
491                     }
492                 }
493                 else
494                 {
495                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
496                 }
497             }
498         }
499 //        else if( MKV_IS_ID( l, KaxCodecSettings) ) DEPRECATED by matroska
500 //        {
501 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
502
503 //            tk->psz_codec_settings = ToUTF8( UTFstring( cset ) );
504 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
505 //        }
506 //        else if( MKV_IS_ID( l, KaxCodecInfoURL) ) DEPRECATED by matroska
507 //        {
508 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
509
510 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
511 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
512 //        }
513 //        else if( MKV_IS_ID( l, KaxCodecDownloadURL) ) DEPRECATED by matroska
514 //        {
515 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
516
517 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
518 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
519 //        }
520         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
521         {
522             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
523             unsigned int i_crop_right = 0, i_crop_left = 0, i_crop_top = 0, i_crop_bottom = 0;
524             unsigned int i_display_unit = 0, i_display_width = 0, i_display_height = 0;
525
526             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
527             tk->f_fps = 0.0;
528
529             tk->fmt.video.i_frame_rate_base = (unsigned int)(tk->i_default_duration / 1000);
530             tk->fmt.video.i_frame_rate = 1000000;
531
532             for( unsigned int j = 0; j < tkv->ListSize(); j++ )
533             {
534                 EbmlElement *l = (*tkv)[j];
535                 if( MKV_IS_ID( l, KaxVideoFlagInterlaced ) ) // UNUSED
536                 {
537                     KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)l;
538
539                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
540                 }
541                 else if( MKV_IS_ID( l, KaxVideoStereoMode ) ) // UNUSED
542                 {
543                     KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)l;
544
545                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
546                 }
547                 else if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
548                 {
549                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
550
551                     tk->fmt.video.i_width += uint16( vwidth );
552                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
553                 }
554                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
555                 {
556                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
557
558                     tk->fmt.video.i_height += uint16( vheight );
559                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
560                 }
561                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
562                 {
563                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
564
565                     i_display_width = uint16( vwidth );
566                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
567                 }
568                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
569                 {
570                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
571
572                     i_display_height = uint16( vheight );
573                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
574                 }
575                 else if( MKV_IS_ID( l, KaxVideoPixelCropBottom ) )
576                 {
577                     KaxVideoPixelCropBottom &cropval = *(KaxVideoPixelCropBottom*)l;
578
579                     i_crop_bottom = uint16( cropval );
580                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel bottom=%d", uint16( cropval ) );
581                 }
582                 else if( MKV_IS_ID( l, KaxVideoPixelCropTop ) )
583                 {
584                     KaxVideoPixelCropTop &cropval = *(KaxVideoPixelCropTop*)l;
585
586                     i_crop_top = uint16( cropval );
587                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel top=%d", uint16( cropval ) );
588                 }
589                 else if( MKV_IS_ID( l, KaxVideoPixelCropRight ) )
590                 {
591                     KaxVideoPixelCropRight &cropval = *(KaxVideoPixelCropRight*)l;
592
593                     i_crop_right = uint16( cropval );
594                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel right=%d", uint16( cropval ) );
595                 }
596                 else if( MKV_IS_ID( l, KaxVideoPixelCropLeft ) )
597                 {
598                     KaxVideoPixelCropLeft &cropval = *(KaxVideoPixelCropLeft*)l;
599
600                     i_crop_left = uint16( cropval );
601                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel left=%d", uint16( cropval ) );
602                 }
603                 else if( MKV_IS_ID( l, KaxVideoDisplayUnit ) )
604                 {
605                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
606
607                     i_display_unit = uint8( vdmode );
608                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
609                              i_display_unit == 0 ? "pixels" : ( i_display_unit == 1 ? "centimeters": "inches" ) );
610                 }
611                 else if( MKV_IS_ID( l, KaxVideoAspectRatio ) ) // UNUSED
612                 {
613                     KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
614
615                     msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
616                 }
617                 // ColourSpace UNUSED
618                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
619                 {
620                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
621
622                     tk->f_fps = float( vfps );
623                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
624                 }
625 //                else if( MKV_IS_ID( l, KaxVideoGamma) ) //DEPRECATED by Matroska
626 //                {
627 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
628
629 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + gamma=%f", float( gamma ) );
630 //                }
631                 else
632                 {
633                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
634                 }
635             }
636             if( i_display_height && i_display_width )
637             {
638                 tk->fmt.video.i_sar_num = i_display_width  * tk->fmt.video.i_height;
639                 tk->fmt.video.i_sar_den = i_display_height * tk->fmt.video.i_width;
640             }
641             if( i_crop_left || i_crop_right || i_crop_top || i_crop_bottom )
642             {
643                 tk->fmt.video.i_visible_width   = tk->fmt.video.i_width;
644                 tk->fmt.video.i_visible_height  = tk->fmt.video.i_height;
645                 tk->fmt.video.i_x_offset        = i_crop_left;
646                 tk->fmt.video.i_y_offset        = i_crop_top;
647                 tk->fmt.video.i_visible_width  -= i_crop_left + i_crop_right;
648                 tk->fmt.video.i_visible_height -= i_crop_top + i_crop_bottom;
649             }
650             /* FIXME: i_display_* allows you to not only set DAR, but also a zoom factor.
651                we do not support this atm */
652         }
653         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
654         {
655             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
656
657             /* Initialize default values */
658             tk->fmt.audio.i_channels = 1;
659             tk->fmt.audio.i_rate = 8000;
660
661             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
662
663             for( unsigned int j = 0; j < tka->ListSize(); j++ )
664             {
665                 EbmlElement *l = (*tka)[j];
666
667                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
668                 {
669                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
670
671                     tk->i_original_rate = tk->fmt.audio.i_rate = (int)float( afreq );
672                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
673                 }
674                 else if( MKV_IS_ID( l, KaxAudioOutputSamplingFreq ) )
675                 {
676                     KaxAudioOutputSamplingFreq &afreq = *(KaxAudioOutputSamplingFreq*)l;
677
678                     tk->fmt.audio.i_rate = (int)float( afreq );
679                     msg_Dbg( &sys.demuxer, "|   |   |   |   + aoutfreq=%d", tk->fmt.audio.i_rate );
680                 }
681                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
682                 {
683                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
684
685                     tk->fmt.audio.i_channels = uint8( achan );
686                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
687                 }
688                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
689                 {
690                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
691
692                     tk->fmt.audio.i_bitspersample = uint8( abits );
693                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
694                 }
695                 else
696                 {
697                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
698                 }
699             }
700         }
701         else
702         {
703             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
704                      typeid(*l).name() );
705         }
706     }
707
708     if ( bSupported )
709     {
710 #ifdef HAVE_ZLIB_H
711         if( tk->i_compression_type == MATROSKA_COMPRESSION_ZLIB &&
712             tk->i_encoding_scope & MATROSKA_ENCODING_SCOPE_PRIVATE &&
713             tk->i_extra_data && tk->p_extra_data &&
714             zlib_decompress_extra( &sys.demuxer, tk) )
715             return;
716 #endif
717         if( TrackInit( tk ) )
718         {
719             msg_Err(&sys.demuxer, "Couldn't init track %d", tk->i_number );
720             free(tk->p_extra_data);
721             delete tk;
722             return;
723         }
724
725         tracks.push_back( tk );
726     }
727     else
728     {
729         msg_Err( &sys.demuxer, "Track Entry %d not supported", tk->i_number );
730         free(tk->p_extra_data);
731         delete tk;
732     }
733 }
734
735 /*****************************************************************************
736  * ParseTracks:
737  *****************************************************************************/
738 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
739 {
740     EbmlElement *el;
741     int i_upper_level = 0;
742
743     /* Master elements */
744     if( unlikely( tracks->GetSize() >= SIZE_MAX ) )
745     {
746         msg_Err( &sys.demuxer, "Track too big, aborting" );
747         return;
748     }
749     try
750     {
751         tracks->Read( es, EBML_CONTEXT(tracks), i_upper_level, el, true );
752     }
753     catch(...)
754     {
755         msg_Err( &sys.demuxer, "Couldn't read tracks" );
756         return;
757     }
758
759     for( size_t i = 0; i < tracks->ListSize(); i++ )
760     {
761         EbmlElement *l = (*tracks)[i];
762
763         if( MKV_IS_ID( l, KaxTrackEntry ) )
764         {
765             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
766         }
767         else
768         {
769             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
770         }
771     }
772 }
773
774 /*****************************************************************************
775  * ParseInfo:
776  *****************************************************************************/
777 void matroska_segment_c::ParseInfo( KaxInfo *info )
778 {
779     EbmlElement *el;
780     EbmlMaster  *m;
781     int i_upper_level = 0;
782
783     /* Master elements */
784     m = static_cast<EbmlMaster *>(info);
785     if( unlikely( m->GetSize() >= SIZE_MAX ) )
786     {
787         msg_Err( &sys.demuxer, "Info too big, aborting" );
788         return;
789     }
790     try
791     {
792         m->Read( es, EBML_CONTEXT(info), i_upper_level, el, true );
793     }
794     catch(...)
795     {
796         msg_Err( &sys.demuxer, "Couldn't read info" );
797         return;
798     }   
799
800     for( size_t i = 0; i < m->ListSize(); i++ )
801     {
802         EbmlElement *l = (*m)[i];
803
804         if( MKV_IS_ID( l, KaxSegmentUID ) )
805         {
806             if ( p_segment_uid == NULL )
807                 p_segment_uid = new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l));
808
809             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)p_segment_uid->GetBuffer() );
810         }
811         else if( MKV_IS_ID( l, KaxPrevUID ) )
812         {
813             if ( p_prev_segment_uid == NULL )
814             {
815                 p_prev_segment_uid = new KaxPrevUID(*static_cast<KaxPrevUID*>(l));
816                 b_ref_external_segments = true;
817             }
818
819             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)p_prev_segment_uid->GetBuffer() );
820         }
821         else if( MKV_IS_ID( l, KaxNextUID ) )
822         {
823             if ( p_next_segment_uid == NULL )
824             {
825                 p_next_segment_uid = new KaxNextUID(*static_cast<KaxNextUID*>(l));
826                 b_ref_external_segments = true;
827             }
828
829             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)p_next_segment_uid->GetBuffer() );
830         }
831         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
832         {
833             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
834
835             i_timescale = uint64(tcs);
836
837             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale=%"PRId64,
838                      i_timescale );
839         }
840         else if( MKV_IS_ID( l, KaxDuration ) )
841         {
842             KaxDuration &dur = *(KaxDuration*)l;
843
844             i_duration = mtime_t( double( dur ) );
845
846             msg_Dbg( &sys.demuxer, "|   |   + Duration=%"PRId64,
847                      i_duration );
848         }
849         else if( MKV_IS_ID( l, KaxMuxingApp ) )
850         {
851             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
852
853             psz_muxing_application = ToUTF8( UTFstring( mapp ) );
854
855             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
856                      psz_muxing_application );
857         }
858         else if( MKV_IS_ID( l, KaxWritingApp ) )
859         {
860             KaxWritingApp &wapp = *(KaxWritingApp*)l;
861
862             psz_writing_application = ToUTF8( UTFstring( wapp ) );
863
864             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
865                      psz_writing_application );
866         }
867         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
868         {
869             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
870
871             psz_segment_filename = ToUTF8( UTFstring( sfn ) );
872
873             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
874                      psz_segment_filename );
875         }
876         else if( MKV_IS_ID( l, KaxTitle ) )
877         {
878             KaxTitle &title = *(KaxTitle*)l;
879
880             psz_title = ToUTF8( UTFstring( title ) );
881
882             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
883         }
884         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
885         {
886             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
887
888             families.push_back( new KaxSegmentFamily(*uid) );
889
890             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
891         }
892         else if( MKV_IS_ID( l, KaxDateUTC ) )
893         {
894             KaxDateUTC &date = *(KaxDateUTC*)l;
895             time_t i_date;
896             struct tm tmres;
897             char   buffer[25];
898
899             i_date = date.GetEpochDate();
900             if( gmtime_r( &i_date, &tmres ) &&
901                 strftime( buffer, sizeof(buffer), "%a %b %d %H:%M:%S %Y",
902                           &tmres ) )
903             {
904                 psz_date_utc = strdup( buffer );
905                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", buffer );
906             }
907         }
908         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
909         {
910             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
911             try
912             {
913                 if( unlikely( p_trans->GetSize() >= SIZE_MAX ) )
914                 {
915                     msg_Err( &sys.demuxer, "Chapter translate too big, aborting" );
916                     continue;
917                 }
918
919                 p_trans->Read( es, EBML_CONTEXT(p_trans), i_upper_level, el, true );
920                 chapter_translation_c *p_translate = new chapter_translation_c();
921
922                 for( size_t j = 0; j < p_trans->ListSize(); j++ )
923                 {
924                     EbmlElement *l = (*p_trans)[j];
925
926                     if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
927                     {
928                         p_translate->editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
929                     }
930                     else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
931                     {
932                         p_translate->codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
933                     }
934                     else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
935                     {
936                         p_translate->p_translated = new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) );
937                     }
938                 }
939
940                 translations.push_back( p_translate );
941             }
942             catch(...)
943             {
944                 msg_Err( &sys.demuxer, "Error while reading Chapter Tranlate");
945             }
946         }
947         else
948         {
949             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
950         }
951     }
952
953     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
954     i_duration = mtime_t(f_dur);
955     if( !i_duration ) i_duration = -1;
956 }
957
958
959 /*****************************************************************************
960  * ParseChapterAtom
961  *****************************************************************************/
962 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
963 {
964     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
965     for( size_t i = 0; i < ca->ListSize(); i++ )
966     {
967         EbmlElement *l = (*ca)[i];
968
969         if( MKV_IS_ID( l, KaxChapterUID ) )
970         {
971             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
972             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %"PRIu64"", chapters.i_uid );
973         }
974         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
975         {
976             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
977             chapters.b_display_seekpoint = uint8( flag ) == 0;
978
979             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
980         }
981         else if( MKV_IS_ID( l, KaxChapterSegmentUID ) )
982         {
983             chapters.p_segment_uid = new KaxChapterSegmentUID( *static_cast<KaxChapterSegmentUID*>(l) );
984             b_ref_external_segments = true;
985             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterSegmentUID= %u", *(uint32*)chapters.p_segment_uid->GetBuffer() );
986         }
987         else if( MKV_IS_ID( l, KaxChapterSegmentEditionUID ) )
988         {
989             chapters.p_segment_edition_uid = new KaxChapterSegmentEditionUID( *static_cast<KaxChapterSegmentEditionUID*>(l) );
990             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterSegmentEditionUID= %u",
991 #if LIBMATROSKA_VERSION < 0x010300
992                      *(uint32*)chapters.p_segment_edition_uid->GetBuffer()
993 #else
994                      *(uint32*)chapters.p_segment_edition_uid
995 #endif
996                    );
997         }
998         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
999         {
1000             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
1001             chapters.i_start_time = uint64( start ) / INT64_C(1000);
1002
1003             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %"PRId64"", chapters.i_start_time );
1004         }
1005         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
1006         {
1007             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
1008             chapters.i_end_time = uint64( end ) / INT64_C(1000);
1009
1010             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %"PRId64"", chapters.i_end_time );
1011         }
1012         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
1013         {
1014             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
1015
1016             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
1017             for( size_t j = 0; j < cd->ListSize(); j++ )
1018             {
1019                 EbmlElement *l= (*cd)[j];
1020
1021                 if( MKV_IS_ID( l, KaxChapterString ) )
1022                 {
1023                     KaxChapterString &name =*(KaxChapterString*)l;
1024                     for ( int k = 0; k < i_level; k++)
1025                         chapters.psz_name += '+';
1026                     chapters.psz_name += ' ';
1027                     char *psz_tmp_utf8 = ToUTF8( UTFstring( name ) );
1028                     chapters.psz_name += psz_tmp_utf8;
1029                     chapters.b_user_display = true;
1030
1031                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", psz_tmp_utf8 );
1032                     free( psz_tmp_utf8 );
1033                 }
1034                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
1035                 {
1036                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
1037                     const char *psz = string( lang ).c_str();
1038
1039                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
1040                 }
1041                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
1042                 {
1043                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
1044                     const char *psz = string( ct ).c_str();
1045
1046                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
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             if( p_wf->wFormatTag == WAVE_FORMAT_EXTENSIBLE && 
1433                 p_tk->i_extra_data >= sizeof(WAVEFORMATEXTENSIBLE) )
1434             {
1435                 WAVEFORMATEXTENSIBLE * p_wext = (WAVEFORMATEXTENSIBLE*) p_wf;
1436                 sf_tag_to_fourcc( &p_wext->SubFormat,  &p_tk->fmt.i_codec, NULL);
1437                 /* FIXME should we use Samples and dwChannelMask?*/
1438             }
1439             else
1440                 wf_tag_to_fourcc( GetWLE( &p_wf->wFormatTag ), &p_tk->fmt.i_codec, NULL );
1441
1442             if( p_tk->fmt.i_codec == VLC_FOURCC( 'u', 'n', 'd', 'f' ) )
1443                 msg_Err( &sys.demuxer, "Unrecognized wf tag: 0x%x", GetWLE( &p_wf->wFormatTag ) );
1444             p_tk->fmt.audio.i_channels   = GetWLE( &p_wf->nChannels );
1445             p_tk->fmt.audio.i_rate = GetDWLE( &p_wf->nSamplesPerSec );
1446             p_tk->fmt.i_bitrate    = GetDWLE( &p_wf->nAvgBytesPerSec ) * 8;
1447             p_tk->fmt.audio.i_blockalign = GetWLE( &p_wf->nBlockAlign );;
1448             p_tk->fmt.audio.i_bitspersample = GetWLE( &p_wf->wBitsPerSample );
1449
1450             p_tk->fmt.i_extra            = GetWLE( &p_wf->cbSize );
1451             if( p_tk->fmt.i_extra > 0 )
1452             {
1453                 p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1454                 memcpy( p_tk->fmt.p_extra, &p_wf[1], p_tk->fmt.i_extra );
1455             }
1456         }
1457     }
1458     else if( !strcmp( p_tk->psz_codec, "A_MPEG/L3" ) ||
1459              !strcmp( p_tk->psz_codec, "A_MPEG/L2" ) ||
1460              !strcmp( p_tk->psz_codec, "A_MPEG/L1" ) )
1461     {
1462         p_tk->fmt.i_codec = VLC_CODEC_MPGA;
1463     }
1464     else if( !strcmp( p_tk->psz_codec, "A_AC3" ) )
1465     {
1466         p_tk->fmt.i_codec = VLC_CODEC_A52;
1467     }
1468     else if( !strcmp( p_tk->psz_codec, "A_EAC3" ) )
1469     {
1470         p_tk->fmt.i_codec = VLC_CODEC_EAC3;
1471     }
1472     else if( !strcmp( p_tk->psz_codec, "A_DTS" ) )
1473     {
1474         p_tk->fmt.i_codec = VLC_CODEC_DTS;
1475     }
1476     else if( !strcmp( p_tk->psz_codec, "A_MLP" ) )
1477     {
1478         p_tk->fmt.i_codec = VLC_CODEC_MLP;
1479     }
1480     else if( !strcmp( p_tk->psz_codec, "A_TRUEHD" ) )
1481     {
1482         /* FIXME when more samples arrive */
1483         p_tk->fmt.i_codec = VLC_CODEC_TRUEHD;
1484         p_fmt->b_packetized = false;
1485     }
1486     else if( !strcmp( p_tk->psz_codec, "A_FLAC" ) )
1487     {
1488         p_tk->fmt.i_codec = VLC_CODEC_FLAC;
1489         fill_extra_data( p_tk, 8 );
1490     }
1491     else if( !strcmp( p_tk->psz_codec, "A_VORBIS" ) )
1492     {
1493         p_tk->fmt.i_codec = VLC_CODEC_VORBIS;
1494         fill_extra_data( p_tk, 0 );
1495     }
1496     else if( !strncmp( p_tk->psz_codec, "A_OPUS", 6 ) )
1497     {
1498         p_tk->fmt.i_codec = VLC_CODEC_OPUS;
1499         if( !p_tk->fmt.audio.i_rate )
1500         {
1501             msg_Err( &sys.demuxer,"No sampling rate, defaulting to 48kHz");
1502             p_tk->fmt.audio.i_rate = 48000;
1503         }
1504         const uint8_t tags[16] = {'O','p','u','s','T','a','g','s',
1505                                    0, 0, 0, 0, 0, 0, 0, 0};
1506         unsigned ps[2] = { p_tk->i_extra_data, 16 };
1507         const void *pkt[2] = { (const void *)p_tk->p_extra_data,
1508                               (const void *) tags };
1509
1510         if( xiph_PackHeaders( &p_tk->fmt.i_extra,
1511                               &p_tk->fmt.p_extra,
1512                               ps, pkt, 2 ) )
1513             msg_Err( &sys.demuxer, "Couldn't pack OPUS headers");
1514
1515     }
1516     else if( !strncmp( p_tk->psz_codec, "A_AAC/MPEG2/", strlen( "A_AAC/MPEG2/" ) ) ||
1517              !strncmp( p_tk->psz_codec, "A_AAC/MPEG4/", strlen( "A_AAC/MPEG4/" ) ) )
1518     {
1519         int i_profile, i_srate, sbr = 0;
1520         static const unsigned int i_sample_rates[] =
1521         {
1522             96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050,
1523             16000, 12000, 11025,  8000,  7350,     0,     0,     0
1524         };
1525
1526         p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1527         /* create data for faad (MP4DecSpecificDescrTag)*/
1528
1529         if( !strcmp( &p_tk->psz_codec[12], "MAIN" ) )
1530         {
1531             i_profile = 0;
1532         }
1533         else if( !strcmp( &p_tk->psz_codec[12], "LC" ) )
1534         {
1535             i_profile = 1;
1536         }
1537         else if( !strcmp( &p_tk->psz_codec[12], "SSR" ) )
1538         {
1539             i_profile = 2;
1540         }
1541         else if( !strcmp( &p_tk->psz_codec[12], "LC/SBR" ) )
1542         {
1543             i_profile = 1;
1544             sbr = 1;
1545         }
1546         else
1547         {
1548             i_profile = 3;
1549         }
1550
1551         for( i_srate = 0; i_srate < 13; i_srate++ )
1552         {
1553             if( i_sample_rates[i_srate] == p_tk->i_original_rate )
1554             {
1555                 break;
1556             }
1557         }
1558         msg_Dbg( &sys.demuxer, "profile=%d srate=%d", i_profile, i_srate );
1559
1560         p_tk->fmt.i_extra = sbr ? 5 : 2;
1561         p_tk->fmt.p_extra = xmalloc( p_tk->fmt.i_extra );
1562         ((uint8_t*)p_tk->fmt.p_extra)[0] = ((i_profile + 1) << 3) | ((i_srate&0xe) >> 1);
1563         ((uint8_t*)p_tk->fmt.p_extra)[1] = ((i_srate & 0x1) << 7) | (p_tk->fmt.audio.i_channels << 3);
1564         if (sbr != 0)
1565         {
1566             int syncExtensionType = 0x2B7;
1567             int iDSRI;
1568             for (iDSRI=0; iDSRI<13; iDSRI++)
1569                 if( i_sample_rates[iDSRI] == p_tk->fmt.audio.i_rate )
1570                     break;
1571             ((uint8_t*)p_tk->fmt.p_extra)[2] = (syncExtensionType >> 3) & 0xFF;
1572             ((uint8_t*)p_tk->fmt.p_extra)[3] = ((syncExtensionType & 0x7) << 5) | 5;
1573             ((uint8_t*)p_tk->fmt.p_extra)[4] = ((1 & 0x1) << 7) | (iDSRI << 3);
1574         }
1575     }
1576     else if( !strcmp( p_tk->psz_codec, "A_AAC" ) )
1577     {
1578         p_tk->fmt.i_codec = VLC_CODEC_MP4A;
1579         fill_extra_data( p_tk, 0 );
1580     }
1581     else if( !strcmp( p_tk->psz_codec, "A_ALAC" ) )
1582     {
1583         p_tk->fmt.i_codec =  VLC_CODEC_ALAC;
1584         fill_extra_data( p_tk, 0 );
1585     }
1586     else if( !strcmp( p_tk->psz_codec, "A_WAVPACK4" ) )
1587     {
1588         p_tk->fmt.i_codec = VLC_CODEC_WAVPACK;
1589         fill_extra_data( p_tk, 0 );
1590     }
1591     else if( !strcmp( p_tk->psz_codec, "A_TTA1" ) )
1592     {
1593         p_fmt->i_codec = VLC_CODEC_TTA;
1594         if( p_tk->i_extra_data > 0 )
1595         {
1596             fill_extra_data( p_tk, 0 );
1597         }
1598         else
1599         {
1600             p_fmt->i_extra = 30;
1601             p_fmt->p_extra = xmalloc( p_fmt->i_extra );
1602             uint8_t *p_extra = (uint8_t*)p_fmt->p_extra;
1603             memcpy( &p_extra[ 0], "TTA1", 4 );
1604             SetWLE( &p_extra[ 4], 1 );
1605             SetWLE( &p_extra[ 6], p_fmt->audio.i_channels );
1606             SetWLE( &p_extra[ 8], p_fmt->audio.i_bitspersample );
1607             SetDWLE( &p_extra[10], p_fmt->audio.i_rate );
1608             SetDWLE( &p_extra[14], 0xffffffff );
1609             memset( &p_extra[18], 0, 30  - 18 );
1610         }
1611     }
1612     else if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) ||
1613              !strcmp( p_tk->psz_codec, "A_PCM/INT/LIT" ) ||
1614              !strcmp( p_tk->psz_codec, "A_PCM/FLOAT/IEEE" ) )
1615     {
1616         if( !strcmp( p_tk->psz_codec, "A_PCM/INT/BIG" ) )
1617         {
1618             p_tk->fmt.i_codec = VLC_FOURCC( 't', 'w', 'o', 's' );
1619         }
1620         else
1621         {
1622             p_tk->fmt.i_codec = VLC_FOURCC( 'a', 'r', 'a', 'w' );
1623         }
1624         p_tk->fmt.audio.i_blockalign = ( p_tk->fmt.audio.i_bitspersample + 7 ) / 8 * p_tk->fmt.audio.i_channels;
1625     }
1626     else if( !strncmp( p_tk->psz_codec, "A_REAL/", 7 ) )
1627     {
1628         if( !strcmp( p_tk->psz_codec, "A_REAL/14_4" ) )
1629         {
1630             p_fmt->i_codec = VLC_CODEC_RA_144;
1631             p_fmt->audio.i_channels = 1;
1632             p_fmt->audio.i_rate = 8000;
1633             p_fmt->audio.i_blockalign = 0x14;
1634         }
1635         else if( p_tk->i_extra_data > 28 )
1636         {
1637             uint8_t *p = p_tk->p_extra_data;
1638             if( memcmp( p, ".ra", 3 ) ) {
1639                 msg_Err( &sys.demuxer, "Invalid Real ExtraData 0x%4.4s", (char *)p );
1640                 p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1641             }
1642             else
1643             {
1644                 real_audio_private * priv = (real_audio_private*) p_tk->p_extra_data;
1645                 if( !strcmp( p_tk->psz_codec, "A_REAL/COOK" ) )
1646                 {
1647                     p_tk->fmt.i_codec = VLC_CODEC_COOK;
1648                     p_tk->fmt.audio.i_blockalign = hton16(priv->sub_packet_size);
1649                 }
1650                 else if( !strcmp( p_tk->psz_codec, "A_REAL/ATRC" ) )
1651                     p_tk->fmt.i_codec = VLC_CODEC_ATRAC3;
1652                 else if( !strcmp( p_tk->psz_codec, "A_REAL/28_8" ) )
1653                     p_tk->fmt.i_codec = VLC_CODEC_RA_288;
1654                 /* FIXME RALF and SIPR */
1655                 uint16_t version = (uint16_t) hton16(priv->version);
1656                 p_tk->p_sys =
1657                     new Cook_PrivateTrackData( hton16(priv->sub_packet_h),
1658                                                hton16(priv->frame_size),
1659                                                hton16(priv->sub_packet_size));
1660                 if( unlikely( !p_tk->p_sys ) )
1661                     return 1;
1662
1663                 if( unlikely( p_tk->p_sys->Init() ) )
1664                     return 1;
1665
1666                 if( version == 4 )
1667                 {
1668                     real_audio_private_v4 * v4 = (real_audio_private_v4*) priv;
1669                     p_tk->fmt.audio.i_channels = hton16(v4->channels);
1670                     p_tk->fmt.audio.i_bitspersample = hton16(v4->sample_size);
1671                     p_tk->fmt.audio.i_rate = hton16(v4->sample_rate);
1672                 }
1673                 else if( version == 5 )
1674                 {
1675                     real_audio_private_v5 * v5 = (real_audio_private_v5*) priv;
1676                     p_tk->fmt.audio.i_channels = hton16(v5->channels);
1677                     p_tk->fmt.audio.i_bitspersample = hton16(v5->sample_size);
1678                     p_tk->fmt.audio.i_rate = hton16(v5->sample_rate);
1679                 }
1680                 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);
1681
1682                 fill_extra_data( p_tk, p_tk->fmt.i_codec == VLC_CODEC_RA_288 ? 0 : 78);
1683             }
1684         }
1685     }
1686     else if( !strcmp( p_tk->psz_codec, "S_KATE" ) )
1687     {
1688         p_tk->fmt.i_codec = VLC_CODEC_KATE;
1689         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1690
1691         fill_extra_data( p_tk, 0 );
1692     }
1693     else if( !strcmp( p_tk->psz_codec, "S_TEXT/ASCII" ) )
1694     {
1695         p_fmt->i_codec = VLC_CODEC_SUBT;
1696         p_fmt->subs.psz_encoding = strdup( "ASCII" );
1697     }
1698     else if( !strcmp( p_tk->psz_codec, "S_TEXT/UTF8" ) )
1699     {
1700         p_tk->fmt.i_codec = VLC_CODEC_SUBT;
1701         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1702     }
1703     else if( !strcmp( p_tk->psz_codec, "S_TEXT/USF" ) )
1704     {
1705         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 's', 'f', ' ' );
1706         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1707         if( p_tk->i_extra_data )
1708             fill_extra_data( p_tk, 0 );
1709     }
1710     else if( !strcmp( p_tk->psz_codec, "S_TEXT/SSA" ) ||
1711              !strcmp( p_tk->psz_codec, "S_TEXT/ASS" ) ||
1712              !strcmp( p_tk->psz_codec, "S_SSA" ) ||
1713              !strcmp( p_tk->psz_codec, "S_ASS" ))
1714     {
1715         p_tk->fmt.i_codec = VLC_CODEC_SSA;
1716         p_tk->fmt.subs.psz_encoding = strdup( "UTF-8" );
1717         if( p_tk->i_extra_data )
1718             fill_extra_data( p_tk, 0 );
1719     }
1720     else if( !strcmp( p_tk->psz_codec, "S_VOBSUB" ) )
1721     {
1722         p_tk->fmt.i_codec = VLC_CODEC_SPU;
1723         if( p_tk->i_extra_data )
1724         {
1725             char *psz_start;
1726             char *psz_buf = (char *)malloc( p_tk->i_extra_data + 1);
1727             if( psz_buf != NULL )
1728             {
1729                 memcpy( psz_buf, p_tk->p_extra_data , p_tk->i_extra_data );
1730                 psz_buf[p_tk->i_extra_data] = '\0';
1731
1732                 psz_start = strstr( psz_buf, "size:" );
1733                 if( psz_start &&
1734                     vobsub_size_parse( psz_start,
1735                                        &p_tk->fmt.subs.spu.i_original_frame_width,
1736                                        &p_tk->fmt.subs.spu.i_original_frame_height ) == VLC_SUCCESS )
1737                 {
1738                     msg_Dbg( &sys.demuxer, "original frame size vobsubs: %dx%d",
1739                              p_tk->fmt.subs.spu.i_original_frame_width,
1740                              p_tk->fmt.subs.spu.i_original_frame_height );
1741                 }
1742                 else
1743                 {
1744                     msg_Warn( &sys.demuxer, "reading original frame size for vobsub failed" );
1745                     return 1;
1746                 }
1747
1748                 psz_start = strstr( psz_buf, "palette:" );
1749                 if( psz_start &&
1750                     vobsub_palette_parse( psz_start, &p_tk->fmt.subs.spu.palette[1] ) == VLC_SUCCESS )
1751                 {
1752                     p_tk->fmt.subs.spu.palette[0] =  0xBeef;
1753                     msg_Dbg( &sys.demuxer, "vobsub palette read" );
1754                 }
1755                 else
1756                 {
1757                     msg_Warn( &sys.demuxer, "reading original palette failed" );
1758                 }
1759                 free( psz_buf );
1760             }
1761         }
1762     }
1763     else if( !strcmp( p_tk->psz_codec, "S_HDMV/PGS" ) )
1764     {
1765         p_tk->fmt.i_codec = VLC_CODEC_BD_PG;
1766     }
1767     else if( !strcmp( p_tk->psz_codec, "B_VOBBTN" ) )
1768     {
1769         p_tk->fmt.i_cat = NAV_ES;
1770     }
1771     else
1772     {
1773         msg_Err( &sys.demuxer, "unknown codec id=`%s'", p_tk->psz_codec );
1774         p_tk->fmt.i_codec = VLC_FOURCC( 'u', 'n', 'd', 'f' );
1775     }
1776     return 0;
1777 }