-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathSFBShortenDecoder.mm
More file actions
1688 lines (1451 loc) · 58.6 KB
/
Copy pathSFBShortenDecoder.mm
File metadata and controls
1688 lines (1451 loc) · 58.6 KB
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
//
// SPDX-FileCopyrightText: 2020 Stephen F. Booth <contact@sbooth.dev>
// SPDX-License-Identifier: MIT
//
// Part of https://github.com/sbooth/SFBAudioEngine
//
#import "SFBShortenDecoder.h"
#import "NSData+SFBExtensions.h"
#import "SFBLocalizedNameForURL.h"
#import <AVFAudioExtensions/AVFAudioExtensions.h>
#import <libkern/OSByteOrder.h>
#import <os/log.h>
#import <algorithm>
#import <cmath>
#import <cstdlib>
#import <cstring>
#import <ranges>
#import <vector>
SFBAudioDecoderName const SFBAudioDecoderNameShorten = @"org.sbooth.AudioEngine.Decoder.Shorten";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenVersion = @"_version";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenFileType = @"_fileType";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenNumberChannels = @"_channelCount";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenBlockSize = @"_blocksize";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenSampleRate = @"_sampleRate";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenBitsPerSample = @"_bitsPerSample";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyShortenBigEndian = @"_bigEndian";
namespace {
// MARK: Constants
// Rice-Golomb code k values
constexpr auto parameterBitshift = 2;
constexpr auto parameterChannelCount = 0;
constexpr auto parameterEnergy = 3;
constexpr auto parameterExtraByte = 7;
constexpr auto parameterFileType = 4;
constexpr auto parameterFunction = 2;
constexpr auto parameterQLPC = 2;
constexpr auto parameterSkipBytes = 1;
constexpr auto parameterUInt32 = 2;
constexpr auto parameterVerbatimChunkSize = 5;
constexpr auto parameterVerbatimByte = 8;
// File commands
constexpr auto functionDiff0 = 0;
constexpr auto functionDiff1 = 1;
constexpr auto functionDiff2 = 2;
constexpr auto functionDiff3 = 3;
constexpr auto functionQuit = 4;
constexpr auto functionBlocksize = 5;
constexpr auto functionBitshift = 6;
constexpr auto functionQLPC = 7;
constexpr auto functionZero = 8;
constexpr auto functionVerbatim = 9;
// Format limitations
constexpr auto maxBlocksize = 65535;
constexpr auto verbatimChunkMaxSizeBytes = 256;
// File types
constexpr auto fileTypeSInt8 = 1;
constexpr auto fileTypeUInt8 = 2;
constexpr auto fileTypeSInt16BE = 3;
constexpr auto fileTypeUInt16BE = 4;
constexpr auto fileTypeSInt16LE = 5;
constexpr auto fileTypeUInt16LE = 6;
// Seeking support
constexpr auto seekTableRevision = 1;
constexpr auto seekHeaderSizeBytes = 12;
constexpr auto seekTrailerSizeBytes = 12;
constexpr auto seekEntrySizeBytes = 80;
constexpr int32_t roundedShiftDown(int32_t x, int k) noexcept { return (k == 0) ? x : (x >> (k - 1)) >> 1; }
/// Returns a two-dimensional `rows` x `cols` array using one allocation from `malloc`
template <typename T> T **allocateContiguous2DArray(size_t rows, size_t cols) noexcept {
T **result = static_cast<T **>(std::malloc((rows * sizeof(T *)) + (rows * cols * sizeof(T))));
if (!result) {
return nullptr;
}
T *tmp = reinterpret_cast<T *>(result + rows);
for (size_t i = 0; i < rows; ++i) {
result[i] = tmp + (i * cols);
}
return result;
}
/// Variable-length input using Golomb-Rice coding
class VariableLengthInput {
public:
// An entry i has the lowest i bits set
static constexpr uint32_t maskTable_[] = {
0x0, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f, 0xff,
0x1ff, 0x3ff, 0x7ff, 0xfff, 0x1fff, 0x3fff, 0x7fff, 0xffff, 0x1ffff,
0x3ffff, 0x7ffff, 0xfffff, 0x1fffff, 0x3fffff, 0x7fffff, 0xffffff, 0x1ffffff, 0x3ffffff,
0x7ffffff, 0xfffffff, 0x1fffffff, 0x3fffffff, 0x7fffffff, 0xffffffff};
/// Creates an empty `VariableLengthInput` object
/// - important: `Allocate()` must be called before using
VariableLengthInput() noexcept = default;
~VariableLengthInput() { delete[] byteBuffer_; }
VariableLengthInput(const VariableLengthInput &) = delete;
VariableLengthInput(VariableLengthInput &&) = delete;
VariableLengthInput &operator=(const VariableLengthInput &) = delete;
VariableLengthInput &operator=(VariableLengthInput &&) = delete;
/// Input callback type
using InputBlock = bool (^)(void *buf, size_t len, size_t &read);
/// Sets the input callback
void setInputCallback(InputBlock block) noexcept { inputBlock_ = block; }
/// Allocates an internal buffer of the specified size
/// - warning: Sizes other than `512` will break seeking
bool allocate(size_t size = 512) noexcept {
if (byteBuffer_) {
return false;
}
auto *byteBuffer = new (std::nothrow) unsigned char[size];
if (!byteBuffer) {
return false;
}
byteBuffer_ = byteBuffer;
byteBufferPosition_ = byteBuffer_;
size_ = size;
return true;
}
bool getRiceGolombCode(int32_t &i32, int k) noexcept {
#if DEBUG
assert(k >= 0 && k < 32);
#endif /* DEBUG */
if (k < 0 || k > 31) {
return false;
}
if (bitsAvailable_ == 0 && !refillBitBuffer()) {
return false;
}
// Calculate unary quotient
int32_t result;
for (result = 0; !(bitBuffer_ & (1L << --bitsAvailable_)); ++result) {
if (bitsAvailable_ == 0 && !refillBitBuffer()) {
return false;
}
}
while (k != 0) {
if (bitsAvailable_ >= k) {
result = (result << k) | static_cast<int32_t>((bitBuffer_ >> (bitsAvailable_ - k)) & maskTable_[k]);
bitsAvailable_ -= k;
k = 0;
} else {
#if DEBUG
assert(bitsAvailable_ < 32);
#endif /* DEBUG */
result = (result << bitsAvailable_) | static_cast<int32_t>(bitBuffer_ & maskTable_[bitsAvailable_]);
k -= bitsAvailable_;
if (!refillBitBuffer()) {
return false;
}
}
}
i32 = result;
return true;
}
bool getInt32(int32_t &i32, int k) noexcept {
int32_t var;
if (!getRiceGolombCode(var, k + 1)) {
return false;
}
uint32_t uvar = static_cast<uint32_t>(var);
if (uvar & 1) {
i32 = ~(uvar >> 1);
} else {
i32 = (uvar >> 1);
}
return true;
}
bool getUInt32(uint32_t &ui32, int version, int k) noexcept {
if (version > 0 && !getRiceGolombCode(k, parameterUInt32)) {
return false;
}
int32_t i32;
if (!getRiceGolombCode(i32, k)) {
return false;
}
ui32 = static_cast<uint32_t>(i32);
return true;
}
void reset() noexcept {
byteBufferPosition_ = byteBuffer_;
bytesAvailable_ = 0;
bitsAvailable_ = 0;
}
bool refill() noexcept {
size_t bytesRead = 0;
if (!inputBlock_ || !inputBlock_(byteBuffer_, size_, bytesRead) || bytesRead < 4) {
return false;
}
bytesAvailable_ += bytesRead;
byteBufferPosition_ = byteBuffer_;
return true;
}
bool setState(uint16_t byteBufferPosition, uint16_t bytesAvailable, uint32_t bitBuffer,
uint16_t bitsAvailable) noexcept {
if (byteBufferPosition > size_ || bytesAvailable > size_ - byteBufferPosition || bitsAvailable > 32) {
return false;
}
byteBufferPosition_ = byteBuffer_ + byteBufferPosition;
bytesAvailable_ = bytesAvailable;
bitBuffer_ = bitBuffer;
bitsAvailable_ = bitsAvailable;
return true;
}
private:
/// Input callback
InputBlock inputBlock_ = nil;
/// Size of `byteBuffer_` in bytes
size_t size_ = 0;
/// Byte buffer
unsigned char *byteBuffer_ = nullptr;
/// Current position in `byteBuffer_`
unsigned char *byteBufferPosition_ = nullptr;
/// Bytes available in `byteBuffer_`
int bytesAvailable_ = 0;
/// Bit buffer
uint32_t bitBuffer_ = 0;
/// Bits available in `mBitBuffer`
int bitsAvailable_ = 0;
/// Reads a single `uint32_t` from the byte buffer, refilling if necessary
bool refillBitBuffer() noexcept {
if (bytesAvailable_ < 4 && !refill()) {
return false;
}
bitBuffer_ = static_cast<uint32_t>((static_cast<int32_t>(byteBufferPosition_[0]) << 24) |
(static_cast<int32_t>(byteBufferPosition_[1]) << 16) |
(static_cast<int32_t>(byteBufferPosition_[2]) << 8) |
static_cast<int32_t>(byteBufferPosition_[3]));
byteBufferPosition_ += 4;
bytesAvailable_ -= 4;
bitsAvailable_ = 32;
return true;
}
};
/// Shorten seek table header
struct SeekTableHeader {
int8_t signature_[4];
uint32_t version_;
uint32_t fileSize_;
};
SeekTableHeader parseSeekTableHeader(const void *buf) {
SeekTableHeader header;
std::memcpy(header.signature_, buf, 4);
header.version_ = OSReadLittleInt32(buf, 4);
header.fileSize_ = OSReadLittleInt32(buf, 8);
return header;
}
/// Shorten seek table trailer
struct SeekTableTrailer {
uint32_t seekTableSize_;
int8_t signature_[8];
};
SeekTableTrailer parseSeekTableTrailer(const void *buf) {
SeekTableTrailer trailer;
trailer.seekTableSize_ = OSReadLittleInt32(buf, 0);
std::memcpy(trailer.signature_, static_cast<const unsigned char *>(buf) + 4, 8);
return trailer;
}
/// A Shorten seek table entry
struct SeekTableEntry {
uint32_t frameNumber_;
uint32_t byteOffsetInFile_;
uint32_t lastBufferReadPosition_;
uint16_t bytesAvailable_;
uint16_t byteBufferPosition_;
uint16_t bitBufferPosition_;
uint32_t bitBuffer_;
uint16_t bitshift_;
int32_t chanBuf0_[3];
int32_t chanBuf1_[3];
int32_t offset0_[4];
int32_t offset1_[4];
};
SeekTableEntry parseSeekTableEntry(const void *buf) {
SeekTableEntry entry;
entry.frameNumber_ = OSReadLittleInt32(buf, 0);
entry.byteOffsetInFile_ = OSReadLittleInt32(buf, 4);
entry.lastBufferReadPosition_ = OSReadLittleInt32(buf, 8);
entry.bytesAvailable_ = OSReadLittleInt16(buf, 12);
entry.byteBufferPosition_ = OSReadLittleInt16(buf, 14);
entry.bitBufferPosition_ = OSReadLittleInt16(buf, 16);
entry.bitBuffer_ = OSReadLittleInt32(buf, 18);
entry.bitshift_ = OSReadLittleInt16(buf, 22);
for (auto i = 0; i < 3; ++i) {
entry.chanBuf0_[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 24 + 4 * i));
}
for (auto i = 0; i < 3; ++i) {
entry.chanBuf1_[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 36 + 4 * i));
}
for (auto i = 0; i < 4; ++i) {
entry.offset0_[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 48 + 4 * i));
}
for (auto i = 0; i < 4; ++i) {
entry.offset1_[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 64 + 4 * i));
}
return entry;
}
} /* namespace */
@interface SFBShortenDecoder () {
@private
VariableLengthInput _input;
int _version;
int32_t _lpcQuantOffset;
int _fileType;
int _channelCount;
int _mean;
int _blocksize;
int _maxLPC;
int _wrap;
uint32_t _sampleRate;
uint32_t _bitsPerSample;
bool _bigEndian;
int32_t **_buffer;
int32_t **_offset;
int *_qlpc;
int _bitshift;
bool _eos;
std::vector<SeekTableEntry> _seekTableEntries;
AVAudioPCMBuffer *_frameBuffer;
AVAudioFramePosition _framePosition;
AVAudioFramePosition _frameLength;
uint64_t _blocksDecoded;
}
- (bool)parseShortenHeaderReturningError:(NSError **)error;
- (bool)parseRIFFChunk:(const unsigned char *)chunkData size:(size_t)size error:(NSError **)error;
- (bool)parseFORMChunk:(const unsigned char *)chunkData size:(size_t)size error:(NSError **)error;
- (bool)decodeBlockReturningError:(NSError **)error;
- (bool)scanForSeekTableReturningError:(NSError **)error;
- (std::vector<SeekTableEntry>)parseExternalSeekTable:(NSURL *)url;
- (bool)seekTableIsValid:(std::vector<SeekTableEntry>)entries startOffset:(NSInteger)startOffset;
@end
@implementation SFBShortenDecoder
+ (void)load {
[SFBAudioDecoder registerSubclass:[self class]];
}
+ (NSSet *)supportedPathExtensions {
return [NSSet setWithObject:@"shn"];
}
+ (NSSet *)supportedMIMETypes {
return [NSSet setWithObject:@"audio/x-shorten"];
}
+ (SFBAudioDecoderName)decoderName {
return SFBAudioDecoderNameShorten;
}
+ (BOOL)testInputSource:(SFBInputSource *)inputSource
formatIsSupported:(SFBTernaryTruthValue *)formatIsSupported
error:(NSError **)error {
NSParameterAssert(inputSource != nil);
NSParameterAssert(formatIsSupported != nullptr);
NSData *header = [inputSource readHeaderOfLength:SFBShortenDetectionSize skipID3v2Tag:NO error:error];
if (header == nil) {
return NO;
}
if ([header isShortenHeader]) {
*formatIsSupported = SFBTernaryTruthValueTrue;
} else {
*formatIsSupported = SFBTernaryTruthValueFalse;
}
return YES;
}
- (BOOL)decodingIsLossless {
return YES;
}
- (BOOL)openReturningError:(NSError **)error {
if (![super openReturningError:error] || ![self parseShortenHeaderReturningError:error]) {
return NO;
}
// Sanity checks
if (_bitsPerSample != 8 && _bitsPerSample != 16) {
os_log_error(gSFBAudioDecoderLog, "Unsupported bit depth: %u", _bitsPerSample);
if (error != nullptr) {
*error = [self unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The audio bit depth is not supported.", @"")];
}
return NO;
}
if ((_bitsPerSample == 8 && _fileType != fileTypeUInt8 && _fileType != fileTypeSInt8) ||
(_bitsPerSample == 16 && _fileType != fileTypeUInt16BE && _fileType != fileTypeUInt16LE &&
_fileType != fileTypeSInt16BE && _fileType != fileTypeSInt16LE)) {
os_log_error(gSFBAudioDecoderLog, "Unsupported bit depth/audio type combination: %u, %u", _bitsPerSample,
_fileType);
if (error != nullptr) {
*error = [self
unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(
@"The audio bit depth and sample type combination is not supported.",
@"")];
}
return NO;
}
if (![self scanForSeekTableReturningError:error]) {
return NO;
}
// Set up the processing format
AudioStreamBasicDescription processingStreamDescription{};
processingStreamDescription.mFormatID = kAudioFormatLinearPCM;
processingStreamDescription.mFormatFlags = kAudioFormatFlagIsNonInterleaved | kAudioFormatFlagIsPacked;
// Apparently *16BE isn't true for 'AIFF'
// if(_fileType == fileTypeUInt16BE || _fileType == fileTypeSInt16BE)
if (_bigEndian) {
processingStreamDescription.mFormatFlags |= kAudioFormatFlagIsBigEndian;
}
if (_fileType == fileTypeSInt8 || _fileType == fileTypeSInt16BE || _fileType == fileTypeSInt16LE) {
processingStreamDescription.mFormatFlags |= kAudioFormatFlagIsSignedInteger;
}
processingStreamDescription.mSampleRate = _sampleRate;
processingStreamDescription.mChannelsPerFrame = static_cast<UInt32>(_channelCount);
processingStreamDescription.mBitsPerChannel = _bitsPerSample;
processingStreamDescription.mBytesPerPacket = (_bitsPerSample + 7) / 8;
processingStreamDescription.mFramesPerPacket = 1;
processingStreamDescription.mBytesPerFrame =
processingStreamDescription.mBytesPerPacket / processingStreamDescription.mFramesPerPacket;
AVAudioChannelLayout *channelLayout = nil;
switch (_channelCount) {
case 1:
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_Mono];
break;
case 2:
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:kAudioChannelLayoutTag_Stereo];
break;
// FIXME: Is there a standard ordering for multichannel files? WAVEFORMATEX?
default:
channelLayout = [AVAudioChannelLayout layoutWithLayoutTag:(kAudioChannelLayoutTag_Unknown | _channelCount)];
break;
}
_processingFormat = [[AVAudioFormat alloc] initWithStreamDescription:&processingStreamDescription
channelLayout:channelLayout];
// Set up the source format
AudioStreamBasicDescription sourceStreamDescription{};
sourceStreamDescription.mFormatID = kSFBAudioFormatShorten;
sourceStreamDescription.mSampleRate = _sampleRate;
sourceStreamDescription.mChannelsPerFrame = static_cast<UInt32>(_channelCount);
sourceStreamDescription.mBitsPerChannel = _bitsPerSample;
sourceStreamDescription.mFramesPerPacket = static_cast<UInt32>(_blocksize);
_sourceFormat = [[AVAudioFormat alloc] initWithStreamDescription:&sourceStreamDescription
channelLayout:channelLayout];
// Populate codec properties
_properties = @{
SFBAudioDecodingPropertiesKeyShortenVersion : @(_version),
SFBAudioDecodingPropertiesKeyShortenFileType : @(_fileType),
SFBAudioDecodingPropertiesKeyShortenNumberChannels : @(_channelCount),
SFBAudioDecodingPropertiesKeyShortenBlockSize : @(_blocksize),
SFBAudioDecodingPropertiesKeyShortenSampleRate : @(_sampleRate),
SFBAudioDecodingPropertiesKeyShortenBitsPerSample : @(_bitsPerSample),
SFBAudioDecodingPropertiesKeyShortenBigEndian : _bigEndian ? @YES : @NO,
};
_framePosition = 0;
_frameBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:_processingFormat
frameCapacity:static_cast<AVAudioFrameCount>(_blocksize)];
// Allocate decoding buffers
_buffer = allocateContiguous2DArray<int32_t>(static_cast<size_t>(_channelCount),
static_cast<size_t>(_blocksize + _wrap));
if (_buffer == nullptr) {
if (error != nullptr) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
}
return NO;
}
_offset = allocateContiguous2DArray<int32_t>(static_cast<size_t>(_channelCount),
static_cast<size_t>(std::max(1, _mean)));
if (_offset == nullptr) {
std::free(_buffer);
if (error != nullptr) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
}
return NO;
}
if (_maxLPC > 0) {
_qlpc = static_cast<int *>(std::malloc(sizeof(int) * _maxLPC));
if (_qlpc == nullptr) {
std::free(_buffer);
std::free(_offset);
if (error != nullptr) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
}
return NO;
}
}
for (auto i = 0; i < _channelCount; ++i) {
for (auto j = 0; j < _wrap; ++j) {
_buffer[i][j] = 0;
}
_buffer[i] += _wrap;
}
// Initialize offset
int32_t mean = 0;
switch (_fileType) {
case fileTypeSInt8:
case fileTypeSInt16BE:
case fileTypeSInt16LE:
mean = 0;
break;
case fileTypeUInt8:
mean = 0x80;
break;
case fileTypeUInt16BE:
case fileTypeUInt16LE:
mean = 0x8000;
break;
default:
os_log_error(gSFBAudioDecoderLog, "Unsupported audio type: %u", _fileType);
return NO;
}
for (auto chan = 0; chan < _channelCount; ++chan) {
for (auto i = 0; i < std::max(1, _mean); ++i) {
_offset[chan][i] = mean;
}
}
return YES;
}
- (BOOL)closeReturningError:(NSError **)error {
if (_buffer != nullptr) {
std::free(_buffer);
_buffer = nullptr;
}
if (_offset != nullptr) {
std::free(_offset);
_offset = nullptr;
}
if (_qlpc != nullptr) {
std::free(_qlpc);
_qlpc = nullptr;
}
_frameBuffer = nil;
return [super closeReturningError:error];
}
- (BOOL)isOpen {
return _buffer != nullptr;
}
- (AVAudioFramePosition)framePosition {
return _framePosition;
}
- (AVAudioFramePosition)frameLength {
return _frameLength;
}
- (BOOL)decodeIntoBuffer:(AVAudioPCMBuffer *)buffer frameLength:(AVAudioFrameCount)frameLength error:(NSError **)error {
NSParameterAssert(buffer != nil);
NSParameterAssert([buffer.format isEqual:_processingFormat]);
// Reset output buffer data size
buffer.frameLength = 0;
frameLength = std::min(frameLength, buffer.frameCapacity);
if (frameLength == 0) {
return YES;
}
AVAudioFrameCount framesDecoded = 0;
for (;;) {
if (const auto framesToCopy = std::min(frameLength - framesDecoded, _frameBuffer.frameLength);
framesToCopy > 0) {
const auto framesCopied = [buffer appendFromBuffer:_frameBuffer
readingFromOffset:0
frameLength:framesToCopy];
[[maybe_unused]] const auto framesTrimmed = [_frameBuffer trimAtOffset:0 frameLength:framesCopied];
#if DEBUG
assert(framesTrimmed == framesCopied);
#endif /* DEBUG */
framesDecoded += framesCopied;
}
// All requested frames were read or EOS reached
if (framesDecoded == frameLength || _eos) {
break;
}
// Decode the next block
if (![self decodeBlockReturningError:error]) {
os_log_error(gSFBAudioDecoderLog, "Error decoding Shorten block");
return NO;
}
}
_framePosition += framesDecoded;
return YES;
}
- (BOOL)supportsSeeking {
return !_seekTableEntries.empty();
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error {
NSParameterAssert(frame >= 0);
if (frame >= self.frameLength) {
if (error != nullptr) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:EINVAL userInfo:nil];
}
return NO;
}
auto entry = std::ranges::upper_bound(_seekTableEntries, frame, {}, &SeekTableEntry::frameNumber_);
if (entry == std::begin(_seekTableEntries)) {
os_log_error(gSFBAudioDecoderLog, "No seek table entry for frame %lld", frame);
if (error != nullptr) {
NSError *seekError = [self genericSeekError];
NSMutableDictionary *userInfo = [seekError.userInfo mutableCopy];
userInfo[NSLocalizedRecoverySuggestionErrorKey] =
NSLocalizedString(@"There is no suitable seek table entry for the requested audio frame.", @"");
*error = [NSError errorWithDomain:seekError.domain code:seekError.code userInfo:userInfo];
}
return NO;
}
entry = std::prev(entry);
#if DEBUG
os_log_debug(gSFBAudioDecoderLog, "Using seek table entry %ld for frame %u to seek to frame %lld",
std::ranges::distance(_seekTableEntries.cbegin(), entry), entry->frameNumber_, frame);
#endif
if (![_inputSource seekToOffset:entry->lastBufferReadPosition_ error:error]) {
return NO;
}
_eos = false;
_input.reset();
if (!_input.refill() || !_input.setState(entry->byteBufferPosition_, entry->bytesAvailable_, entry->bitBuffer_,
entry->bitBufferPosition_)) {
if (error != nullptr) {
NSDictionary *userInfo = nil;
if (_inputSource.url) {
userInfo = [NSDictionary dictionaryWithObject:_inputSource.url forKey:NSURLErrorKey];
}
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:EIO userInfo:userInfo];
}
return NO;
}
_buffer[0][-1] = entry->chanBuf0_[0];
_buffer[0][-2] = entry->chanBuf0_[1];
_buffer[0][-3] = entry->chanBuf0_[2];
if (_channelCount == 2) {
_buffer[1][-1] = entry->chanBuf1_[0];
_buffer[1][-2] = entry->chanBuf1_[1];
_buffer[1][-3] = entry->chanBuf1_[2];
}
for (auto i = 0; i < std::max(1, _mean); ++i) {
_offset[0][i] = entry->offset0_[i];
if (_channelCount == 2) {
_offset[1][i] = entry->offset1_[i];
}
}
_bitshift = entry->bitshift_;
_framePosition = entry->frameNumber_;
_frameBuffer.frameLength = 0;
const auto framesToSkip = static_cast<AVAudioFrameCount>(frame - entry->frameNumber_);
AVAudioFrameCount framesSkipped = 0;
for (;;) {
// All requested frames were skipped or EOS reached
if (framesSkipped == framesToSkip || _eos) {
break;
}
// Decode the next block
if (![self decodeBlockReturningError:error]) {
os_log_error(gSFBAudioDecoderLog, "Error decoding Shorten block");
return NO;
}
if (const auto framesToTrim = std::min(framesToSkip - framesSkipped, _frameBuffer.frameLength);
framesToTrim > 0) {
framesSkipped += [_frameBuffer trimAtOffset:0 frameLength:framesToTrim];
}
}
_framePosition += framesSkipped;
return YES;
}
- (bool)parseShortenHeaderReturningError:(NSError **)error {
// Read magic number
uint32_t magic;
if (![_inputSource readUInt32BigEndian:&magic error:nil] || magic != 'ajkg') {
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")];
}
return false;
}
constexpr auto minSupportedVersion = 1;
constexpr auto maxSupportedVersion = 3;
// Read file version
uint8_t version;
if (![_inputSource readUInt8:&version error:nil] || version < minSupportedVersion ||
version > maxSupportedVersion) {
os_log_error(gSFBAudioDecoderLog, "Unsupported version: %u", version);
if (error != nullptr) {
*error = [self unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The Shorten version is not supported.", @"")];
}
return false;
}
_version = version;
constexpr auto v0DefaultMean = 0;
constexpr auto v2DefaultMean = 4;
// Default mean
_mean = _version < 2 ? v0DefaultMean : v2DefaultMean;
// Set up variable length input
if (!_input.allocate()) {
os_log_error(gSFBAudioDecoderLog, "Unable to allocate variable-length input");
if (error != nullptr) {
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
}
return false;
}
__weak SFBInputSource *inputSource = self->_inputSource;
_input.setInputCallback(^bool(void *buf, size_t len, size_t &read) {
NSInteger bytesRead;
if (![inputSource readBytes:buf length:static_cast<NSInteger>(len) bytesRead:&bytesRead error:nil]) {
return false;
}
read = static_cast<size_t>(bytesRead);
return true;
});
// Read file type
uint32_t fileType;
if (!_input.getUInt32(fileType, _version, parameterFileType)) {
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")];
}
return false;
}
if (fileType != fileTypeUInt8 && fileType != fileTypeSInt8 && fileType != fileTypeUInt16BE &&
fileType != fileTypeUInt16LE && fileType != fileTypeSInt16BE && fileType != fileTypeSInt16LE) {
os_log_error(gSFBAudioDecoderLog, "Unsupported audio type: %u", fileType);
if (error != nullptr) {
*error = [self unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The audio type is invalid or unsupported.", @"")];
}
return false;
}
_fileType = static_cast<int>(fileType);
// Maximum supported channel count
constexpr auto maxChannelCount = 8;
// Read number of channels
uint32_t channelCount = 0;
if (!_input.getUInt32(channelCount, _version, parameterChannelCount) || channelCount == 0 ||
channelCount > maxChannelCount) {
os_log_error(gSFBAudioDecoderLog, "Invalid or unsupported channel count: %u", channelCount);
if (error != nullptr) {
*error = [self unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(
@"The number of channels is invalid or unsupported.", @"")];
}
return false;
}
_channelCount = static_cast<int>(channelCount);
constexpr auto defaultBlockSize = 256;
/// Number of extra samples in buffer
constexpr auto defaultWrap = 3;
// Read blocksize if version > 0
if (_version > 0) {
uint32_t blocksize = 0;
if (!_input.getUInt32(blocksize, _version, static_cast<int>(std::log2(defaultBlockSize))) || blocksize == 0 ||
blocksize > maxBlocksize || blocksize <= defaultWrap) {
os_log_error(gSFBAudioDecoderLog, "Invalid or unsupported block size: %u", blocksize);
if (error != nullptr) {
*error = [self
unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The block size is invalid or unsupported.", @"")];
}
return false;
}
_blocksize = static_cast<int>(blocksize);
uint32_t maxLPC = 0;
if (!_input.getUInt32(maxLPC, _version, parameterQLPC) || maxLPC > 1024) {
os_log_error(gSFBAudioDecoderLog, "Invalid maximum linear predictor order: %u", maxLPC);
if (error != nullptr) {
*error = [self
unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(
@"The maximum linear predictor order is invalid or unsupported.",
@"")];
}
return false;
}
_maxLPC = static_cast<int>(maxLPC);
uint32_t mean = 0;
if (!_input.getUInt32(mean, _version, 0) || mean > 32768) {
os_log_error(gSFBAudioDecoderLog, "Invalid mean: %u", mean);
if (error != nullptr) {
*error = [self unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The mean is invalid or unsupported.", @"")];
}
return false;
}
_mean = static_cast<int>(mean);
uint32_t skipCount;
if (!_input.getUInt32(skipCount, _version, parameterSkipBytes) /* || nskip > bits_remaining_in_input */) {
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")];
}
return false;
}
for (uint32_t i = 0; i < skipCount; ++i) {
uint32_t dummy;
if (!_input.getUInt32(dummy, _version, parameterExtraByte)) {
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")];
}
return false;
}
}
} else {
constexpr auto defaultMaxLPC = 0;
_blocksize = defaultBlockSize;
_maxLPC = defaultMaxLPC;
}
_wrap = std::max(defaultWrap, _maxLPC);
if (_version > 1) {
constexpr auto v2LPCQuantOffset = (1 << parameterQLPC);
_lpcQuantOffset = v2LPCQuantOffset;
}
// Parse the WAVE or AIFF header in the verbatim section
int32_t function;
if (!_input.getRiceGolombCode(function, parameterFunction) || function != functionVerbatim) {
os_log_error(gSFBAudioDecoderLog, "Missing initial verbatim section");
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The initial verbatim section is missing.", @"")];
}
return false;
}
constexpr auto canonicalHeaderSizeBytes = 44;
int32_t headerSize;
if (!_input.getRiceGolombCode(headerSize, parameterVerbatimChunkSize) || headerSize < canonicalHeaderSizeBytes ||
headerSize > verbatimChunkMaxSizeBytes) {
os_log_error(gSFBAudioDecoderLog, "Incorrect header size: %u", headerSize);
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")];
}
return false;
}
std::vector<unsigned char> headerBytes(headerSize);
for (int32_t i = 0; i < headerSize; ++i) {
int32_t byte;
if (!_input.getRiceGolombCode(byte, parameterVerbatimByte)) {
if (error != nullptr) {
*error = [self invalidFormatError:NSLocalizedString(@"Shorten", @"")];
}
return false;
}
headerBytes[i] = static_cast<unsigned char>(byte);
}
// headerBytes is at least canonicalHeaderSizeBytes (44) in size
auto chunkID = OSReadBigInt32(headerBytes.data(), 0);
// auto chunkSize = OSReadBigInt32(headerBytes.data(), 4);
if (chunkID == 'RIFF') {
// WAVE
if (![self parseRIFFChunk:(headerBytes.data() + 8) size:(headerSize - 8) error:error]) {
return false;
}
} else if (chunkID == 'FORM') {
// AIFF
if (![self parseFORMChunk:(headerBytes.data() + 8) size:(headerSize - 8) error:error]) {
return false;
}
} else {
os_log_error(gSFBAudioDecoderLog, "Unsupported data format: %u", chunkID);
if (error != nullptr) {
*error = [self unsupportedFormatError:NSLocalizedString(@"Shorten", @"")
recoverySuggestion:NSLocalizedString(@"The audio data format is not supported.", @"")];
}
return false;
}
return true;
}
- (bool)parseRIFFChunk:(const unsigned char *)chunkData size:(size_t)size error:(NSError **)error {
NSParameterAssert(chunkData != nullptr);
NSParameterAssert(size >= 28);