forked from sbooth/SFBAudioEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSFBDSDIFFDecoder.mm
918 lines (742 loc) · 25.7 KB
/
SFBDSDIFFDecoder.mm
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
//
// Copyright (c) 2014-2025 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
#import <cstdint>
#import <map>
#import <memory>
#import <string>
#import <vector>
#import <os/log.h>
#import <AVAudioChannelLayout+SFBChannelLabels.h>
#import "SFBDSDIFFDecoder.h"
#import "NSData+SFBExtensions.h"
#import "NSError+SFBURLPresentation.h"
#import "SFBCStringForOSType.h"
SFBDSDDecoderName const SFBDSDDecoderNameDSDIFF = @"org.sbooth.AudioEngine.DSDDecoder.DSDIFF";
namespace {
// Convert a four byte chunk ID to a uint32_t
uint32_t BytesToID(char bytes [4]) noexcept
{
auto one = bytes[0];
auto two = bytes[1];
auto three = bytes[2];
auto four = bytes[3];
// Verify well-formedness
if(!std::isprint(one) || !std::isprint(two) || !std::isprint(three) || !std::isprint(four))
return 0;
if(std::isspace(one))
return 0;
if(std::isspace(two) && std::isspace(one))
return 0;
if(std::isspace(three) && std::isspace(two) && std::isspace(one))
return 0;
if(std::isspace(four) && std::isspace(three) && std::isspace(two) && std::isspace(one))
return 0;
return static_cast<uint32_t>((one << 24u) | (two << 16u) | (three << 8u) | four);
}
// Read an ID as a uint32_t, performing validation
bool ReadID(SFBInputSource *inputSource, uint32_t& chunkID) noexcept
{
NSCParameterAssert(inputSource != nil);
char chunkIDBytes [4];
NSInteger bytesRead;
if(![inputSource readBytes:chunkIDBytes length:4 bytesRead:&bytesRead error:nil] || bytesRead != 4) {
os_log_error(gSFBDSDDecoderLog, "Unable to read chunk ID");
return false;
}
chunkID = BytesToID(chunkIDBytes);
if(0 == chunkID) {
os_log_error(gSFBDSDDecoderLog, "Illegal chunk ID");
return false;
}
return true;
}
AudioChannelLabel DSDIFFChannelIDToCoreAudioChannelLabel(uint32_t channelID) noexcept
{
switch(channelID) {
case 'SLFT': return kAudioChannelLabel_Left;
case 'SRGT': return kAudioChannelLabel_Right;
case 'MLFT': return kAudioChannelLabel_LeftSurroundDirect;
case 'MRGT': return kAudioChannelLabel_RightSurroundDirect;
case 'LS ': return kAudioChannelLabel_LeftSurround;
case 'RS ': return kAudioChannelLabel_RightSurround;
case 'C ': return kAudioChannelLabel_Center;
case 'LFE ': return kAudioChannelLabel_LFE2;
}
return kAudioChannelLabel_Unknown;
}
#pragma mark DSDIFF chunks
// Base class for DSDIFF chunks
struct DSDIFFChunk : std::enable_shared_from_this<DSDIFFChunk>
{
using shared_ptr = std::shared_ptr<DSDIFFChunk>;
using chunk_map = std::map<uint32_t, shared_ptr>;
// Shared pointer support
shared_ptr getptr() { return shared_from_this(); }
uint32_t mChunkID;
uint64_t mDataSize;
int64_t mDataOffset;
};
// 'FRM8'
struct FormDSDChunk : public DSDIFFChunk
{
uint32_t mFormType;
chunk_map mLocalChunks;
};
// 'FVER' in 'FRM8'
struct FormatVersionChunk : public DSDIFFChunk
{
static const uint32_t kSupportedFormatVersion = 0x01050000;
uint32_t mFormatVersion;
};
// 'PROP' in 'FRM8'
struct PropertyChunk : public DSDIFFChunk
{
uint32_t mPropertyType;
chunk_map mLocalChunks;
};
// 'FS ' in 'PROP'
struct SampleRateChunk : public DSDIFFChunk
{
uint32_t mSampleRate;
};
// 'CHNL' in 'PROP'
struct ChannelsChunk : public DSDIFFChunk
{
uint16_t mNumberChannels;
std::vector<uint32_t> mChannelIDs;
};
// 'CMPR' in 'PROP'
struct CompressionTypeChunk : public DSDIFFChunk
{
uint32_t mCompressionType;
std::string mCompressionName;
};
// 'ABSS' in 'PROP'
struct AbsoluteStartTimeChunk : public DSDIFFChunk
{
uint16_t mHours;
uint8_t mMinutes;
uint8_t mSeconds;
uint32_t mSamples;
};
// 'LSCO' in 'PROP'
struct LoudspeakerConfigurationChunk : public DSDIFFChunk
{
uint16_t mLoudspeakerConfiguration;
};
// 'DSD ' in 'FRM8'
struct DSDSoundDataChunk : public DSDIFFChunk
{};
// 'DST ', 'DSTI', 'COMT', 'DIIN', 'MANF' are not handled
// // 'DST ' in 'FRM8'
// class DSTSoundDataChunk : public DSDIFFChunk
// {};
//
// // 'FRTE' in 'DST '
// class DSTFrameInformationChunk : public DSDIFFChunk
// {};
//
// // 'FRTE' in 'DST '
// class DSTFrameDataChunk : public DSDIFFChunk
// {};
//
// // 'FRTE' in 'DST '
// class DSTFrameCRCChunk : public DSDIFFChunk
// {};
//
// // 'DSTI' in 'FRM8'
// class DSTSoundIndexChunk : public DSDIFFChunk
// {};
//
// // 'COMT' in 'FRM8'
// class CommentsChunk : public DSDIFFChunk
// {};
//
// // 'DIIN' in 'FRM8'
// class EditedMasterInformationChunk : public DSDIFFChunk
// {};
//
// // 'EMID' in 'DIIN'
// class EditedMasterIDChunk : public DSDIFFChunk
// {};
//
// // 'MARK' in 'DIIN'
// class MarkerChunk : public DSDIFFChunk
// {};
//
// // 'DIAR' in 'DIIN'
// class ArtistChunk : public DSDIFFChunk
// {};
//
// // 'DITI' in 'DIIN'
// class TitleChunk : public DSDIFFChunk
// {};
//
// // 'MANF' in 'FRM8'
// class ManufacturerSpecificChunk : public DSDIFFChunk
// {};
#pragma mark DSDIFF parsing
bool ReadChunkIDAndDataSize(SFBInputSource *inputSource, uint32_t& chunkID, uint64_t& chunkDataSize)
{
if(!ReadID(inputSource, chunkID))
return false;
if(![inputSource readUInt64BigEndian:&chunkDataSize error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read chunk data size");
return false;
}
return true;
}
std::shared_ptr<FormatVersionChunk> ParseFormatVersionChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'FVER') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'FVER' chunk");
return nullptr;
}
auto result = std::make_shared<FormatVersionChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(![inputSource readUInt32BigEndian:&result->mFormatVersion error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read format version in 'FVER' chunk");
return nullptr;
}
if(result->mFormatVersion > FormatVersionChunk::kSupportedFormatVersion) {
os_log_error(gSFBDSDDecoderLog, "Unsupported format version in 'FVER': %u", result->mFormatVersion);
return nullptr;
}
return result;
}
std::shared_ptr<SampleRateChunk> ParseSampleRateChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'FS ') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'FS ' chunk");
return nullptr;
}
auto result = std::make_shared<SampleRateChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(![inputSource readUInt32BigEndian:&result->mSampleRate error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read sample rate in 'FS ' chunk");
return nullptr;
}
return result;
}
std::shared_ptr<ChannelsChunk> ParseChannelsChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'CHNL') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'CHNL' chunk");
return nullptr;
}
auto result = std::make_shared<ChannelsChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(![inputSource readUInt16BigEndian:&result->mNumberChannels error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read number channels in 'CHNL' chunk");
return nullptr;
}
for(uint16_t i = 0; i < result->mNumberChannels; ++i) {
uint32_t channelID;
if(!ReadID(inputSource, channelID)) {
os_log_error(gSFBDSDDecoderLog, "Unable to read channel ID in 'CHNL' chunk");
return nullptr;
}
result->mChannelIDs.push_back(channelID);
}
return result;
}
std::shared_ptr<CompressionTypeChunk> ParseCompressionTypeChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'CMPR') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'CMPR' chunk");
return nullptr;
}
auto result = std::make_shared<CompressionTypeChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(!ReadID(inputSource, result->mCompressionType)) {
os_log_error(gSFBDSDDecoderLog, "Unable to read compression type in 'CMPR' chunk");
return nullptr;
}
uint8_t count;
if(![inputSource readUInt8:&count error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read count in 'CMPR' chunk");
return nullptr;
}
char compressionName [count];
NSInteger bytesRead;
if(![inputSource readBytes:compressionName length:count bytesRead:&bytesRead error:nil] || bytesRead != count) {
os_log_error(gSFBDSDDecoderLog, "Unable to read compressionName in 'CMPR' chunk");
return nullptr;
}
result->mCompressionName = std::string(compressionName, count);
// Chunks always have an even length
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
if(offset % 2) {
uint8_t unused;
if(![inputSource readUInt8:&unused error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read dummy byte in 'CMPR' chunk");
return nullptr;
}
}
return result;
}
std::shared_ptr<AbsoluteStartTimeChunk> ParseAbsoluteStartTimeChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'ABSS') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'ABSS' chunk");
return nullptr;
}
auto result = std::make_shared<AbsoluteStartTimeChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(![inputSource readUInt16BigEndian:&result->mHours error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read hours in 'ABSS' chunk");
return nullptr;
}
if(![inputSource readUInt8:&result->mMinutes error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read minutes in 'ABSS' chunk");
return nullptr;
}
if(![inputSource readUInt8:&result->mSeconds error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read seconds in 'ABSS' chunk");
return nullptr;
}
if(![inputSource readUInt32BigEndian:&result->mSamples error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read samples in 'ABSS' chunk");
return nullptr;
}
return result;
}
std::shared_ptr<LoudspeakerConfigurationChunk> ParseLoudspeakerConfigurationChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'LSCO') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'LSCO' chunk");
return nullptr;
}
auto result = std::make_shared<LoudspeakerConfigurationChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(![inputSource readUInt16BigEndian:&result->mLoudspeakerConfiguration error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Unable to read loudspeaker configuration in 'LSCO' chunk");
return nullptr;
}
return result;
}
std::shared_ptr<PropertyChunk> ParsePropertyChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'PROP') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'PROP' chunk");
return nullptr;
}
auto result = std::make_shared<PropertyChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(!ReadID(inputSource, result->mPropertyType)) {
os_log_error(gSFBDSDDecoderLog, "Unable to read property type in 'PROP' chunk");
return nullptr;
}
if(result->mPropertyType != 'SND ') {
os_log_error(gSFBDSDDecoderLog, "Unexpected property type in 'PROP' chunk: %u", result->mPropertyType);
return nullptr;
}
// Parse the local chunks
auto chunkDataSizeRemaining = result->mDataSize - 4; // adjust for mPropertyType
while(chunkDataSizeRemaining) {
uint32_t localChunkID;
uint64_t localChunkDataSize;
if(ReadChunkIDAndDataSize(inputSource, localChunkID, localChunkDataSize)) {
switch(localChunkID) {
case 'FS ':
{
auto chunk = ParseSampleRateChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
case 'CHNL':
{
auto chunk = ParseChannelsChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
case 'CMPR':
{
auto chunk = ParseCompressionTypeChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
case 'ABSS':
{
auto chunk = ParseAbsoluteStartTimeChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
case 'LSCO':
{
auto chunk = ParseLoudspeakerConfigurationChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
// Skip unrecognized or ignored chunks
default:
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
if(![inputSource seekToOffset:(offset + static_cast<NSInteger>(localChunkDataSize)) error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error skipping chunk data");
return nullptr;
}
break;
}
chunkDataSizeRemaining -= 12;
chunkDataSizeRemaining -= localChunkDataSize;
}
else {
os_log_error(gSFBDSDDecoderLog, "Error reading local chunk in 'PROP' chunk");
return nullptr;
}
}
return result;
}
std::shared_ptr<DSDSoundDataChunk> ParseDSDSoundDataChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'DSD ') {
os_log_error(gSFBDSDDecoderLog, "Invalid chunk ID for 'DSD ' chunk");
return nullptr;
}
auto result = std::make_shared<DSDSoundDataChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
// Skip the data
if(![inputSource seekToOffset:(offset + static_cast<NSInteger>(chunkDataSize)) error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error skipping chunk data");
return nullptr;
}
return result;
}
std::unique_ptr<FormDSDChunk> ParseFormDSDChunk(SFBInputSource *inputSource, const uint32_t chunkID, const uint64_t chunkDataSize)
{
if(chunkID != 'FRM8') {
os_log_error(gSFBDSDDecoderLog, "Missing 'FRM8' chunk");
return nullptr;
}
auto result = std::make_unique<FormDSDChunk>();
result->mChunkID = chunkID;
result->mDataSize = chunkDataSize;
NSInteger offset;
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
result->mDataOffset = offset;
if(!ReadID(inputSource, result->mFormType)) {
os_log_error(gSFBDSDDecoderLog, "Unable to read formType in 'FRM8' chunk");
return nullptr;
}
if(result->mFormType != 'DSD ') {
os_log_error(gSFBDSDDecoderLog, "Unexpected formType in 'FRM8' chunk: '%{public}.4s'", SFBCStringForOSType(result->mFormType));
return nullptr;
}
// Parse the local chunks
auto chunkDataSizeRemaining = result->mDataSize - 4; // adjust for mFormType
while(chunkDataSizeRemaining) {
uint32_t localChunkID;
uint64_t localChunkDataSize;
if(ReadChunkIDAndDataSize(inputSource, localChunkID, localChunkDataSize)) {
switch(localChunkID) {
case 'FVER':
{
auto chunk = ParseFormatVersionChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
case 'PROP':
{
auto chunk = ParsePropertyChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
case 'DSD ':
{
auto chunk = ParseDSDSoundDataChunk(inputSource, localChunkID, localChunkDataSize);
if(chunk)
result->mLocalChunks[chunk->mChunkID] = chunk;
break;
}
// Skip unrecognized or ignored chunks
default:
if(![inputSource getOffset:&offset error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error getting chunk data offset");
return nullptr;
}
if(![inputSource seekToOffset:(offset + static_cast<NSInteger>(localChunkDataSize)) error:nil]) {
os_log_error(gSFBDSDDecoderLog, "Error skipping chunk data");
return nullptr;
}
break;
}
chunkDataSizeRemaining -= 12;
chunkDataSizeRemaining -= localChunkDataSize;
}
else {
os_log_error(gSFBDSDDecoderLog, "Error reading local chunk in 'FRM8' chunk");
return nullptr;
}
}
return result;
}
std::unique_ptr<FormDSDChunk> ParseDSDIFF(SFBInputSource *inputSource)
{
uint32_t chunkID;
uint64_t chunkDataSize;
if(!ReadChunkIDAndDataSize(inputSource, chunkID, chunkDataSize))
return nullptr;
return ParseFormDSDChunk(inputSource, chunkID, chunkDataSize);
}
static NSError * CreateInvalidDSDIFFFileError(NSURL * url)
{
return [NSError SFB_errorWithDomain:SFBDSDDecoderErrorDomain
code:SFBDSDDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid DSDIFF file.", @"")
url:url
failureReason:NSLocalizedString(@"Not a DSDIFF file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
}
} /* namespace */
@interface SFBDSDIFFDecoder ()
{
@private
BOOL _isOpen;
AVAudioFramePosition _packetPosition;
AVAudioFramePosition _packetCount;
int64_t _audioOffset;
AVAudioCompressedBuffer *_buffer;
}
@end
@implementation SFBDSDIFFDecoder
+ (void)load
{
[SFBDSDDecoder registerSubclass:[self class]];
}
+ (NSSet *)supportedPathExtensions
{
return [NSSet setWithObject:@"dff"];
}
+ (NSSet *)supportedMIMETypes
{
return [NSSet setWithObject:@"audio/dsdiff"];
}
+ (SFBDSDDecoderName)decoderName
{
return SFBDSDDecoderNameDSDIFF;
}
+ (BOOL)testInputSource:(SFBInputSource *)inputSource formatIsSupported:(SFBTernaryTruthValue *)formatIsSupported error:(NSError **)error
{
NSParameterAssert(inputSource != nil);
NSParameterAssert(formatIsSupported != NULL);
NSData *header = [inputSource readHeaderOfLength:SFBDSDIFFDetectionSize skipID3v2Tag:NO error:error];
if(!header)
return NO;
if([header isDSDIFFHeader])
*formatIsSupported = SFBTernaryTruthValueTrue;
else
*formatIsSupported = SFBTernaryTruthValueFalse;
return YES;
}
- (BOOL)decodingIsLossless
{
return YES;
}
- (BOOL)openReturningError:(NSError **)error
{
if(![super openReturningError:error])
return NO;
auto chunks = ParseDSDIFF(_inputSource);
if(!chunks) {
os_log_error(gSFBDSDDecoderLog, "Error parsing file");
if(error)
*error = CreateInvalidDSDIFFFileError(_inputSource.url);
return NO;
}
auto propertyChunk = std::static_pointer_cast<PropertyChunk>(chunks->mLocalChunks['PROP']);
auto sampleRateChunk = std::static_pointer_cast<SampleRateChunk>(propertyChunk->mLocalChunks['FS ']);
auto channelsChunk = std::static_pointer_cast<ChannelsChunk>(propertyChunk->mLocalChunks['CHNL']);
if(!propertyChunk || !sampleRateChunk || !channelsChunk) {
os_log_error(gSFBDSDDecoderLog, "Missing chunk in file");
if(error)
*error = CreateInvalidDSDIFFFileError(_inputSource.url);
return NO;
}
// Channel layouts are defined in the DSDIFF file format specification
AVAudioChannelLayout *channelLayout = nil;
if(channelsChunk->mChannelIDs.size() == 2 && channelsChunk->mChannelIDs[0] == 'SLFT' && channelsChunk->mChannelIDs[1] == 'SRGT')
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_Stereo];
else if(channelsChunk->mChannelIDs.size() == 5 && channelsChunk->mChannelIDs[0] == 'MLFT' && channelsChunk->mChannelIDs[1] == 'MRGT' && channelsChunk->mChannelIDs[2] == 'C ' && channelsChunk->mChannelIDs[3] == 'LS ' && channelsChunk->mChannelIDs[4] == 'RS ')
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_MPEG_5_0_A];
else if(channelsChunk->mChannelIDs.size() == 6 && channelsChunk->mChannelIDs[0] == 'MLFT' && channelsChunk->mChannelIDs[1] == 'MRGT' && channelsChunk->mChannelIDs[2] == 'C ' && channelsChunk->mChannelIDs[3] == 'LFE ' && channelsChunk->mChannelIDs[4] == 'LS ' && channelsChunk->mChannelIDs[5] == 'RS ')
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_MPEG_5_1_A];
else if(!channelsChunk->mChannelIDs.empty()) {
std::vector<AudioChannelLabel> labels;
for(auto channelID : channelsChunk->mChannelIDs)
labels.push_back(DSDIFFChannelIDToCoreAudioChannelLabel(channelID));
channelLayout = [AVAudioChannelLayout layoutWithChannelLabels:&labels[0] count:(AVAudioChannelCount)labels.size()];
}
AudioStreamBasicDescription processingStreamDescription{};
// The output format is raw DSD
processingStreamDescription.mFormatID = kSFBAudioFormatDSD;
processingStreamDescription.mFormatFlags = kAudioFormatFlagIsBigEndian;
processingStreamDescription.mSampleRate = (Float64)sampleRateChunk->mSampleRate;
processingStreamDescription.mChannelsPerFrame = channelsChunk->mNumberChannels;
processingStreamDescription.mBitsPerChannel = 1;
processingStreamDescription.mBytesPerPacket = kSFBBytesPerDSDPacketPerChannel * channelsChunk->mNumberChannels;
processingStreamDescription.mFramesPerPacket = kSFBPCMFramesPerDSDPacket;
_processingFormat = [[AVAudioFormat alloc] initWithStreamDescription:&processingStreamDescription channelLayout:channelLayout];
// Set up the source format
AudioStreamBasicDescription sourceStreamDescription{};
sourceStreamDescription.mFormatID = kSFBAudioFormatDSD;
sourceStreamDescription.mSampleRate = static_cast<Float64>(sampleRateChunk->mSampleRate);
sourceStreamDescription.mChannelsPerFrame = channelsChunk->mNumberChannels;
sourceStreamDescription.mBitsPerChannel = 1;
_sourceFormat = [[AVAudioFormat alloc] initWithStreamDescription:&sourceStreamDescription channelLayout:channelLayout];
auto soundDataChunk = std::static_pointer_cast<DSDSoundDataChunk>(chunks->mLocalChunks['DSD ']);
if(!soundDataChunk) {
os_log_error(gSFBDSDDecoderLog, "Missing chunk in file");
if(error)
*error = CreateInvalidDSDIFFFileError(_inputSource.url);
return NO;
}
_audioOffset = soundDataChunk->mDataOffset;
_packetCount = static_cast<AVAudioFramePosition>(soundDataChunk->mDataSize - 12) / (kSFBBytesPerDSDPacketPerChannel * channelsChunk->mNumberChannels);
if(![_inputSource seekToOffset:_audioOffset error:error])
return NO;
_isOpen = YES;
return YES;
}
- (BOOL)closeReturningError:(NSError **)error
{
_isOpen = NO;
return [super closeReturningError:error];
}
- (BOOL)isOpen
{
return _isOpen;
}
- (AVAudioFramePosition)packetPosition
{
return _packetPosition;
}
- (AVAudioFramePosition)packetCount
{
return _packetCount;
}
- (BOOL)decodeIntoBuffer:(AVAudioCompressedBuffer *)buffer packetCount:(AVAudioPacketCount)packetCount error:(NSError **)error
{
NSParameterAssert(buffer != nil);
NSParameterAssert([buffer.format isEqual:_processingFormat]);
// Reset output buffer data size
buffer.packetCount = 0;
buffer.byteLength = 0;
if(packetCount > buffer.packetCapacity)
packetCount = buffer.packetCapacity;
if(packetCount == 0)
return YES;
AVAudioPacketCount packetsRemaining = static_cast<AVAudioPacketCount>(_packetCount - _packetPosition);
AVAudioPacketCount packetsToRead = std::min(packetCount, packetsRemaining);
AVAudioPacketCount packetsRead = 0;
uint32_t packetSize = kSFBBytesPerDSDPacketPerChannel * _processingFormat.channelCount;
for(;;) {
// Read interleaved input, grouped as 8 one bit samples per frame (a single channel byte) into
// a clustered frame (one channel byte per channel)
auto buf = static_cast<uint8_t *>(reinterpret_cast<void *>(reinterpret_cast<uintptr_t>(buffer.data) + buffer.byteLength));
NSInteger bytesToRead = std::min(packetsToRead * packetSize, buffer.byteCapacity - buffer.byteLength);
NSInteger bytesRead;
if(![_inputSource readBytes:buf length:bytesToRead bytesRead:&bytesRead error:error] || bytesRead != bytesToRead) {
os_log_error(gSFBDSDDecoderLog, "Error reading audio: requested %ld bytes, got %ld", static_cast<long>(bytesToRead), bytesRead);
return NO;
}
// Decoding is finished
if(bytesRead == 0)
break;
packetsRead += (bytesRead / packetSize);
buffer.packetCount += static_cast<AVAudioPacketCount>(bytesRead / packetSize);
buffer.byteLength += static_cast<uint32_t>(bytesRead);
// All requested frames were read
if(packetsRead == packetCount)
break;
packetsToRead -= packetsRead;
}
_packetPosition += packetsRead;
return YES;
}
- (BOOL)seekToPacket:(AVAudioFramePosition)packet error:(NSError **)error
{
NSParameterAssert(packet >= 0);
NSInteger packetOffset = packet * kSFBBytesPerDSDPacketPerChannel * _processingFormat.channelCount;
if(![_inputSource seekToOffset:(_audioOffset + packetOffset) error:error]) {
os_log_debug(gSFBDSDDecoderLog, "-seekToPacket:error: failed seeking to input offset: %lld", _audioOffset + packetOffset);
return NO;
}
_packetPosition = packet;
return YES;
}
@end