-
Notifications
You must be signed in to change notification settings - Fork 7
/
MatroskaImportPrivate.cpp
1446 lines (1206 loc) · 47.4 KB
/
MatroskaImportPrivate.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* MatroskaImportPrivate.cpp
*
* MatroskaImportPrivate.cpp - C++ code for interfacing with libmatroska to import.
*
*
* Copyright (c) 2006 David Conrad
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation;
* version 2.1 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include <QuickTime/QuickTime.h>
#include <vector>
#include <string>
#include <ebml/EbmlHead.h>
#include <ebml/EbmlSubHead.h>
#include <matroska/KaxSegment.h>
#include <matroska/KaxSeekHead.h>
#include <matroska/KaxInfo.h>
#include <matroska/KaxInfoData.h>
#include <matroska/KaxTracks.h>
#include <matroska/KaxTrackVideo.h>
#include <matroska/KaxTrackAudio.h>
#include <matroska/KaxChapters.h>
#include <matroska/KaxCluster.h>
#include <matroska/KaxBlock.h>
#include <matroska/KaxAttachments.h>
#include <matroska/KaxAttached.h>
#include "MatroskaImport.h"
#include "MatroskaCodecIDs.h"
#include "SubImport.h"
#include "SubRenderer.h"
#include "CommonUtils.h"
#include "Codecprintf.h"
#include "bitstream_info.h"
#include "CompressCodecUtils.h"
extern "C" {
#include <libavutil/avutil.h>
#include "ff_private.h"
#undef CodecType
}
using namespace std;
using namespace libmatroska;
bool MatroskaImport::OpenFile()
{
bool valid = true;
int upperLevel = 0;
ioHandler = new DataHandlerCallback(dataRef, dataRefType, MODE_READ);
aStream = new EbmlStream(*ioHandler);
el_l0 = aStream->FindNextID(EbmlHead::ClassInfos, ~0);
if (el_l0 != NULL) {
EbmlElement *dummyElt = NULL;
el_l0->Read(*aStream, EbmlHead::ClassInfos.Context, upperLevel, dummyElt, true);
if (EbmlId(*el_l0) != EBML_ID(EbmlHead)) {
Codecprintf(NULL, "Not a Matroska file\n");
valid = false;
goto exit;
}
EbmlHead *head = static_cast<EbmlHead *>(el_l0);
EDocType docType = GetChild<EDocType>(*head);
if (string(docType) != "matroska" && string(docType) != "webm") {
Codecprintf(NULL, "Unknown Matroska doctype\n");
valid = false;
goto exit;
}
EDocTypeReadVersion readVersion = GetChild<EDocTypeReadVersion>(*head);
if (UInt64(readVersion) > 2) {
Codecprintf(NULL, "Matroska file too new to be read\n");
valid = false;
}
} else {
Codecprintf(NULL, "Matroska file missing EBML Head\n");
valid = false;
}
exit:
delete el_l0;
el_l0 = NULL;
return valid;
}
ComponentResult MatroskaImport::ProcessLevel1Element()
{
int upperLevel = 0;
EbmlElement *dummyElt = NULL;
if (EbmlId(*el_l1) == KaxInfo::ClassInfos.GlobalId) {
el_l1->Read(*aStream, KaxInfo::ClassInfos.Context, upperLevel, dummyElt, true);
return ReadSegmentInfo(*static_cast<KaxInfo *>(el_l1));
} else if (EbmlId(*el_l1) == KaxTracks::ClassInfos.GlobalId) {
el_l1->Read(*aStream, KaxTracks::ClassInfos.Context, upperLevel, dummyElt, true);
return ReadTracks(*static_cast<KaxTracks *>(el_l1));
} else if (EbmlId(*el_l1) == KaxChapters::ClassInfos.GlobalId) {
el_l1->Read(*aStream, KaxChapters::ClassInfos.Context, upperLevel, dummyElt, true);
return ReadChapters(*static_cast<KaxChapters *>(el_l1));
} else if (EbmlId(*el_l1) == KaxAttachments::ClassInfos.GlobalId) {
ComponentResult res;
el_l1->Read(*aStream, KaxAttachments::ClassInfos.Context, upperLevel, dummyElt, true);
res = ReadAttachments(*static_cast<KaxAttachments *>(el_l1));
PrerollSubtitleTracks();
return res;
} else if (EbmlId(*el_l1) == KaxSeekHead::ClassInfos.GlobalId) {
el_l1->Read(*aStream, KaxSeekHead::ClassInfos.Context, upperLevel, dummyElt, true);
return ReadMetaSeek(*static_cast<KaxSeekHead *>(el_l1));
}
return noErr;
}
ComponentResult MatroskaImport::SetupMovie()
{
ComponentResult err = noErr;
// once we've read the Tracks and Segment Info elements and Chapters if it's in the seek head,
// we don't need to read any more of the file
bool done = false;
el_l0 = aStream->FindNextID(KaxSegment::ClassInfos, ~0);
if (!el_l0) return err; // nothing in the file
segmentOffset = static_cast<KaxSegment *>(el_l0)->GetDataStart();
SetAutoTrackAlternatesEnabled(theMovie, false);
while (!done && NextLevel1Element()) {
if (EbmlId(*el_l1) == KaxCluster::ClassInfos.GlobalId) {
// all header elements are before clusters in sane files
done = true;
} else
err = ProcessLevel1Element();
if (err) return err;
}
// some final setup of info across elements since they can come in any order
for (int i = 0; i < tracks.size(); i++) {
tracks[i].timecodeScale = timecodeScale;
// chapter tracks have to be associated with other enabled tracks to display
if (chapterTrack) {
AddTrackReference(tracks[i].theTrack, chapterTrack, kTrackReferenceChapterList, NULL);
}
}
return err;
}
EbmlElement * MatroskaImport::NextLevel1Element()
{
int upperLevel = 0;
if (el_l1) {
el_l1->SkipData(*aStream, el_l1->Generic().Context);
delete el_l1;
el_l1 = NULL;
}
el_l1 = aStream->FindNextElement(el_l0->Generic().Context, upperLevel, 0xFFFFFFFFL, true);
// dummy element -> probably corrupt file, search for next element in meta seek and continue from there
if (el_l1 && el_l1->IsDummy()) {
vector<MatroskaSeek>::iterator nextElt;
MatroskaSeek currElt;
currElt.segmentPos = el_l1->GetElementPosition();
currElt.idLength = currElt.ebmlID = 0;
nextElt = find_if(levelOneElements.begin(), levelOneElements.end(), bind2nd(greater<MatroskaSeek>(), currElt));
if (nextElt != levelOneElements.end()) {
SetContext(nextElt->GetSeekContext(segmentOffset));
NextLevel1Element();
}
}
return el_l1;
}
ComponentResult MatroskaImport::ReadSegmentInfo(KaxInfo &segmentInfo)
{
if (seenInfo)
return noErr;
KaxDuration & duration = GetChild<KaxDuration>(segmentInfo);
KaxTimecodeScale & timecodeScale = GetChild<KaxTimecodeScale>(segmentInfo);
KaxTitle & title = GetChild<KaxTitle>(segmentInfo);
KaxWritingApp & writingApp = GetChild<KaxWritingApp>(segmentInfo);
movieDuration = Float64(duration);
this->timecodeScale = UInt64(timecodeScale);
SetMovieTimeScale(theMovie, S64Div(1000000000L, this->timecodeScale));
QTMetaDataRef movieMetaData;
OSStatus err = QTCopyMovieMetaData(theMovie, &movieMetaData);
if (err == noErr) {
OSType key;
if (!title.IsDefaultValue()) {
key = kQTMetaDataCommonKeyDisplayName;
QTMetaDataAddItem(movieMetaData,
kQTMetaDataStorageFormatQuickTime, kQTMetaDataKeyFormatCommon,
(UInt8 *)&key, sizeof(key),
(UInt8 *)UTFstring(title).GetUTF8().c_str(),
UTFstring(title).GetUTF8().size(),
kQTMetaDataTypeUTF8, NULL);
}
if (!writingApp.IsDefaultValue()) {
key = kQTMetaDataCommonKeySoftware;
QTMetaDataAddItem(movieMetaData,
kQTMetaDataStorageFormatQuickTime, kQTMetaDataKeyFormatCommon,
(UInt8 *)&key, sizeof(key),
(UInt8 *)UTFstring(writingApp).GetUTF8().c_str(),
UTFstring(writingApp).GetUTF8().size(),
kQTMetaDataTypeUTF8, NULL);
}
QTMetaDataRelease(movieMetaData);
}
seenInfo = true;
return noErr;
}
ComponentResult MatroskaImport::ReadTracks(KaxTracks &trackEntries)
{
Track firstVideoTrack = NULL; short firstVideoTrackLang = 0; bool videoEnabled = false;
Track firstAudioTrack = NULL; short firstAudioTrackLang = 0; bool audioEnabled = false;
Track firstSubtitleTrack = NULL; short firstSubtitleTrackLang = 0; bool subtitleEnabled = false;
ComponentResult err = noErr;
if (seenTracks)
return noErr;
// Since creating a subtitle track requires a video track to have already been created
// (so that it can be sized to fit exactly over the video track), we go through the
// track entries in two passes, first to add audio/video, second to add subtitle tracks.
for (int pass = 1; pass <= 2; pass++) {
for (int i = 0; i < trackEntries.ListSize(); i++) {
if (EbmlId(*trackEntries[i]) != KaxTrackEntry::ClassInfos.GlobalId)
continue;
KaxTrackEntry & track = *static_cast<KaxTrackEntry *>(trackEntries[i]);
KaxTrackNumber & number = GetChild<KaxTrackNumber>(track);
KaxTrackType & type = GetChild<KaxTrackType>(track);
KaxTrackDefaultDuration * defaultDuration = FindChild<KaxTrackDefaultDuration>(track);
KaxTrackFlagDefault & enabled = GetChild<KaxTrackFlagDefault>(track);
KaxTrackFlagLacing & lacing = GetChild<KaxTrackFlagLacing>(track);
MatroskaTrack mkvTrack;
mkvTrack.number = uint16(number);
mkvTrack.type = uint8(type);
if (defaultDuration)
mkvTrack.defaultDuration = uint32(*defaultDuration) / float(timecodeScale) + .5;
else
mkvTrack.defaultDuration = 0;
mkvTrack.isEnabled = uint8(enabled);
mkvTrack.usesLacing = uint8(lacing);
KaxTrackLanguage & trackLang = GetChild<KaxTrackLanguage>(track);
KaxTrackName & trackName = GetChild<KaxTrackName>(track);
KaxContentEncodings * encodings = FindChild<KaxContentEncodings>(track);
short qtLang = ISO639_2ToQTLangCode(string(trackLang).c_str());
switch (uint8(type)) {
case track_video:
if (pass == 2) continue;
err = AddVideoTrack(track, mkvTrack, encodings);
if (err) return err;
if (mkvTrack.isEnabled)
videoEnabled = true;
if (firstVideoTrack && qtLang != firstVideoTrackLang)
SetTrackAlternate(firstVideoTrack, mkvTrack.theTrack);
else {
firstVideoTrack = mkvTrack.theTrack;
firstVideoTrackLang = qtLang;
}
break;
case track_audio:
if (pass == 2) continue;
err = AddAudioTrack(track, mkvTrack, encodings);
if (err) return err;
if (mkvTrack.isEnabled)
audioEnabled = true;
if (firstAudioTrack && qtLang != firstAudioTrackLang)
SetTrackAlternate(firstAudioTrack, mkvTrack.theTrack);
else {
firstAudioTrack = mkvTrack.theTrack;
firstAudioTrackLang = qtLang;
}
break;
case track_subtitle:
if (pass == 1) continue;
err = AddSubtitleTrack(track, mkvTrack, encodings);
if (err) return err;
if (mkvTrack.theTrack == NULL) continue;
if (mkvTrack.isEnabled)
subtitleEnabled = true;
if (firstSubtitleTrack && qtLang != firstSubtitleTrackLang)
SetTrackAlternate(firstSubtitleTrack, mkvTrack.theTrack);
else {
firstSubtitleTrack = mkvTrack.theTrack;
firstSubtitleTrackLang = qtLang;
}
break;
case track_complex:
case track_logo:
case track_buttons:
case track_control:
// not likely to be implemented soon
default:
continue;
}
SetMediaLanguage(mkvTrack.theMedia, qtLang);
if (!trackName.IsDefaultValue()) {
QTMetaDataRef trackMetaData;
err = QTCopyTrackMetaData(mkvTrack.theTrack, &trackMetaData);
if (err == noErr) {
OSType key = 'name';
// QuickTime differentiates between the title of a track and its name
// so we set both
QTMetaDataAddItem(trackMetaData,
kQTMetaDataStorageFormatQuickTime,
kQTMetaDataKeyFormatCommon,
(UInt8 *)&key, sizeof(key),
(UInt8 *)UTFstring(trackName).GetUTF8().c_str(),
UTFstring(trackName).GetUTF8().size(),
kQTMetaDataTypeUTF8, NULL);
QTMetaDataAddItem(trackMetaData,
kQTMetaDataStorageFormatUserData,
kQTMetaDataKeyFormatUserData,
(UInt8 *)&key, sizeof(key),
(UInt8 *)UTFstring(trackName).GetUTF8().c_str(),
UTFstring(trackName).GetUTF8().size(),
kQTMetaDataTypeUTF8, NULL);
QTMetaDataRelease(trackMetaData);
}
}
tracks.push_back(mkvTrack);
}
}
for (int i = 0; i < tracks.size(); i++) {
SetTrackEnabled(tracks[i].theTrack, tracks[i].isEnabled);
}
// ffmpeg used to write a TrackDefault of 0 for all tracks
// ensure that at least one track of each media type is enabled, if none were originally
// this picks the first track, which may not be the best, but the situation is quite rare anyway
// FIXME: properly choose tracks based on forced/default/language flags, and consider turning auto-alternates back on
if (!videoEnabled && firstVideoTrack)
SetTrackEnabled(firstVideoTrack, 1);
if (!audioEnabled && firstAudioTrack)
SetTrackEnabled(firstAudioTrack, 1);
if (!subtitleEnabled && firstSubtitleTrack)
SetTrackEnabled(firstSubtitleTrack, 1);
seenTracks = true;
return noErr;
}
ComponentResult MatroskaImport::ReadVobSubContentEncodings(KaxContentEncodings *encodings, MatroskaTrack &mkvTrack)
{
KaxContentEncoding & encoding = GetChild<KaxContentEncoding>(*encodings);
int scope = uint32(GetChild<KaxContentEncodingScope>(encoding));
int type = uint32(GetChild<KaxContentEncodingType>(encoding));
if (scope != 1) {
Codecprintf(NULL, "Content encoding scope of %d not expected\n", scope);
return -1;
}
if (type != 0) {
Codecprintf(NULL, "Encrypted track\n");
return -2;
}
KaxContentCompression & comp = GetChild<KaxContentCompression>(encoding);
int algo = uint32(GetChild<KaxContentCompAlgo>(comp));
if (algo != 0)
Codecprintf(NULL, "MKV: warning, track compression algorithm %d not zlib\n", algo);
if ((*mkvTrack.desc)->dataFormat != kSubFormatVobSub)
Codecprintf(NULL, "MKV: warning, compressed track %s probably won't work (not VobSub)\n", FourCCString((*mkvTrack.desc)->dataFormat));
Handle ext = NewHandle(1);
**ext = algo;
if (mkvTrack.type == track_audio)
AddSoundDescriptionExtension((SoundDescriptionHandle)mkvTrack.desc, ext, kMKVCompressionExtension);
else
AddImageDescriptionExtension((ImageDescriptionHandle)mkvTrack.desc, ext, kMKVCompressionExtension);
return noErr;
}
ComponentResult MatroskaImport::AddVideoTrack(KaxTrackEntry &kaxTrack, MatroskaTrack &mkvTrack, KaxContentEncodings *encodings)
{
ComponentResult err = noErr;
ImageDescriptionHandle imgDesc;
Fixed width, height;
KaxTrackVideo &videoTrack = GetChild<KaxTrackVideo>(kaxTrack);
KaxVideoDisplayWidth & disp_width = GetChild<KaxVideoDisplayWidth>(videoTrack);
KaxVideoDisplayHeight & disp_height = GetChild<KaxVideoDisplayHeight>(videoTrack);
KaxVideoPixelWidth & pxl_width = GetChild<KaxVideoPixelWidth>(videoTrack);
KaxVideoPixelHeight & pxl_height = GetChild<KaxVideoPixelHeight>(videoTrack);
// Use the PixelWidth if the DisplayWidth is not set
if (disp_width.ValueIsSet() || disp_height.ValueIsSet()) {
// some files ignore the spec and treat display width/height as a ratio, not as pixels
// so scale the display size to be at least as large as the pixel size here
// but don't let it be bigger in both dimensions
uint32 displayWidth = disp_width.ValueIsSet() ? uint32(disp_width) : uint32(pxl_width);
uint32 displayHeight = disp_height.ValueIsSet() ? uint32(disp_height) : uint32(pxl_height);
float horizRatio = float(uint32(pxl_width)) / displayWidth;
float vertRatio = float(uint32(pxl_height)) / displayHeight;
if (vertRatio > horizRatio && vertRatio > 1) {
width = FloatToFixed(displayWidth * vertRatio);
height = FloatToFixed(displayHeight * vertRatio);
} else if (horizRatio > 1) {
width = FloatToFixed(displayWidth * horizRatio);
height = FloatToFixed(displayHeight * horizRatio);
} else {
float dar = displayWidth / (float)displayHeight;
float p_ratio = uint32(pxl_width) / (float)uint32(pxl_height);
if (dar > p_ratio) {
width = FloatToFixed(uint32(pxl_height) * dar);
height = IntToFixed(uint32(pxl_height));
} else {
width = IntToFixed(uint32(pxl_width));
height = FloatToFixed(uint32(pxl_width) / dar);
}
}
} else if (pxl_width.ValueIsSet() && pxl_height.ValueIsSet()) {
width = IntToFixed(uint32(pxl_width));
height = IntToFixed(uint32(pxl_height));
} else {
Codecprintf(NULL, "MKV: Video has unknown dimensions.\n");
return invalidTrack;
}
mkvTrack.theTrack = NewMovieTrack(theMovie, width, height, kNoVolume);
if (mkvTrack.theTrack == NULL)
return GetMoviesError();
mkvTrack.theMedia = NewTrackMedia(mkvTrack.theTrack, 'vide', GetMovieTimeScale(theMovie), dataRef, dataRefType);
if (mkvTrack.theMedia == NULL) {
DisposeMovieTrack(mkvTrack.theTrack);
return GetMoviesError();
}
imgDesc = (ImageDescriptionHandle) NewHandleClear(sizeof(ImageDescription));
(*imgDesc)->idSize = sizeof(ImageDescription);
(*imgDesc)->width = uint16(pxl_width);
(*imgDesc)->height = uint16(pxl_height);
(*imgDesc)->frameCount = 1;
(*imgDesc)->cType = MkvGetFourCC(&kaxTrack);
(*imgDesc)->depth = 24;
(*imgDesc)->clutID = -1;
set_track_clean_aperture_ext(imgDesc, width, height, IntToFixed(uint32(pxl_width)), IntToFixed(uint32(pxl_height)));
set_track_colorspace_ext(imgDesc, width, height);
mkvTrack.desc = (SampleDescriptionHandle) imgDesc;
// this sets up anything else needed in the description for the specific codec.
err = MkvFinishSampleDescription(&kaxTrack, (SampleDescriptionHandle) imgDesc, kToSampleDescription);
if (err) return err;
if(encodings)
{
KaxContentEncoding & encoding = GetChild<KaxContentEncoding>(*encodings);
int scope = uint32(GetChild<KaxContentEncodingScope>(encoding));
int type = uint32(GetChild<KaxContentEncodingType>(encoding));
if (scope != 1) {
Codecprintf(NULL, "Content encoding scope of %d not expected\n", scope);
}
if (type != 0) {
Codecprintf(NULL, "Encrypted track\n");
}
if(scope == 1 && type == 0)
{
KaxContentCompression & comp = GetChild<KaxContentCompression>(encoding);
int algo = uint32(GetChild<KaxContentCompAlgo>(comp));
if (algo != 3)
Codecprintf(NULL, "MKV: warning, track compression algorithm %d not stripped header\n", algo);
SampleDescriptionHandle sampleDesc = mkvTrack.desc;
OSType compressedType = compressStreamFourCC((*sampleDesc)->dataFormat);
if (compressedType == 0)
Codecprintf(NULL, "MKV: warning, compressed track %s probably won't work\n", FourCCString((*mkvTrack.desc)->dataFormat));
else
{
Handle ext = NewHandle(4);
memcpy(*ext, &algo, 4);
(*sampleDesc)->dataFormat = compressedType;
AddImageDescriptionExtension((ImageDescriptionHandle)mkvTrack.desc, ext, kCompressionAlgorithm);
DisposeHandle(ext);
KaxContentCompSettings & settings = GetChild<KaxContentCompSettings>(comp);
uint8_t *compSettings = (uint8_t *)settings.GetBuffer();
int compSize = settings.GetSize();
if(compSize > 0) {
ext = NewHandle(compSize);
memcpy(*ext, compSettings, compSize);
AddImageDescriptionExtension((ImageDescriptionHandle)mkvTrack.desc, ext, kCompressionSettingsExtension);
DisposeHandle(ext);
}
}
}
}
// video tracks can have display offsets, so create a sample table
err = QTSampleTableCreateMutable(NULL, GetMovieTimeScale(theMovie), NULL, &mkvTrack.sampleTable);
if (err) return err;
err = QTSampleTableAddSampleDescription(mkvTrack.sampleTable, mkvTrack.desc, 0, &mkvTrack.qtSampleDesc);
return err;
}
ComponentResult MatroskaImport::AddAudioTrack(KaxTrackEntry &kaxTrack, MatroskaTrack &mkvTrack, KaxContentEncodings *encodings)
{
SoundDescriptionHandle sndDesc = NULL;
AudioStreamBasicDescription asbd = {0};
AudioChannelLayout acl = {0};
AudioChannelLayout *pacl = &acl;
ByteCount acl_size = sizeof(acl);
ByteCount ioSize = sizeof(asbd);
ByteCount cookieSize = 0;
Handle cookieH = NULL;
Ptr cookie = NULL;
OSStatus err = noErr;
mkvTrack.theTrack = NewMovieTrack(theMovie, 0, 0, kFullVolume);
if (mkvTrack.theTrack == NULL)
return GetMoviesError();
mkvTrack.theMedia = NewTrackMedia(mkvTrack.theTrack, 'soun', GetMovieTimeScale(theMovie), dataRef, dataRefType);
if (mkvTrack.theMedia == NULL) {
DisposeMovieTrack(mkvTrack.theTrack);
return GetMoviesError();
}
KaxTrackAudio & audioTrack = GetChild<KaxTrackAudio>(kaxTrack);
KaxAudioSamplingFreq & sampleFreq = GetChild<KaxAudioSamplingFreq>(audioTrack);
KaxAudioChannels & numChannels = GetChild<KaxAudioChannels>(audioTrack);
KaxAudioBitDepth & bitDepth = GetChild<KaxAudioBitDepth>(audioTrack);
if (bitDepth.ValueIsSet()) asbd.mBitsPerChannel = uint32(bitDepth);
asbd.mFormatID = MkvGetFourCC(&kaxTrack);
asbd.mSampleRate = Float64(sampleFreq);
asbd.mChannelsPerFrame = uint32(numChannels);
MkvFinishAudioDescription(&kaxTrack, &cookieH, &asbd, &acl);
if (cookieH) {
cookie = *cookieH;
cookieSize = GetHandleSize(cookieH);
}
// get more info about the codec
err = AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, cookieSize, cookie, &ioSize, &asbd);
if(asbd.mChannelsPerFrame == 0 || asbd.mFormatID == 0) {
Codecprintf(NULL, "Audio channels or format not set in MKV\n");
goto err; // better to fail than import with the wrong number of channels...
}
if (err) {
Codecprintf(NULL, "AudioFormatGetProperty failed (error %lx / format %lx)\n", err, asbd.mFormatID);
}
// see ff_private.c initialize_audio_map
if (!asbd.mFramesPerPacket && asbd.mFormatID == kAudioFormatMPEGLayer3)
asbd.mFramesPerPacket = asbd.mSampleRate > 24000 ? 1152 : 576;
// FIXME: mChannelLayoutTag == 0 is valid
// but we don't use channel position lists (yet) so it's safe for now
if (acl.mChannelLayoutTag == 0) acl = GetDefaultChannelLayout(&asbd);
if (acl.mChannelLayoutTag == 0) {
pacl = NULL;
acl_size = 0;
}
if(encodings)
{
KaxContentEncoding & encoding = GetChild<KaxContentEncoding>(*encodings);
int scope = uint32(GetChild<KaxContentEncodingScope>(encoding));
int type = uint32(GetChild<KaxContentEncodingType>(encoding));
if (scope != 1) {
Codecprintf(NULL, "Content encoding scope of %d not expected\n", scope);
}
if (type != 0) {
Codecprintf(NULL, "Encrypted track\n");
}
if(scope == 1 && type == 0)
{
KaxContentCompression & comp = GetChild<KaxContentCompression>(encoding);
int algo = uint32(GetChild<KaxContentCompAlgo>(comp));
if (algo != 3)
Codecprintf(NULL, "MKV: warning, track compression algorithm %d not stripped header\n", algo);
OSType compressedType = compressStreamFourCC(asbd.mFormatID);
if (compressedType == 0)
Codecprintf(NULL, "MKV: warning, compressed track %s probably won't work\n", FourCCString(asbd.mFormatID));
else
{
asbd.mFormatID = compressedType;
uint32_t algoHeader[] = {
EndianS32_NtoB(12),
EndianS32_NtoB(kCompressionAlgorithm),
EndianS32_NtoB(algo)
};
Handle newCookieHandle;
PtrToHand(algoHeader, &newCookieHandle, sizeof(algoHeader));
KaxContentCompSettings & settings = GetChild<KaxContentCompSettings>(comp);
uint8_t *compSettings = (uint8_t *)settings.GetBuffer();
int compSize = settings.GetSize();
if(compSize > 0) {
uint32_t settingsHeader[] = {
EndianS32_NtoB(8 + compSize),
EndianS32_NtoB(kCompressionSettingsExtension),
};
PtrAndHand(settingsHeader, newCookieHandle, sizeof(settingsHeader));
PtrAndHand(compSettings, newCookieHandle, compSize);
}
if(cookieSize)
{
HandAndHand(cookieH, newCookieHandle);
DisposeHandle(cookieH);
}
cookieH = newCookieHandle;
cookie = *cookieH;
cookieSize = GetHandleSize(cookieH);
}
}
}
err = QTSoundDescriptionCreate(&asbd, pacl, acl_size, cookie, cookieSize,
kQTSoundDescriptionKind_Movie_LowestPossibleVersion, &sndDesc);
if (err) {
Codecprintf(NULL, "Borked audio track entry, hoping we can parse the track for asbd\n");
DisposeHandle((Handle)sndDesc);
return noErr;
}
mkvTrack.desc = (SampleDescriptionHandle) sndDesc;
err = QTSampleTableCreateMutable(NULL, GetMovieTimeScale(theMovie), NULL, &mkvTrack.sampleTable);
if (err) goto err;
err = QTSampleTableAddSampleDescription(mkvTrack.sampleTable, mkvTrack.desc, 0, &mkvTrack.qtSampleDesc);
err:
if (cookieH)
DisposeHandle(cookieH);
return err;
}
ComponentResult MatroskaImport::AddSubtitleTrack(KaxTrackEntry &kaxTrack, MatroskaTrack &mkvTrack, KaxContentEncodings *encodings)
{
Fixed trackWidth, trackHeight;
Rect movieBox;
MediaHandler mh;
ImageDescriptionHandle imgDesc = (ImageDescriptionHandle) NewHandleClear(sizeof(ImageDescription));
mkvTrack.desc = (SampleDescriptionHandle) imgDesc;
// we assume that a video track has already been created, so we can set the subtitle track
// to have the same dimensions as it. Note that this doesn't work so well with multiple
// video tracks with different dimensions; but QuickTime doesn't expect that; how should we handle them?
GetMovieBox(theMovie, &movieBox);
trackWidth = IntToFixed(movieBox.right - movieBox.left);
trackHeight = IntToFixed(movieBox.bottom - movieBox.top);
(*imgDesc)->idSize = sizeof(ImageDescription);
(*imgDesc)->cType = MkvGetFourCC(&kaxTrack);
(*imgDesc)->frameCount = 1;
(*imgDesc)->depth = 32;
(*imgDesc)->clutID = -1;
if ((*imgDesc)->cType == kSubFormatVobSub) {
int width, height;
// bitmap width & height is in the codec private in text format
KaxCodecPrivate & idxFile = GetChild<KaxCodecPrivate>(kaxTrack);
string idxFileStr((char *)idxFile.GetBuffer(), idxFile.GetSize());
string::size_type loc = idxFileStr.find("size:", 0);
if (loc == string::npos)
return -1;
sscanf(&idxFileStr.c_str()[loc], "size: %dx%d", &width, &height);
(*imgDesc)->width = width;
(*imgDesc)->height = height;
if (trackWidth == 0 || trackHeight == 0) {
trackWidth = IntToFixed(width);
trackHeight = IntToFixed(height);
}
set_track_colorspace_ext(imgDesc, width, height);
mkvTrack.theTrack = NewMovieTrack(theMovie, trackWidth, trackHeight, kNoVolume);
if (mkvTrack.theTrack == NULL)
return GetMoviesError();
mkvTrack.theMedia = NewTrackMedia(mkvTrack.theTrack, 'vide', GetMovieTimeScale(theMovie), dataRef, dataRefType);
if (mkvTrack.theMedia == NULL)
return GetMoviesError();
// finally, say that we're transparent
mh = GetMediaHandler(mkvTrack.theMedia);
SetSubtitleMediaHandlerTransparent(mh);
// subtitle tracks should be above the video track, which should be layer 0
SetTrackLayer(mkvTrack.theTrack, -1);
mkvTrack.is_vobsub = true;
} else if ((*imgDesc)->cType == kSubFormatUTF8 || (*imgDesc)->cType == kSubFormatSSA || (*imgDesc)->cType == kSubFormatASS) {
if ((*imgDesc)->cType == kSubFormatASS) (*imgDesc)->cType = kSubFormatSSA; // no real reason to treat them differently
UInt32 emptyDataRefExtension[2]; // FIXME: the various uses of this bit of code should be unified
mkvTrack.subDataRefHandler = NewHandleClear(sizeof(Handle) + 1);
emptyDataRefExtension[0] = EndianU32_NtoB(sizeof(UInt32)*2);
emptyDataRefExtension[1] = EndianU32_NtoB(kDataRefExtensionInitializationData);
PtrAndHand(&emptyDataRefExtension[0], mkvTrack.subDataRefHandler, sizeof(emptyDataRefExtension));
mkvTrack.theTrack = CreatePlaintextSubTrack(theMovie, imgDesc, GetMovieTimeScale(theMovie), mkvTrack.subDataRefHandler, HandleDataHandlerSubType, (*imgDesc)->cType, NULL, movieBox);
if (mkvTrack.theTrack == NULL)
return GetMoviesError();
mkvTrack.theMedia = GetTrackMedia(mkvTrack.theTrack);
mkvTrack.is_vobsub = false;
BeginMediaEdits(mkvTrack.theMedia);
} else {
Codecprintf(NULL, "MKV: Unsupported subtitle type\n");
return noErr;
}
// this sets up anything else needed in the description for the specific codec.
ComponentResult result = MkvFinishSampleDescription(&kaxTrack, (SampleDescriptionHandle) imgDesc, kToSampleDescription);
if(encodings) {
ReadVobSubContentEncodings(encodings, mkvTrack);
}
return result;
}
ComponentResult MatroskaImport::ReadChapters(KaxChapters &chapterEntries)
{
KaxEditionEntry & edition = GetChild<KaxEditionEntry>(chapterEntries);
UInt32 emptyDataRefExtension[2];
if (seenChapters)
return noErr;
chapterTrack = NewMovieTrack(theMovie, 0, 0, kNoVolume);
if (chapterTrack == NULL) {
Codecprintf(NULL, "MKV: Error creating chapter track %d\n", GetMoviesError());
return GetMoviesError();
}
// we use a handle data reference here because I don't see any way to add textual
// sample references (TextMediaAddTextSample() will behave the same as AddSample()
// in that it modifies the original file if that's the data reference of the media)
Handle dataRef = NewHandleClear(sizeof(Handle) + 1);
emptyDataRefExtension[0] = EndianU32_NtoB(sizeof(UInt32)*2);
emptyDataRefExtension[1] = EndianU32_NtoB(kDataRefExtensionInitializationData);
PtrAndHand(&emptyDataRefExtension[0], dataRef, sizeof(emptyDataRefExtension));
Media chapterMedia = NewTrackMedia(chapterTrack, TextMediaType, GetMovieTimeScale(theMovie),
dataRef, HandleDataHandlerSubType);
if (chapterMedia == NULL) {
OSErr err = GetMoviesError();
Codecprintf(NULL, "MKV: Error creating chapter media %d\n", err);
DisposeMovieTrack(chapterTrack);
return err;
}
// Name the chapter track "Chapters" for easy distinguishing
QTMetaDataRef trackMetaData;
OSErr err = QTCopyTrackMetaData(chapterTrack, &trackMetaData);
if (err == noErr) {
OSType key = kUserDataName;
string chapterName("Chapters");
QTMetaDataAddItem(trackMetaData, kQTMetaDataStorageFormatUserData,
kQTMetaDataKeyFormatUserData, (UInt8 *)&key, sizeof(key),
(UInt8 *)chapterName.c_str(), chapterName.size(),
kQTMetaDataTypeUTF8, NULL);
QTMetaDataRelease(trackMetaData);
}
BeginMediaEdits(chapterMedia);
// tell the text media handler the upcoming text samples are
// encoded in Unicode with a byte order mark (BOM)
MediaHandler mediaHandler = GetMediaHandler(chapterMedia);
SInt32 dataPtr = kTextEncodingUnicodeDefault;
TextMediaSetTextSampleData(mediaHandler, &dataPtr, kTXNTextEncodingAttribute);
KaxChapterAtom *chapterAtom = FindChild<KaxChapterAtom>(edition);
while (chapterAtom && chapterAtom->GetSize() > 0) {
AddChapterAtom(chapterAtom);
chapterAtom = &GetNextChild<KaxChapterAtom>(edition, *chapterAtom);
}
EndMediaEdits(chapterMedia);
SetTrackEnabled(chapterTrack, false);
seenChapters = true;
return noErr;
}
void MatroskaImport::AddChapterAtom(KaxChapterAtom *atom)
{
KaxChapterAtom *subChapter = FindChild<KaxChapterAtom>(*atom);
bool addThisChapter = true;
// since QuickTime only supports linear chapter tracks (no nesting), only add chapter leaves
if (subChapter && subChapter->GetSize() > 0) {
while (subChapter && subChapter->GetSize() > 0) {
KaxChapterFlagHidden &hideChapter = GetChild<KaxChapterFlagHidden>(*subChapter);
if (!uint8_t(hideChapter)) {
AddChapterAtom(subChapter);
addThisChapter = false;
}
subChapter = &GetNextChild(*atom, *subChapter);
}
}
if (addThisChapter) {
// add the chapter to the track if it has no children
KaxChapterTimeStart & startTime = GetChild<KaxChapterTimeStart>(*atom);
KaxChapterDisplay & chapDisplay = GetChild<KaxChapterDisplay>(*atom);
KaxChapterString & chapString = GetChild<KaxChapterString>(chapDisplay);
MediaHandler mh = GetMediaHandler(GetTrackMedia(chapterTrack));
TimeValue start = UInt64(startTime) / timecodeScale;
if (start > movieDuration) {
Codecprintf(NULL, "MKV: Chapter time is beyond the end of the file\n");
return;
}
Rect bounds = {0, 0, 0, 0};
TimeValue inserted;
OSErr err = TextMediaAddTextSample(mh,
const_cast<Ptr>(UTFstring(chapString).GetUTF8().c_str()),
UTFstring(chapString).GetUTF8().size(),
0, 0, 0, NULL, NULL,
teCenter, &bounds, dfClipToTextBox,
0, 0, 0, NULL, 1, &inserted);
if (err)
Codecprintf(NULL, "MKV: Error adding text sample %d\n", err);
else {
InsertMediaIntoTrack(chapterTrack, start, inserted, 1, fixed1);
}
}
}
ComponentResult MatroskaImport::ReadAttachments(KaxAttachments &attachments)
{
KaxAttached *attachedFile = FindChild<KaxAttached>(attachments);
while (attachedFile && attachedFile->GetSize() > 0) {
string fileMimeType = GetChild<KaxMimeType>(*attachedFile);
string fileName = UTFstring(GetChild<KaxFileName>(*attachedFile)).GetUTF8();
/* The only attachments handled here are fonts, which currently can be truetype or opentype.
application/x-* is probably not a permanent MIME type, but it is current practice... */
if ((fileMimeType == "application/x-truetype-font" || fileMimeType == "application/x-font-otf") &&
ShouldImportFontFileName(fileName.c_str())) {
KaxFileData & fontData = GetChild<KaxFileData>(*attachedFile);
if (fontData.GetSize()) {
ATSFontContainerRef container;
ATSFontActivateFromMemory(fontData.GetBuffer(), fontData.GetSize(), kATSFontContextLocal,
kATSFontFormatUnspecified, NULL, kATSOptionFlagsDefault, &container);
}
}
bool isCoverArt = false, isJPEG;
if (fileName == "cover.jpg") {
isCoverArt = isJPEG = true;
} else if (fileName == "cover.png") {
isCoverArt = true;
isJPEG = false;
}
if (isCoverArt) {
KaxFileData & fileData = GetChild<KaxFileData>(*attachedFile);
FourCharCode key = 'covr'; //iTunes cover art tag
QTMetaDataRef movieMetaData;
QTCopyMovieMetaData(theMovie, &movieMetaData);
OSErr err;
err = QTMetaDataAddItem(movieMetaData,
kQTMetaDataStorageFormatiTunes, kQTMetaDataKeyFormatiTunesShortForm,
(UInt8 *)&key, sizeof(key),
fileData.GetBuffer(),
fileData.GetSize(),
isJPEG ? kQTMetaDataTypeJPEGImage : kQTMetaDataTypePNGImage, NULL);
if (err)
Codecprintf(NULL, "MKV: Error adding cover art %d\n", (int)err);
QTMetaDataRelease(movieMetaData);
}
attachedFile = &GetNextChild<KaxAttached>(attachments, *attachedFile);
}
return noErr;
}
ComponentResult MatroskaImport::ReadMetaSeek(KaxSeekHead &seekHead)
{
ComponentResult err = noErr;
KaxSeek *seekEntry = FindChild<KaxSeek>(seekHead);
// don't re-read a seek head that's already been read
uint64_t currPos = seekHead.GetElementPosition();
vector<MatroskaSeek>::iterator itr = levelOneElements.begin();
for (; itr != levelOneElements.end(); itr++) {
if (itr->GetID() == KaxSeekHead::ClassInfos.GlobalId &&
itr->segmentPos + segmentOffset == currPos)
return noErr;
}
while (seekEntry && seekEntry->GetSize() > 0) {
MatroskaSeek newSeekEntry;
KaxSeekID & seekID = GetChild<KaxSeekID>(*seekEntry);
KaxSeekPosition & position = GetChild<KaxSeekPosition>(*seekEntry);
EbmlId elementID = EbmlId(seekID.GetBuffer(), seekID.GetSize());
newSeekEntry.ebmlID = elementID.Value;
newSeekEntry.idLength = elementID.Length;
newSeekEntry.segmentPos = position;
// recursively read seek heads that are pointed to by the current one
// as well as the level one elements we care about
if (elementID == KaxInfo::ClassInfos.GlobalId ||
elementID == KaxTracks::ClassInfos.GlobalId ||
elementID == KaxChapters::ClassInfos.GlobalId ||
elementID == KaxAttachments::ClassInfos.GlobalId ||
elementID == KaxSeekHead::ClassInfos.GlobalId) {
MatroskaSeekContext savedContext = SaveContext();
SetContext(newSeekEntry.GetSeekContext(segmentOffset));
if (NextLevel1Element())
err = ProcessLevel1Element();
SetContext(savedContext);
if (err) return err;
}
levelOneElements.push_back(newSeekEntry);