bd75f2fe75f6b0864b2b57ba16e1bcfa10865f7c
[vlc.git] / modules / demux / mkv / matroska_segment_parse.cpp
1 /*****************************************************************************
2  * mkv.cpp : matroska demuxer
3  *****************************************************************************
4  * Copyright (C) 2003-2004 the VideoLAN team
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
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 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 General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
23  *****************************************************************************/
24
25 #include "matroska_segment.hpp"
26
27 #include "chapters.hpp"
28
29 #include "demux.hpp"
30
31 /*****************************************************************************
32  * ParseSeekHead:
33  *****************************************************************************/
34 void matroska_segment_c::ParseSeekHead( KaxSeekHead *seekhead )
35 {
36     EbmlParser  *ep;
37     EbmlElement *l;
38     bool b_seekable;
39
40     i_seekhead_count++;
41
42     stream_Control( sys.demuxer.s, STREAM_CAN_SEEK, &b_seekable );
43     if( !b_seekable )
44         return;
45
46     ep = new EbmlParser( &es, seekhead, &sys.demuxer );
47
48     while( ( l = ep->Get() ) != NULL )
49     {
50         if( MKV_IS_ID( l, KaxSeek ) )
51         {
52             EbmlId id = EbmlVoid::ClassInfos.GlobalId;
53             int64_t i_pos = -1;
54
55             msg_Dbg( &sys.demuxer, "|   |   + Seek" );
56             ep->Down();
57             while( ( l = ep->Get() ) != NULL )
58             {
59                 if( MKV_IS_ID( l, KaxSeekID ) )
60                 {
61                     KaxSeekID &sid = *(KaxSeekID*)l;
62                     sid.ReadData( es.I_O() );
63                     id = EbmlId( sid.GetBuffer(), sid.GetSize() );
64                 }
65                 else if( MKV_IS_ID( l, KaxSeekPosition ) )
66                 {
67                     KaxSeekPosition &spos = *(KaxSeekPosition*)l;
68                     spos.ReadData( es.I_O() );
69                     i_pos = (int64_t)segment->GetGlobalPosition( uint64( spos ) );
70                 }
71                 else
72                 {
73                     /* Many mkvmerge files hit this case. It seems to be a broken SeekHead */
74                     msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name()  );
75                 }
76             }
77             ep->Up();
78
79             if( i_pos >= 0 )
80             {
81                 if( id == KaxCues::ClassInfos.GlobalId )
82                 {
83                     msg_Dbg( &sys.demuxer, "|   - cues at %"PRId64, i_pos );
84                     LoadSeekHeadItem( KaxCues::ClassInfos, i_pos );
85                 }
86                 else if( id == KaxInfo::ClassInfos.GlobalId )
87                 {
88                     msg_Dbg( &sys.demuxer, "|   - info at %"PRId64, i_pos );
89                     LoadSeekHeadItem( KaxInfo::ClassInfos, i_pos );
90                 }
91                 else if( id == KaxChapters::ClassInfos.GlobalId )
92                 {
93                     msg_Dbg( &sys.demuxer, "|   - chapters at %"PRId64, i_pos );
94                     LoadSeekHeadItem( KaxChapters::ClassInfos, i_pos );
95                 }
96                 else if( id == KaxTags::ClassInfos.GlobalId )
97                 {
98                     msg_Dbg( &sys.demuxer, "|   - tags at %"PRId64, i_pos );
99                     LoadSeekHeadItem( KaxTags::ClassInfos, i_pos );
100                 }
101                 else if( id == KaxSeekHead::ClassInfos.GlobalId )
102                 {
103                     msg_Dbg( &sys.demuxer, "|   - chained seekhead at %"PRId64, i_pos );
104                     LoadSeekHeadItem( KaxSeekHead::ClassInfos, i_pos );
105                 }
106                 else if( id == KaxTracks::ClassInfos.GlobalId )
107                 {
108                     msg_Dbg( &sys.demuxer, "|   - tracks at %"PRId64, i_pos );
109                     LoadSeekHeadItem( KaxTracks::ClassInfos, i_pos );
110                 }
111                 else if( id == KaxAttachments::ClassInfos.GlobalId )
112                 {
113                     msg_Dbg( &sys.demuxer, "|   - attachments at %"PRId64, i_pos );
114                     LoadSeekHeadItem( KaxAttachments::ClassInfos, i_pos );
115                 }
116                 else
117                     msg_Dbg( &sys.demuxer, "|   - unknown seekhead reference at %"PRId64, i_pos );
118             }
119         }
120         else
121             msg_Dbg( &sys.demuxer, "|   |   + ParseSeekHead Unknown (%s)", typeid(*l).name() );
122     }
123     delete ep;
124 }
125
126
127 /**
128  * Helper function to print the mkv parse tree
129  */
130 static void MkvTree( demux_t & demuxer, int i_level, const char *psz_format, ... )
131 {
132     va_list args;
133     if( i_level > 9 )
134     {
135         msg_Err( &demuxer, "too deep tree" );
136         return;
137     }
138     va_start( args, psz_format );
139     static const char psz_foo[] = "|   |   |   |   |   |   |   |   |   |";
140     char *psz_foo2 = (char*)malloc( i_level * 4 + 3 + strlen( psz_format ) );
141     strncpy( psz_foo2, psz_foo, 4 * i_level );
142     psz_foo2[ 4 * i_level ] = '+';
143     psz_foo2[ 4 * i_level + 1 ] = ' ';
144     strcpy( &psz_foo2[ 4 * i_level + 2 ], psz_format );
145     __msg_GenericVa( VLC_OBJECT(&demuxer),VLC_MSG_DBG, "mkv", psz_foo2, args );
146     free( psz_foo2 );
147     va_end( args );
148 }
149
150
151 /*****************************************************************************
152  * ParseTrackEntry:
153  *****************************************************************************/
154 void matroska_segment_c::ParseTrackEntry( KaxTrackEntry *m )
155 {
156     size_t i, j, k, n;
157     bool bSupported = true;
158
159     mkv_track_t *tk;
160
161     msg_Dbg( &sys.demuxer, "|   |   + Track Entry" );
162
163     tk = new mkv_track_t();
164
165     /* Init the track */
166     memset( tk, 0, sizeof( mkv_track_t ) );
167
168     es_format_Init( &tk->fmt, UNKNOWN_ES, 0 );
169     tk->fmt.psz_language = strdup("English");
170     tk->fmt.psz_description = NULL;
171
172     tk->b_default = true;
173     tk->b_enabled = true;
174     tk->b_silent = false;
175     tk->i_number = tracks.size() - 1;
176     tk->i_extra_data = 0;
177     tk->p_extra_data = NULL;
178     tk->psz_codec = NULL;
179     tk->i_default_duration = 0;
180     tk->f_timecodescale = 1.0;
181
182     tk->b_inited = false;
183     tk->i_data_init = 0;
184     tk->p_data_init = NULL;
185
186     tk->psz_codec_name = NULL;
187     tk->psz_codec_settings = NULL;
188     tk->psz_codec_info_url = NULL;
189     tk->psz_codec_download_url = NULL;
190  
191     tk->i_compression_type = MATROSKA_COMPRESSION_NONE;
192     tk->p_compression_data = NULL;
193
194     for( i = 0; i < m->ListSize(); i++ )
195     {
196         EbmlElement *l = (*m)[i];
197
198         if( MKV_IS_ID( l, KaxTrackNumber ) )
199         {
200             KaxTrackNumber &tnum = *(KaxTrackNumber*)l;
201
202             tk->i_number = uint32( tnum );
203             msg_Dbg( &sys.demuxer, "|   |   |   + Track Number=%u", uint32( tnum ) );
204         }
205         else  if( MKV_IS_ID( l, KaxTrackUID ) )
206         {
207             KaxTrackUID &tuid = *(KaxTrackUID*)l;
208
209             msg_Dbg( &sys.demuxer, "|   |   |   + Track UID=%u",  uint32( tuid ) );
210         }
211         else  if( MKV_IS_ID( l, KaxTrackType ) )
212         {
213             const char *psz_type;
214             KaxTrackType &ttype = *(KaxTrackType*)l;
215
216             switch( uint8(ttype) )
217             {
218                 case track_audio:
219                     psz_type = "audio";
220                     tk->fmt.i_cat = AUDIO_ES;
221                     break;
222                 case track_video:
223                     psz_type = "video";
224                     tk->fmt.i_cat = VIDEO_ES;
225                     break;
226                 case track_subtitle:
227                     psz_type = "subtitle";
228                     tk->fmt.i_cat = SPU_ES;
229                     break;
230                 case track_buttons:
231                     psz_type = "buttons";
232                     tk->fmt.i_cat = SPU_ES;
233                     break;
234                 default:
235                     psz_type = "unknown";
236                     tk->fmt.i_cat = UNKNOWN_ES;
237                     break;
238             }
239
240             msg_Dbg( &sys.demuxer, "|   |   |   + Track Type=%s", psz_type );
241         }
242 //        else  if( EbmlId( *l ) == KaxTrackFlagEnabled::ClassInfos.GlobalId )
243 //        {
244 //            KaxTrackFlagEnabled &fenb = *(KaxTrackFlagEnabled*)l;
245
246 //            tk->b_enabled = uint32( fenb );
247 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Enabled=%u",
248 //                     uint32( fenb )  );
249 //        }
250         else  if( MKV_IS_ID( l, KaxTrackFlagDefault ) )
251         {
252             KaxTrackFlagDefault &fdef = *(KaxTrackFlagDefault*)l;
253
254             tk->b_default = uint32( fdef );
255             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default=%u", uint32( fdef )  );
256         }
257         else  if( MKV_IS_ID( l, KaxTrackFlagLacing ) )
258         {
259             KaxTrackFlagLacing &lac = *(KaxTrackFlagLacing*)l;
260
261             msg_Dbg( &sys.demuxer, "|   |   |   + Track Lacing=%d", uint32( lac ) );
262         }
263         else  if( MKV_IS_ID( l, KaxTrackMinCache ) )
264         {
265             KaxTrackMinCache &cmin = *(KaxTrackMinCache*)l;
266
267             msg_Dbg( &sys.demuxer, "|   |   |   + Track MinCache=%d", uint32( cmin ) );
268         }
269         else  if( MKV_IS_ID( l, KaxTrackMaxCache ) )
270         {
271             KaxTrackMaxCache &cmax = *(KaxTrackMaxCache*)l;
272
273             msg_Dbg( &sys.demuxer, "|   |   |   + Track MaxCache=%d", uint32( cmax ) );
274         }
275         else  if( MKV_IS_ID( l, KaxTrackDefaultDuration ) )
276         {
277             KaxTrackDefaultDuration &defd = *(KaxTrackDefaultDuration*)l;
278
279             tk->i_default_duration = uint64(defd);
280             msg_Dbg( &sys.demuxer, "|   |   |   + Track Default Duration=%"PRId64, uint64(defd) );
281         }
282         else  if( MKV_IS_ID( l, KaxTrackTimecodeScale ) )
283         {
284             KaxTrackTimecodeScale &ttcs = *(KaxTrackTimecodeScale*)l;
285
286             tk->f_timecodescale = float( ttcs );
287             msg_Dbg( &sys.demuxer, "|   |   |   + Track TimeCodeScale=%f", tk->f_timecodescale );
288         }
289         else if( MKV_IS_ID( l, KaxTrackName ) )
290         {
291             KaxTrackName &tname = *(KaxTrackName*)l;
292
293             tk->fmt.psz_description = ToUTF8( UTFstring( tname ) );
294             msg_Dbg( &sys.demuxer, "|   |   |   + Track Name=%s", tk->fmt.psz_description );
295         }
296         else  if( MKV_IS_ID( l, KaxTrackLanguage ) )
297         {
298             KaxTrackLanguage &lang = *(KaxTrackLanguage*)l;
299
300             if ( tk->fmt.psz_language != NULL )
301                 free( tk->fmt.psz_language );
302             tk->fmt.psz_language = strdup( string( lang ).c_str() );
303             msg_Dbg( &sys.demuxer,
304                      "|   |   |   + Track Language=`%s'", tk->fmt.psz_language );
305         }
306         else  if( MKV_IS_ID( l, KaxCodecID ) )
307         {
308             KaxCodecID &codecid = *(KaxCodecID*)l;
309
310             tk->psz_codec = strdup( string( codecid ).c_str() );
311             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecId=%s", string( codecid ).c_str() );
312         }
313         else  if( MKV_IS_ID( l, KaxCodecPrivate ) )
314         {
315             KaxCodecPrivate &cpriv = *(KaxCodecPrivate*)l;
316
317             tk->i_extra_data = cpriv.GetSize();
318             if( tk->i_extra_data > 0 )
319             {
320                 tk->p_extra_data = (uint8_t*)malloc( tk->i_extra_data );
321                 memcpy( tk->p_extra_data, cpriv.GetBuffer(), tk->i_extra_data );
322             }
323             msg_Dbg( &sys.demuxer, "|   |   |   + Track CodecPrivate size=%"PRId64, cpriv.GetSize() );
324         }
325         else if( MKV_IS_ID( l, KaxCodecName ) )
326         {
327             KaxCodecName &cname = *(KaxCodecName*)l;
328
329             tk->psz_codec_name = ToUTF8( UTFstring( cname ) );
330             msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Name=%s", tk->psz_codec_name );
331         }
332         else if( MKV_IS_ID( l, KaxContentEncodings ) )
333         {
334             EbmlMaster *cencs = static_cast<EbmlMaster*>(l);
335             MkvTree( sys.demuxer, 3, "Content Encodings" );
336             if ( cencs->ListSize() > 1 )
337             {
338                 msg_Err( &sys.demuxer, "Multiple Compression method not supported" );
339                 bSupported = false;
340             }
341             for( j = 0; j < cencs->ListSize(); j++ )
342             {
343                 EbmlElement *l2 = (*cencs)[j];
344                 if( MKV_IS_ID( l2, KaxContentEncoding ) )
345                 {
346                     MkvTree( sys.demuxer, 4, "Content Encoding" );
347                     EbmlMaster *cenc = static_cast<EbmlMaster*>(l2);
348                     for( k = 0; k < cenc->ListSize(); k++ )
349                     {
350                         EbmlElement *l3 = (*cenc)[k];
351                         if( MKV_IS_ID( l3, KaxContentEncodingOrder ) )
352                         {
353                             KaxContentEncodingOrder &encord = *(KaxContentEncodingOrder*)l3;
354                             MkvTree( sys.demuxer, 5, "Order: %i", uint32( encord ) );
355                         }
356                         else if( MKV_IS_ID( l3, KaxContentEncodingScope ) )
357                         {
358                             KaxContentEncodingScope &encscope = *(KaxContentEncodingScope*)l3;
359                             MkvTree( sys.demuxer, 5, "Scope: %i", uint32( encscope ) );
360                         }
361                         else if( MKV_IS_ID( l3, KaxContentEncodingType ) )
362                         {
363                             KaxContentEncodingType &enctype = *(KaxContentEncodingType*)l3;
364                             MkvTree( sys.demuxer, 5, "Type: %i", uint32( enctype ) );
365                         }
366                         else if( MKV_IS_ID( l3, KaxContentCompression ) )
367                         {
368                             EbmlMaster *compr = static_cast<EbmlMaster*>(l3);
369                             MkvTree( sys.demuxer, 5, "Content Compression" );
370                             for( n = 0; n < compr->ListSize(); n++ )
371                             {
372                                 EbmlElement *l4 = (*compr)[n];
373                                 if( MKV_IS_ID( l4, KaxContentCompAlgo ) )
374                                 {
375                                     KaxContentCompAlgo &compalg = *(KaxContentCompAlgo*)l4;
376                                     MkvTree( sys.demuxer, 6, "Compression Algorithm: %i", uint32(compalg) );
377                                     tk->i_compression_type = uint32( compalg );
378                                     if ( ( tk->i_compression_type != MATROSKA_COMPRESSION_ZLIB ) &&
379                                          ( tk->i_compression_type != MATROSKA_COMPRESSION_HEADER ) )
380                                     {
381                                         msg_Err( &sys.demuxer, "Track Compression method %d not supported", tk->i_compression_type );
382                                         bSupported = false;
383                                     }
384                                 }
385                                 else if( MKV_IS_ID( l4, KaxContentCompSettings ) )
386                                 {
387                                     tk->p_compression_data = new KaxContentCompSettings( *(KaxContentCompSettings*)l4 );
388                                 }
389                                 else
390                                 {
391                                     MkvTree( sys.demuxer, 6, "Unknown (%s)", typeid(*l4).name() );
392                                 }
393                             }
394                         }
395                         else
396                         {
397                             MkvTree( sys.demuxer, 5, "Unknown (%s)", typeid(*l3).name() );
398                         }
399                     }
400                 }
401                 else
402                 {
403                     MkvTree( sys.demuxer, 4, "Unknown (%s)", typeid(*l2).name() );
404                 }
405             }
406         }
407 //        else if( EbmlId( *l ) == KaxCodecSettings::ClassInfos.GlobalId )
408 //        {
409 //            KaxCodecSettings &cset = *(KaxCodecSettings*)l;
410
411 //            tk->psz_codec_settings = ToUTF8( UTFstring( cset ) );
412 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Settings=%s", tk->psz_codec_settings );
413 //        }
414 //        else if( EbmlId( *l ) == KaxCodecInfoURL::ClassInfos.GlobalId )
415 //        {
416 //            KaxCodecInfoURL &ciurl = *(KaxCodecInfoURL*)l;
417
418 //            tk->psz_codec_info_url = strdup( string( ciurl ).c_str() );
419 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_info_url );
420 //        }
421 //        else if( EbmlId( *l ) == KaxCodecDownloadURL::ClassInfos.GlobalId )
422 //        {
423 //            KaxCodecDownloadURL &cdurl = *(KaxCodecDownloadURL*)l;
424
425 //            tk->psz_codec_download_url = strdup( string( cdurl ).c_str() );
426 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Info URL=%s", tk->psz_codec_download_url );
427 //        }
428 //        else if( EbmlId( *l ) == KaxCodecDecodeAll::ClassInfos.GlobalId )
429 //        {
430 //            KaxCodecDecodeAll &cdall = *(KaxCodecDecodeAll*)l;
431
432 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Codec Decode All=%u <== UNUSED", uint8( cdall ) );
433 //        }
434 //        else if( EbmlId( *l ) == KaxTrackOverlay::ClassInfos.GlobalId )
435 //        {
436 //            KaxTrackOverlay &tovr = *(KaxTrackOverlay*)l;
437
438 //            msg_Dbg( &sys.demuxer, "|   |   |   + Track Overlay=%u <== UNUSED", uint32( tovr ) );
439 //        }
440         else  if( MKV_IS_ID( l, KaxTrackVideo ) )
441         {
442             EbmlMaster *tkv = static_cast<EbmlMaster*>(l);
443             unsigned int j;
444             unsigned int i_crop_right = 0, i_crop_left = 0, i_crop_top = 0, i_crop_bottom = 0;
445             unsigned int i_display_unit = 0, i_display_width = 0, i_display_height = 0;
446
447             msg_Dbg( &sys.demuxer, "|   |   |   + Track Video" );
448             tk->f_fps = 0.0;
449
450             tk->fmt.video.i_frame_rate_base = (unsigned int)(tk->i_default_duration / 1000);
451             tk->fmt.video.i_frame_rate = 1000000;
452  
453             for( j = 0; j < tkv->ListSize(); j++ )
454             {
455                 EbmlElement *l = (*tkv)[j];
456 //                if( EbmlId( *el4 ) == KaxVideoFlagInterlaced::ClassInfos.GlobalId )
457 //                {
458 //                    KaxVideoFlagInterlaced &fint = *(KaxVideoFlagInterlaced*)el4;
459
460 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Interlaced=%u", uint8( fint ) );
461 //                }
462 //                else if( EbmlId( *el4 ) == KaxVideoStereoMode::ClassInfos.GlobalId )
463 //                {
464 //                    KaxVideoStereoMode &stereo = *(KaxVideoStereoMode*)el4;
465
466 //                    msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Stereo Mode=%u", uint8( stereo ) );
467 //                }
468 //                else
469                 if( MKV_IS_ID( l, KaxVideoPixelWidth ) )
470                 {
471                     KaxVideoPixelWidth &vwidth = *(KaxVideoPixelWidth*)l;
472
473                     tk->fmt.video.i_width += uint16( vwidth );
474                     msg_Dbg( &sys.demuxer, "|   |   |   |   + width=%d", uint16( vwidth ) );
475                 }
476                 else if( MKV_IS_ID( l, KaxVideoPixelHeight ) )
477                 {
478                     KaxVideoPixelWidth &vheight = *(KaxVideoPixelWidth*)l;
479
480                     tk->fmt.video.i_height += uint16( vheight );
481                     msg_Dbg( &sys.demuxer, "|   |   |   |   + height=%d", uint16( vheight ) );
482                 }
483                 else if( MKV_IS_ID( l, KaxVideoDisplayWidth ) )
484                 {
485                     KaxVideoDisplayWidth &vwidth = *(KaxVideoDisplayWidth*)l;
486
487                     i_display_width = uint16( vwidth );
488                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display width=%d", uint16( vwidth ) );
489                 }
490                 else if( MKV_IS_ID( l, KaxVideoDisplayHeight ) )
491                 {
492                     KaxVideoDisplayWidth &vheight = *(KaxVideoDisplayWidth*)l;
493
494                     i_display_height = uint16( vheight );
495                     msg_Dbg( &sys.demuxer, "|   |   |   |   + display height=%d", uint16( vheight ) );
496                 }
497                 else if( MKV_IS_ID( l, KaxVideoPixelCropBottom ) )
498                 {
499                     KaxVideoPixelCropBottom &cropval = *(KaxVideoPixelCropBottom*)l;
500
501                     i_crop_bottom = uint16( cropval );
502                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel bottom=%d", uint16( cropval ) );
503                 }
504                 else if( MKV_IS_ID( l, KaxVideoPixelCropTop ) )
505                 {
506                     KaxVideoPixelCropTop &cropval = *(KaxVideoPixelCropTop*)l;
507
508                     i_crop_top = uint16( cropval );
509                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel top=%d", uint16( cropval ) );
510                 }
511                 else if( MKV_IS_ID( l, KaxVideoPixelCropRight ) )
512                 {
513                     KaxVideoPixelCropRight &cropval = *(KaxVideoPixelCropRight*)l;
514
515                     i_crop_right = uint16( cropval );
516                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel right=%d", uint16( cropval ) );
517                 }
518                 else if( MKV_IS_ID( l, KaxVideoPixelCropLeft ) )
519                 {
520                     KaxVideoPixelCropLeft &cropval = *(KaxVideoPixelCropLeft*)l;
521
522                     i_crop_left = uint16( cropval );
523                     msg_Dbg( &sys.demuxer, "|   |   |   |   + crop pixel left=%d", uint16( cropval ) );
524                 }
525                 else if( MKV_IS_ID( l, KaxVideoFrameRate ) )
526                 {
527                     KaxVideoFrameRate &vfps = *(KaxVideoFrameRate*)l;
528
529                     tk->f_fps = float( vfps );
530                     msg_Dbg( &sys.demuxer, "   |   |   |   + fps=%f", float( vfps ) );
531                 }
532                 else if( EbmlId( *l ) == KaxVideoDisplayUnit::ClassInfos.GlobalId )
533                 {
534                     KaxVideoDisplayUnit &vdmode = *(KaxVideoDisplayUnit*)l;
535
536                     i_display_unit = uint8( vdmode );
537                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Track Video Display Unit=%s",
538                              uint8( vdmode ) == 0 ? "pixels" : ( uint8( vdmode ) == 1 ? "centimeters": "inches" ) );
539                 }
540 //                else if( EbmlId( *l ) == KaxVideoAspectRatio::ClassInfos.GlobalId )
541 //                {
542 //                    KaxVideoAspectRatio &ratio = *(KaxVideoAspectRatio*)l;
543
544 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + Track Video Aspect Ratio Type=%u", uint8( ratio ) );
545 //                }
546 //                else if( EbmlId( *l ) == KaxVideoGamma::ClassInfos.GlobalId )
547 //                {
548 //                    KaxVideoGamma &gamma = *(KaxVideoGamma*)l;
549
550 //                    msg_Dbg( &sys.demuxer, "   |   |   |   + gamma=%f", float( gamma ) );
551 //                }
552                 else
553                 {
554                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
555                 }
556             }
557             if( i_display_height && i_display_width )
558                 tk->fmt.video.i_aspect = VOUT_ASPECT_FACTOR * i_display_width / i_display_height;
559             if( i_crop_left || i_crop_right || i_crop_top || i_crop_bottom )
560             {
561                 tk->fmt.video.i_visible_width = tk->fmt.video.i_width;
562                 tk->fmt.video.i_visible_height = tk->fmt.video.i_height;
563                 tk->fmt.video.i_x_offset = i_crop_left;
564                 tk->fmt.video.i_y_offset = i_crop_top;
565                 tk->fmt.video.i_visible_width -= i_crop_left + i_crop_right;
566                 tk->fmt.video.i_visible_height -= i_crop_top + i_crop_bottom;
567             }
568             /* FIXME: i_display_* allows you to not only set DAR, but also a zoom factor.
569                we do not support this atm */
570         }
571         else  if( MKV_IS_ID( l, KaxTrackAudio ) )
572         {
573             EbmlMaster *tka = static_cast<EbmlMaster*>(l);
574             unsigned int j;
575
576             msg_Dbg( &sys.demuxer, "|   |   |   + Track Audio" );
577
578             for( j = 0; j < tka->ListSize(); j++ )
579             {
580                 EbmlElement *l = (*tka)[j];
581
582                 if( MKV_IS_ID( l, KaxAudioSamplingFreq ) )
583                 {
584                     KaxAudioSamplingFreq &afreq = *(KaxAudioSamplingFreq*)l;
585
586                     tk->i_original_rate = tk->fmt.audio.i_rate = (int)float( afreq );
587                     msg_Dbg( &sys.demuxer, "|   |   |   |   + afreq=%d", tk->fmt.audio.i_rate );
588                 }
589                 else if( MKV_IS_ID( l, KaxAudioOutputSamplingFreq ) )
590                 {
591                     KaxAudioOutputSamplingFreq &afreq = *(KaxAudioOutputSamplingFreq*)l;
592
593                     tk->fmt.audio.i_rate = (int)float( afreq );
594                     msg_Dbg( &sys.demuxer, "|   |   |   |   + aoutfreq=%d", tk->fmt.audio.i_rate );
595                 }
596                 else if( MKV_IS_ID( l, KaxAudioChannels ) )
597                 {
598                     KaxAudioChannels &achan = *(KaxAudioChannels*)l;
599
600                     tk->fmt.audio.i_channels = uint8( achan );
601                     msg_Dbg( &sys.demuxer, "|   |   |   |   + achan=%u", uint8( achan ) );
602                 }
603                 else if( MKV_IS_ID( l, KaxAudioBitDepth ) )
604                 {
605                     KaxAudioBitDepth &abits = *(KaxAudioBitDepth*)l;
606
607                     tk->fmt.audio.i_bitspersample = uint8( abits );
608                     msg_Dbg( &sys.demuxer, "|   |   |   |   + abits=%u", uint8( abits ) );
609                 }
610                 else
611                 {
612                     msg_Dbg( &sys.demuxer, "|   |   |   |   + Unknown (%s)", typeid(*l).name() );
613                 }
614             }
615         }
616         else
617         {
618             msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)",
619                      typeid(*l).name() );
620         }
621     }
622
623     if ( bSupported )
624     {
625         tracks.push_back( tk );
626     }
627     else
628     {
629         msg_Err( &sys.demuxer, "Track Entry %d not supported", tk->i_number );
630         delete tk;
631     }
632 }
633
634 /*****************************************************************************
635  * ParseTracks:
636  *****************************************************************************/
637 void matroska_segment_c::ParseTracks( KaxTracks *tracks )
638 {
639     EbmlElement *el;
640     unsigned int i;
641     int i_upper_level = 0;
642
643     /* Master elements */
644     tracks->Read( es, tracks->Generic().Context, i_upper_level, el, true );
645
646     for( i = 0; i < tracks->ListSize(); i++ )
647     {
648         EbmlElement *l = (*tracks)[i];
649
650         if( MKV_IS_ID( l, KaxTrackEntry ) )
651         {
652             ParseTrackEntry( static_cast<KaxTrackEntry *>(l) );
653         }
654         else
655         {
656             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
657         }
658     }
659 }
660
661 /*****************************************************************************
662  * ParseInfo:
663  *****************************************************************************/
664 void matroska_segment_c::ParseInfo( KaxInfo *info )
665 {
666     EbmlElement *el;
667     EbmlMaster  *m;
668     size_t i, j;
669     int i_upper_level = 0;
670
671     /* Master elements */
672     m = static_cast<EbmlMaster *>(info);
673     m->Read( es, info->Generic().Context, i_upper_level, el, true );
674
675     for( i = 0; i < m->ListSize(); i++ )
676     {
677         EbmlElement *l = (*m)[i];
678
679         if( MKV_IS_ID( l, KaxSegmentUID ) )
680         {
681             if ( p_segment_uid == NULL )
682                 p_segment_uid = new KaxSegmentUID(*static_cast<KaxSegmentUID*>(l));
683
684             msg_Dbg( &sys.demuxer, "|   |   + UID=%d", *(uint32*)p_segment_uid->GetBuffer() );
685         }
686         else if( MKV_IS_ID( l, KaxPrevUID ) )
687         {
688             if ( p_prev_segment_uid == NULL )
689                 p_prev_segment_uid = new KaxPrevUID(*static_cast<KaxPrevUID*>(l));
690
691             msg_Dbg( &sys.demuxer, "|   |   + PrevUID=%d", *(uint32*)p_prev_segment_uid->GetBuffer() );
692         }
693         else if( MKV_IS_ID( l, KaxNextUID ) )
694         {
695             if ( p_next_segment_uid == NULL )
696                 p_next_segment_uid = new KaxNextUID(*static_cast<KaxNextUID*>(l));
697
698             msg_Dbg( &sys.demuxer, "|   |   + NextUID=%d", *(uint32*)p_next_segment_uid->GetBuffer() );
699         }
700         else if( MKV_IS_ID( l, KaxTimecodeScale ) )
701         {
702             KaxTimecodeScale &tcs = *(KaxTimecodeScale*)l;
703
704             i_timescale = uint64(tcs);
705
706             msg_Dbg( &sys.demuxer, "|   |   + TimecodeScale=%"PRId64,
707                      i_timescale );
708         }
709         else if( MKV_IS_ID( l, KaxDuration ) )
710         {
711             KaxDuration &dur = *(KaxDuration*)l;
712
713             i_duration = mtime_t( double( dur ) );
714
715             msg_Dbg( &sys.demuxer, "|   |   + Duration=%"PRId64,
716                      i_duration );
717         }
718         else if( MKV_IS_ID( l, KaxMuxingApp ) )
719         {
720             KaxMuxingApp &mapp = *(KaxMuxingApp*)l;
721
722             psz_muxing_application = ToUTF8( UTFstring( mapp ) );
723
724             msg_Dbg( &sys.demuxer, "|   |   + Muxing Application=%s",
725                      psz_muxing_application );
726         }
727         else if( MKV_IS_ID( l, KaxWritingApp ) )
728         {
729             KaxWritingApp &wapp = *(KaxWritingApp*)l;
730
731             psz_writing_application = ToUTF8( UTFstring( wapp ) );
732
733             msg_Dbg( &sys.demuxer, "|   |   + Writing Application=%s",
734                      psz_writing_application );
735         }
736         else if( MKV_IS_ID( l, KaxSegmentFilename ) )
737         {
738             KaxSegmentFilename &sfn = *(KaxSegmentFilename*)l;
739
740             psz_segment_filename = ToUTF8( UTFstring( sfn ) );
741
742             msg_Dbg( &sys.demuxer, "|   |   + Segment Filename=%s",
743                      psz_segment_filename );
744         }
745         else if( MKV_IS_ID( l, KaxTitle ) )
746         {
747             KaxTitle &title = *(KaxTitle*)l;
748
749             psz_title = ToUTF8( UTFstring( title ) );
750
751             msg_Dbg( &sys.demuxer, "|   |   + Title=%s", psz_title );
752         }
753         else if( MKV_IS_ID( l, KaxSegmentFamily ) )
754         {
755             KaxSegmentFamily *uid = static_cast<KaxSegmentFamily*>(l);
756
757             families.push_back( new KaxSegmentFamily(*uid) );
758
759             msg_Dbg( &sys.demuxer, "|   |   + family=%d", *(uint32*)uid->GetBuffer() );
760         }
761 #if defined( HAVE_GMTIME_R )
762         else if( MKV_IS_ID( l, KaxDateUTC ) )
763         {
764             KaxDateUTC &date = *(KaxDateUTC*)l;
765             time_t i_date;
766             struct tm tmres;
767             char   buffer[256];
768
769             i_date = date.GetEpochDate();
770             memset( buffer, 0, 256 );
771             if( gmtime_r( &i_date, &tmres ) &&
772                 asctime_r( &tmres, buffer ) )
773             {
774                 buffer[strlen( buffer)-1]= '\0';
775                 psz_date_utc = strdup( buffer );
776                 msg_Dbg( &sys.demuxer, "|   |   + Date=%s", psz_date_utc );
777             }
778         }
779 #endif
780         else if( MKV_IS_ID( l, KaxChapterTranslate ) )
781         {
782             KaxChapterTranslate *p_trans = static_cast<KaxChapterTranslate*>( l );
783             chapter_translation_c *p_translate = new chapter_translation_c();
784
785             p_trans->Read( es, p_trans->Generic().Context, i_upper_level, el, true );
786             for( j = 0; j < p_trans->ListSize(); j++ )
787             {
788                 EbmlElement *l = (*p_trans)[j];
789
790                 if( MKV_IS_ID( l, KaxChapterTranslateEditionUID ) )
791                 {
792                     p_translate->editions.push_back( uint64( *static_cast<KaxChapterTranslateEditionUID*>( l ) ) );
793                 }
794                 else if( MKV_IS_ID( l, KaxChapterTranslateCodec ) )
795                 {
796                     p_translate->codec_id = uint32( *static_cast<KaxChapterTranslateCodec*>( l ) );
797                 }
798                 else if( MKV_IS_ID( l, KaxChapterTranslateID ) )
799                 {
800                     p_translate->p_translated = new KaxChapterTranslateID( *static_cast<KaxChapterTranslateID*>( l ) );
801                 }
802             }
803
804             translations.push_back( p_translate );
805         }
806         else
807         {
808             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
809         }
810     }
811
812     double f_dur = double(i_duration) * double(i_timescale) / 1000000.0;
813     i_duration = mtime_t(f_dur);
814 }
815
816
817 /*****************************************************************************
818  * ParseChapterAtom
819  *****************************************************************************/
820 void matroska_segment_c::ParseChapterAtom( int i_level, KaxChapterAtom *ca, chapter_item_c & chapters )
821 {
822     size_t i, j;
823
824     msg_Dbg( &sys.demuxer, "|   |   |   + ChapterAtom (level=%d)", i_level );
825     for( i = 0; i < ca->ListSize(); i++ )
826     {
827         EbmlElement *l = (*ca)[i];
828
829         if( MKV_IS_ID( l, KaxChapterUID ) )
830         {
831             chapters.i_uid = uint64_t(*(KaxChapterUID*)l);
832             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterUID: %lld", chapters.i_uid );
833         }
834         else if( MKV_IS_ID( l, KaxChapterFlagHidden ) )
835         {
836             KaxChapterFlagHidden &flag =*(KaxChapterFlagHidden*)l;
837             chapters.b_display_seekpoint = uint8( flag ) == 0;
838
839             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterFlagHidden: %s", chapters.b_display_seekpoint ? "no":"yes" );
840         }
841         else if( MKV_IS_ID( l, KaxChapterTimeStart ) )
842         {
843             KaxChapterTimeStart &start =*(KaxChapterTimeStart*)l;
844             chapters.i_start_time = uint64( start ) / INT64_C(1000);
845
846             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeStart: %lld", chapters.i_start_time );
847         }
848         else if( MKV_IS_ID( l, KaxChapterTimeEnd ) )
849         {
850             KaxChapterTimeEnd &end =*(KaxChapterTimeEnd*)l;
851             chapters.i_end_time = uint64( end ) / INT64_C(1000);
852
853             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterTimeEnd: %lld", chapters.i_end_time );
854         }
855         else if( MKV_IS_ID( l, KaxChapterDisplay ) )
856         {
857             EbmlMaster *cd = static_cast<EbmlMaster *>(l);
858
859             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterDisplay" );
860             for( j = 0; j < cd->ListSize(); j++ )
861             {
862                 EbmlElement *l= (*cd)[j];
863
864                 if( MKV_IS_ID( l, KaxChapterString ) )
865                 {
866                     int k;
867
868                     KaxChapterString &name =*(KaxChapterString*)l;
869                     for (k = 0; k < i_level; k++)
870                         chapters.psz_name += '+';
871                     chapters.psz_name += ' ';
872                     char *psz_tmp_utf8 = ToUTF8( UTFstring( name ) );
873                     chapters.psz_name += psz_tmp_utf8;
874                     chapters.b_user_display = true;
875
876                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterString '%s'", psz_tmp_utf8 );
877                     free( psz_tmp_utf8 );
878                 }
879                 else if( MKV_IS_ID( l, KaxChapterLanguage ) )
880                 {
881                     KaxChapterLanguage &lang =*(KaxChapterLanguage*)l;
882                     const char *psz = string( lang ).c_str();
883
884                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterLanguage '%s'", psz );
885                 }
886                 else if( MKV_IS_ID( l, KaxChapterCountry ) )
887                 {
888                     KaxChapterCountry &ct =*(KaxChapterCountry*)l;
889                     const char *psz = string( ct ).c_str();
890
891                     msg_Dbg( &sys.demuxer, "|   |   |   |   |    + ChapterCountry '%s'", psz );
892                 }
893             }
894         }
895         else if( MKV_IS_ID( l, KaxChapterProcess ) )
896         {
897             msg_Dbg( &sys.demuxer, "|   |   |   |   + ChapterProcess" );
898
899             KaxChapterProcess *cp = static_cast<KaxChapterProcess *>(l);
900             chapter_codec_cmds_c *p_ccodec = NULL;
901
902             for( j = 0; j < cp->ListSize(); j++ )
903             {
904                 EbmlElement *k= (*cp)[j];
905
906                 if( MKV_IS_ID( k, KaxChapterProcessCodecID ) )
907                 {
908                     KaxChapterProcessCodecID *p_codec_id = static_cast<KaxChapterProcessCodecID*>( k );
909                     if ( uint32(*p_codec_id) == 0 )
910                         p_ccodec = new matroska_script_codec_c( sys );
911                     else if ( uint32(*p_codec_id) == 1 )
912                         p_ccodec = new dvd_chapter_codec_c( sys );
913                     break;
914                 }
915             }
916
917             if ( p_ccodec != NULL )
918             {
919                 for( j = 0; j < cp->ListSize(); j++ )
920                 {
921                     EbmlElement *k= (*cp)[j];
922
923                     if( MKV_IS_ID( k, KaxChapterProcessPrivate ) )
924                     {
925                         KaxChapterProcessPrivate * p_private = static_cast<KaxChapterProcessPrivate*>( k );
926                         p_ccodec->SetPrivate( *p_private );
927                     }
928                     else if( MKV_IS_ID( k, KaxChapterProcessCommand ) )
929                     {
930                         p_ccodec->AddCommand( *static_cast<KaxChapterProcessCommand*>( k ) );
931                     }
932                 }
933                 chapters.codecs.push_back( p_ccodec );
934             }
935         }
936         else if( MKV_IS_ID( l, KaxChapterAtom ) )
937         {
938             chapter_item_c *new_sub_chapter = new chapter_item_c();
939             ParseChapterAtom( i_level+1, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
940             new_sub_chapter->psz_parent = &chapters;
941             chapters.sub_chapters.push_back( new_sub_chapter );
942         }
943     }
944 }
945
946 /*****************************************************************************
947  * ParseAttachments:
948  *****************************************************************************/
949 void matroska_segment_c::ParseAttachments( KaxAttachments *attachments )
950 {
951     EbmlElement *el;
952     int i_upper_level = 0;
953
954     attachments->Read( es, attachments->Generic().Context, i_upper_level, el, true );
955
956     KaxAttached *attachedFile = FindChild<KaxAttached>( *attachments );
957
958     while( attachedFile && ( attachedFile->GetSize() > 0 ) )
959     {
960         std::string psz_mime_type  = GetChild<KaxMimeType>( *attachedFile );
961         KaxFileName  &file_name    = GetChild<KaxFileName>( *attachedFile );
962         KaxFileData  &img_data     = GetChild<KaxFileData>( *attachedFile );
963
964         attachment_c *new_attachment = new attachment_c();
965
966         if( new_attachment )
967         {
968             new_attachment->psz_file_name  = ToUTF8( UTFstring( file_name ) );
969             new_attachment->psz_mime_type  = psz_mime_type;
970             new_attachment->i_size         = img_data.GetSize();
971             new_attachment->p_data         = malloc( img_data.GetSize() );
972
973             if( new_attachment->p_data )
974             {
975                 memcpy( new_attachment->p_data, img_data.GetBuffer(), img_data.GetSize() );
976                 sys.stored_attachments.push_back( new_attachment );
977             }
978             else
979             {
980                 delete new_attachment;
981             }
982         }
983
984         attachedFile = &GetNextChild<KaxAttached>( *attachments, *attachedFile );
985     }
986 }
987
988 /*****************************************************************************
989  * ParseChapters:
990  *****************************************************************************/
991 void matroska_segment_c::ParseChapters( KaxChapters *chapters )
992 {
993     EbmlElement *el;
994     size_t i;
995     int i_upper_level = 0;
996     mtime_t i_dur;
997
998     /* Master elements */
999     chapters->Read( es, chapters->Generic().Context, i_upper_level, el, true );
1000
1001     for( i = 0; i < chapters->ListSize(); i++ )
1002     {
1003         EbmlElement *l = (*chapters)[i];
1004
1005         if( MKV_IS_ID( l, KaxEditionEntry ) )
1006         {
1007             chapter_edition_c *p_edition = new chapter_edition_c();
1008  
1009             EbmlMaster *E = static_cast<EbmlMaster *>(l );
1010             size_t j;
1011             msg_Dbg( &sys.demuxer, "|   |   + EditionEntry" );
1012             for( j = 0; j < E->ListSize(); j++ )
1013             {
1014                 EbmlElement *l = (*E)[j];
1015
1016                 if( MKV_IS_ID( l, KaxChapterAtom ) )
1017                 {
1018                     chapter_item_c *new_sub_chapter = new chapter_item_c();
1019                     ParseChapterAtom( 0, static_cast<KaxChapterAtom *>(l), *new_sub_chapter );
1020                     p_edition->sub_chapters.push_back( new_sub_chapter );
1021                 }
1022                 else if( MKV_IS_ID( l, KaxEditionUID ) )
1023                 {
1024                     p_edition->i_uid = uint64(*static_cast<KaxEditionUID *>( l ));
1025                 }
1026                 else if( MKV_IS_ID( l, KaxEditionFlagOrdered ) )
1027                 {
1028                     p_edition->b_ordered = config_GetInt( &sys.demuxer, "mkv-use-ordered-chapters" ) ? (uint8(*static_cast<KaxEditionFlagOrdered *>( l )) != 0) : 0;
1029                 }
1030                 else if( MKV_IS_ID( l, KaxEditionFlagDefault ) )
1031                 {
1032                     if (uint8(*static_cast<KaxEditionFlagDefault *>( l )) != 0)
1033                         i_default_edition = stored_editions.size();
1034                 }
1035                 else
1036                 {
1037                     msg_Dbg( &sys.demuxer, "|   |   |   + Unknown (%s)", typeid(*l).name() );
1038                 }
1039             }
1040             stored_editions.push_back( p_edition );
1041         }
1042         else
1043         {
1044             msg_Dbg( &sys.demuxer, "|   |   + Unknown (%s)", typeid(*l).name() );
1045         }
1046     }
1047
1048     for( i = 0; i < stored_editions.size(); i++ )
1049     {
1050         stored_editions[i]->RefreshChapters( );
1051     }
1052  
1053     if ( stored_editions.size() != 0 && stored_editions[i_default_edition]->b_ordered )
1054     {
1055         /* update the duration of the segment according to the sum of all sub chapters */
1056         i_dur = stored_editions[i_default_edition]->Duration() / INT64_C(1000);
1057         if (i_dur > 0)
1058             i_duration = i_dur;
1059     }
1060 }
1061
1062 void matroska_segment_c::ParseCluster( )
1063 {
1064     EbmlElement *el;
1065     EbmlMaster  *m;
1066     unsigned int i;
1067     int i_upper_level = 0;
1068
1069     /* Master elements */
1070     m = static_cast<EbmlMaster *>( cluster );
1071     m->Read( es, cluster->Generic().Context, i_upper_level, el, true );
1072
1073     for( i = 0; i < m->ListSize(); i++ )
1074     {
1075         EbmlElement *l = (*m)[i];
1076
1077         if( MKV_IS_ID( l, KaxClusterTimecode ) )
1078         {
1079             KaxClusterTimecode &ctc = *(KaxClusterTimecode*)l;
1080
1081             cluster->InitTimecode( uint64( ctc ), i_timescale );
1082             break;
1083         }
1084     }
1085
1086     i_start_time = cluster->GlobalTimecode() / 1000;
1087 }
1088
1089