forked from sbooth/SFBAudioEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSFBShortenDecoder.mm
1603 lines (1356 loc) · 50.3 KB
/
SFBShortenDecoder.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
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
//
// Copyright (c) 2020-2025 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
#import <algorithm>
#import <cmath>
#import <cstring>
#import <vector>
#import <libkern/OSByteOrder.h>
#import <os/log.h>
#import <AVAudioPCMBuffer+SFBBufferUtilities.h>
#import "SFBShortenDecoder.h"
#import "NSData+SFBExtensions.h"
#import "NSError+SFBURLPresentation.h"
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
constexpr auto kMinSupportedVersion = 1;
constexpr auto kMaxSupportedVersion = 3;
constexpr auto kDefaultBlockSize = 256;
constexpr auto kV0DefaultMean = 0;
constexpr auto kV2DefaultMean = 4;
constexpr auto kDefaultMaxLPC = 0;
constexpr auto kChannelCountCodeSize = 0;
constexpr auto kEnergyCodeSize = 3;
constexpr auto kBitshiftCodeSize = 2;
constexpr auto kWrap = 3;
constexpr auto kFunctionCodeSize = 2;
constexpr auto kFunctionDiff0 = 0;
constexpr auto kFunctionDiff1 = 1;
constexpr auto kFunctionDiff2 = 2;
constexpr auto kFunctionDiff3 = 3;
constexpr auto kFunctionQuit = 4;
constexpr auto kFunctionBlocksize = 5;
constexpr auto kFunctionBitshfit = 6;
constexpr auto kFunctionQLPC = 7;
constexpr auto kFunctionZero = 8;
constexpr auto kFunctionVerbatim = 9;
constexpr auto kVerbatimChunkSizeCodeSize = 5;
constexpr auto kVerbatimByteCodeSize = 8;
constexpr auto kVerbatimChunkMaxSizeBytes = 256;
constexpr auto kUInt32CodeSize = 2;
constexpr auto kSkipBytesCodeSize = 1;
constexpr auto kLPCQuantCodeSize = 2;
constexpr auto kExtraByteCodeSize = 7;
constexpr auto kFileTypeCodeSize = 4;
constexpr auto kFileTypeSInt8 = 1;
constexpr auto kFileTypeUInt8 = 2;
constexpr auto kFileTypeSInt16BE = 3;
constexpr auto kFileTypeUInt16BE = 4;
constexpr auto kFileTypeSInt16LE = 5;
constexpr auto kFileTypeUInt16LE = 6;
constexpr auto kSeekTableRevision = 1;
constexpr auto kSeekHeaderSizeBytes = 12;
constexpr auto kSeekTrailerSizeBytes = 12;
constexpr auto kSeekEntrySizeBytes = 80;
constexpr auto kV2LPCQuantOffset = (1 << kLPCQuantCodeSize);
constexpr auto kMaxChannelCount = 8;
constexpr auto kMaxBlocksizeBytes = 65535;
constexpr auto kCanonicalHeaderSizeBytes = 44;
constexpr auto kWAVEFormatPCMTag = 0x0001;
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:
static constexpr uint32_t sMaskTable [] = {
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
};
static constexpr size_t sizeof_uvar(uint32_t val, size_t nbin) noexcept
{
return (val >> nbin) + nbin;
}
static constexpr size_t sizeof_var(int32_t val, size_t nbin) noexcept
{
return static_cast<size_t>(labs(val) >> nbin) + nbin + 1;
}
/// Creates an empty `VariableLengthInput` object
/// - important: `Allocate()` must be called before using
VariableLengthInput() noexcept = default;
~VariableLengthInput()
{
delete [] mByteBuffer;
}
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
{
mInputBlock = 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(mByteBuffer)
return false;
auto byteBuffer = new (std::nothrow) uint8_t [size];
if(!byteBuffer)
return false;
mByteBuffer = byteBuffer;
mByteBufferPosition = mByteBuffer;
mSize = size;
return true;
}
bool GetRiceGolombCode(int32_t& i32, int k) noexcept
{
if(mBitsAvailable == 0 && !RefillBitBuffer())
return false;
int32_t result;
for(result = 0; !(mBitBuffer & (1L << --mBitsAvailable)); ++result) {
if(mBitsAvailable == 0 && !RefillBitBuffer())
return false;
}
while(k != 0) {
if(mBitsAvailable >= k) {
result = (result << k) | static_cast<int32_t>((mBitBuffer >> (mBitsAvailable - k)) & sMaskTable[k]);
mBitsAvailable -= k;
k = 0;
}
else {
result = (result << mBitsAvailable) | static_cast<int32_t>(mBitBuffer & sMaskTable[mBitsAvailable]);
k -= mBitsAvailable;
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, kUInt32CodeSize))
return false;
int32_t i32;
if(!GetRiceGolombCode(i32, k))
return false;
ui32 = static_cast<uint32_t>(i32);
return true;
}
void Reset() noexcept
{
mByteBufferPosition = mByteBuffer;
mBytesAvailable = 0;
mBitsAvailable = 0;
}
bool Refill() noexcept
{
size_t bytesRead = 0;
if(!mInputBlock || !mInputBlock(mByteBuffer, mSize, bytesRead) || bytesRead < 4)
return false;
mBytesAvailable += bytesRead;
mByteBufferPosition = mByteBuffer;
return true;
}
bool SetState(uint16_t byteBufferPosition, uint16_t bytesAvailable, uint32_t bitBuffer, uint16_t bitsAvailable) noexcept
{
if(byteBufferPosition > mBytesAvailable || bytesAvailable > mBytesAvailable - byteBufferPosition || bitsAvailable > 32)
return false;
mByteBufferPosition = mByteBuffer + byteBufferPosition;
mBytesAvailable = bytesAvailable;
mBitBuffer = bitBuffer;
mBitsAvailable = bitsAvailable;
return true;
}
private:
/// Input callback
InputBlock mInputBlock = nil;
/// Size of `mByteBuffer` in bytes
size_t mSize = 0;
/// Byte buffer
uint8_t *mByteBuffer = nullptr;
/// Current position in `mByteBuffer`
uint8_t *mByteBufferPosition = nullptr;
/// Bytes available in `mByteBuffer`
int mBytesAvailable = 0;
/// Bit buffer
uint32_t mBitBuffer = 0;
/// Bits available in `mBitBuffer`
int mBitsAvailable = 0;
/// Reads a single `uint32_t` from the byte buffer, refilling if necessary
bool RefillBitBuffer() noexcept
{
if(mBytesAvailable < 4 && !Refill())
return false;
mBitBuffer = static_cast<uint32_t>((static_cast<int32_t>(mByteBufferPosition[0]) << 24) | (static_cast<int32_t>(mByteBufferPosition[1]) << 16) | (static_cast<int32_t>(mByteBufferPosition[2]) << 8) | static_cast<int32_t>(mByteBufferPosition[3]));
mByteBufferPosition += 4;
mBytesAvailable -= 4;
mBitsAvailable = 32;
return true;
}
};
/// Shorten seek table header
struct SeekTableHeader
{
int8_t mSignature [4];
uint32_t mVersion;
uint32_t mFileSize;
};
SeekTableHeader ParseSeekTableHeader(const void *buf)
{
SeekTableHeader header;
std::memcpy(header.mSignature, buf, 4);
header.mVersion = OSReadLittleInt32(buf, 4);
header.mFileSize = OSReadLittleInt32(buf, 8);
return header;
}
/// Shorten seek table trailer
struct SeekTableTrailer
{
uint32_t mSeekTableSize;
int8_t mSignature [8];
};
SeekTableTrailer ParseSeekTableTrailer(const void *buf)
{
SeekTableTrailer trailer;
trailer.mSeekTableSize = OSReadLittleInt32(buf, 0);
std::memcpy(trailer.mSignature, static_cast<const uint8_t *>(buf) + 4, 8);
return trailer;
}
/// A Shorten seek table entry
struct SeekTableEntry
{
uint32_t mFrameNumber;
uint32_t mByteOffsetInFile;
uint32_t mLastBufferReadPosition;
uint16_t mBytesAvailable;
uint16_t mByteBufferPosition;
uint16_t mBitBufferPosition;
uint32_t mBitBuffer;
uint16_t mBitshift;
int32_t mCBuf0 [3];
int32_t mCBuf1 [3];
int32_t mOffset0 [4];
int32_t mOffset1 [4];
};
SeekTableEntry ParseSeekTableEntry(const void *buf)
{
SeekTableEntry entry;
entry.mFrameNumber = OSReadLittleInt32(buf, 0);
entry.mByteOffsetInFile = OSReadLittleInt32(buf, 4);
entry.mLastBufferReadPosition = OSReadLittleInt32(buf, 8);
entry.mBytesAvailable = OSReadLittleInt16(buf, 12);
entry.mByteBufferPosition = OSReadLittleInt16(buf, 14);
entry.mBitBufferPosition = OSReadLittleInt16(buf, 16);
entry.mBitBuffer = OSReadLittleInt32(buf, 18);
entry.mBitshift = OSReadLittleInt16(buf, 22);
for(auto i = 0; i < 3; ++i)
entry.mCBuf0[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 24 + 4 * i));
for(auto i = 0; i < 3; ++i)
entry.mCBuf1[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 36 + 4 * i));
for(auto i = 0; i < 4; ++i)
entry.mOffset0[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 48 + 4 * i));
for(auto i = 0; i < 4; ++i)
entry.mOffset1[i] = static_cast<int32_t>(OSReadLittleInt32(buf, 64 + 4 * i));
return entry;
}
/// Locates the most suitable seek table entry for `frame`
std::vector<SeekTableEntry>::const_iterator FindSeekTableEntry(std::vector<SeekTableEntry>::const_iterator begin, std::vector<SeekTableEntry>::const_iterator end, AVAudioFramePosition frame)
{
auto it = std::upper_bound(begin, end, frame, [](AVAudioFramePosition value, const SeekTableEntry& entry) {
return value < entry.mFrameNumber;
});
return it == begin ? end : --it;
}
/// Returns a generic error for an invalid Shorten file
NSError * GenericShortenInvalidFormatErrorForURL(NSURL * _Nonnull url) noexcept
{
return [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid Shorten file.", @"")
url:url
failureReason:NSLocalizedString(@"Not a valid Shorten file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
}
} /* 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 uint8_t *)chunkData size:(size_t)size error:(NSError **)error;
- (BOOL)parseFORMChunk:(const uint8_t *)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 != NULL);
NSData *header = [inputSource readHeaderOfLength:SFBShortenDetectionSize skipID3v2Tag:NO error:error];
if(!header)
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)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a supported Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Unsupported bit depth", @"")
recoverySuggestion:NSLocalizedString(@"The file's bit depth is not supported.", @"")];
return NO;
}
if((_bitsPerSample == 8 && !(_fileType == kFileTypeUInt8 || _fileType == kFileTypeSInt8)) || (_bitsPerSample == 16 && !(_fileType == kFileTypeUInt16BE || _fileType == kFileTypeUInt16LE || _fileType == kFileTypeSInt16BE || _fileType == kFileTypeSInt16LE))) {
os_log_error(gSFBAudioDecoderLog, "Unsupported bit depth/audio type combination: %u, %u", _bitsPerSample, _fileType);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a supported Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Unsupported bit depth/audio type combination", @"")
recoverySuggestion:NSLocalizedString(@"The file's bit depth and audio type 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 == kFileTypeUInt16BE || _fileType == kFileTypeSInt16BE)
if(_bigEndian)
processingStreamDescription.mFormatFlags |= kAudioFormatFlagIsBigEndian;
if(_fileType == kFileTypeSInt8 || _fileType == kFileTypeSInt16BE || _fileType == kFileTypeSInt16LE)
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,
};
_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) {
if(error)
*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) {
std::free(_buffer);
if(error)
*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;
}
if(_maxLPC > 0)
_qlpc = new int [static_cast<size_t>(_maxLPC)];
// Initialize offset
int32_t mean = 0;
switch(_fileType) {
case kFileTypeSInt8:
case kFileTypeSInt16BE:
case kFileTypeSInt16LE:
mean = 0;
break;
case kFileTypeUInt8:
mean = 0x80;
break;
case kFileTypeUInt16BE:
case kFileTypeUInt16LE:
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) {
std::free(_buffer);
_buffer = nullptr;
}
if(_offset) {
std::free(_offset);
_offset = nullptr;
}
if(_qlpc) {
delete [] _qlpc;
_qlpc = nullptr;
}
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;
if(frameLength > buffer.frameCapacity)
frameLength = buffer.frameCapacity;
if(frameLength == 0)
return YES;
AVAudioFrameCount framesProcessed = 0;
for(;;) {
AVAudioFrameCount framesRemaining = frameLength - framesProcessed;
AVAudioFrameCount framesCopied = [buffer appendFromBuffer:_frameBuffer readingFromOffset:0 frameLength:framesRemaining];
[_frameBuffer trimAtOffset:0 frameLength:framesCopied];
framesProcessed += framesCopied;
// All requested frames were read or EOS reached
if(framesProcessed == frameLength || _eos)
break;
// Decode the next _blocksize frames
if(![self decodeBlockReturningError:error]) {
os_log_error(gSFBAudioDecoderLog, "Error decoding Shorten block");
return NO;
}
}
_framePosition += framesProcessed;
return YES;
}
- (BOOL)supportsSeeking
{
return !_seekTableEntries.empty();
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error
{
NSParameterAssert(frame >= 0);
if(frame >= self.frameLength)
return NO;
auto entry = FindSeekTableEntry(_seekTableEntries.cbegin(), _seekTableEntries.cend(), frame);
if(entry == _seekTableEntries.end()) {
os_log_error(gSFBAudioDecoderLog, "No seek table entry for frame %lld", frame);
return NO;
}
#if DEBUG
os_log_debug(gSFBAudioDecoderLog, "Using seek table entry %ld for frame %d to seek to frame %lld", std::distance(_seekTableEntries.cbegin(), entry), entry->mFrameNumber, frame);
#endif
if(![_inputSource seekToOffset:entry->mLastBufferReadPosition error:error])
return NO;
_input.Reset();
if(!_input.Refill() || !_input.SetState(entry->mByteBufferPosition, entry->mBytesAvailable, entry->mBitBuffer, entry->mBitBufferPosition))
return NO;
_buffer[0][-1] = entry->mCBuf0[0];
_buffer[0][-2] = entry->mCBuf0[1];
_buffer[0][-3] = entry->mCBuf0[2];
if(_channelCount == 2) {
_buffer[1][-1] = entry->mCBuf1[0];
_buffer[1][-2] = entry->mCBuf1[1];
_buffer[1][-3] = entry->mCBuf1[2];
}
for(auto i = 0; i < std::max(1, _mean); ++i) {
_offset[0][i] = entry->mOffset0[i];
if(_channelCount == 2)
_offset[1][i] = entry->mOffset1[i];
}
_bitshift = entry->mBitshift;
_framePosition = entry->mFrameNumber;
_frameBuffer.frameLength = 0;
AVAudioFrameCount framesToSkip = static_cast<AVAudioFrameCount>(frame - entry->mFrameNumber);
AVAudioFrameCount framesSkipped = 0;
for(;;) {
// Decode the next _blocksize frames
if(![self decodeBlockReturningError:error])
os_log_error(gSFBAudioDecoderLog, "Error decoding Shorten block");
AVAudioFrameCount framesToTrim = std::min(framesToSkip - framesSkipped, _frameBuffer.frameLength);
[_frameBuffer trimAtOffset:0 frameLength:framesToTrim];
framesSkipped += framesToTrim;
// All requested frames were skipped or EOS reached
if(framesSkipped == framesToSkip || _eos)
break;
}
_framePosition += framesSkipped;
return YES;
}
- (BOOL)parseShortenHeaderReturningError:(NSError **)error
{
// Read magic number
uint32_t magic;
if(![_inputSource readUInt32BigEndian:&magic error:nil] || magic != 'ajkg') {
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a valid Shorten file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
// Read file version
uint8_t version;
if(![_inputSource readUInt8:&version error:nil] || version < kMinSupportedVersion || version > kMaxSupportedVersion) {
os_log_error(gSFBAudioDecoderLog, "Unsupported version: %u", version);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a supported Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Version not supported", @"")
recoverySuggestion:NSLocalizedString(@"The file's version is not supported.", @"")];
return NO;
}
_version = version;
// Default mean
_mean = _version < 2 ? kV0DefaultMean : kV2DefaultMean;
// Set up variable length input
if(!_input.Allocate()) {
os_log_error(gSFBAudioDecoderLog, "Unable to allocate variable-length input");
if(error)
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
return NO;
}
__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, kFileTypeCodeSize)) {
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
if(fileType != kFileTypeUInt8 && fileType != kFileTypeSInt8 && fileType != kFileTypeUInt16BE && fileType != kFileTypeUInt16LE && fileType != kFileTypeSInt16BE && fileType != kFileTypeSInt16LE) {
os_log_error(gSFBAudioDecoderLog, "Unsupported audio type: %u", fileType);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Invalid or unsupported audio type", @"")
recoverySuggestion:NSLocalizedString(@"The file contains an invalid or unsupported audio type.", @"")];
return NO;
}
_fileType = static_cast<int>(fileType);
// Read number of channels
uint32_t channelCount = 0;
if(!_input.GetUInt32(channelCount, _version, kChannelCountCodeSize) || channelCount == 0 || channelCount > kMaxChannelCount) {
os_log_error(gSFBAudioDecoderLog, "Invalid or unsupported channel count: %u", channelCount);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Invalid or unsupported number of channels", @"")
recoverySuggestion:NSLocalizedString(@"The file contains an invalid or unsupported number of channels.", @"")];
return NO;
}
_channelCount = static_cast<int>(channelCount);
// Read blocksize if version > 0
if(_version > 0) {
uint32_t blocksize = 0;
if(!_input.GetUInt32(blocksize, _version, static_cast<int>(std::log2(kDefaultBlockSize))) || blocksize == 0 || blocksize > kMaxBlocksizeBytes) {
os_log_error(gSFBAudioDecoderLog, "Invalid or unsupported block size: %u", blocksize);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Invalid or unsupported block size", @"")
recoverySuggestion:NSLocalizedString(@"The file contains an invalid or unsupported block size.", @"")];
return NO;
}
_blocksize = static_cast<int>(blocksize);
uint32_t maxLPC = 0;
if(!_input.GetUInt32(maxLPC, _version, kLPCQuantCodeSize) || maxLPC > 1024) {
os_log_error(gSFBAudioDecoderLog, "Invalid max lpc: %u", maxLPC);
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
_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)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
_mean = static_cast<int>(mean);
uint32_t skipCount;
if(!_input.GetUInt32(skipCount, _version, kSkipBytesCodeSize) /* || nskip > bits_remaining_in_input */) {
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
for(uint32_t i = 0; i < skipCount; ++i) {
uint32_t dummy;
if(!_input.GetUInt32(dummy, _version, kExtraByteCodeSize)) {
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
}
}
else {
_blocksize = kDefaultBlockSize;
_maxLPC = kDefaultMaxLPC;
}
_wrap = std::max(kWrap, static_cast<int>(_maxLPC));
if(_version > 1)
_lpcQuantOffset = kV2LPCQuantOffset;
// Parse the WAVE or AIFF header in the verbatim section
int32_t function;
if(!_input.GetRiceGolombCode(function, kFunctionCodeSize) || function != kFunctionVerbatim) {
os_log_error(gSFBAudioDecoderLog, "Missing initial verbatim section");
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a supported Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Missing initial verbatim section", @"")
recoverySuggestion:NSLocalizedString(@"The file is missing the initial verbatim section.", @"")];
return NO;
}
int32_t headerSize;
if(!_input.GetRiceGolombCode(headerSize, kVerbatimChunkSizeCodeSize) || headerSize < kCanonicalHeaderSizeBytes || headerSize > kVerbatimChunkMaxSizeBytes) {
os_log_error(gSFBAudioDecoderLog, "Incorrect header size: %u", headerSize);
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
uint8_t headerBytes [headerSize];
for(int32_t i = 0; i < headerSize; ++i) {
int32_t byte;
if(!_input.GetRiceGolombCode(byte, kVerbatimByteCodeSize)) {
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
headerBytes[i] = static_cast<uint8_t>(byte);
}
// header_bytes is at least kCanonicalHeaderSizeBytes (44) in size
auto chunkID = OSReadBigInt32(headerBytes, 0);
// auto chunkSize = OSReadBigInt32(header_bytes, 4);
// WAVE
if(chunkID == 'RIFF') {
if(![self parseRIFFChunk:(headerBytes + 8) size:(headerSize - 8) error:error])
return NO;
}
// AIFF
else if(chunkID == 'FORM') {
if(![self parseFORMChunk:(headerBytes + 8) size:(headerSize - 8) error:error])
return NO;
}
else {
os_log_error(gSFBAudioDecoderLog, "Unsupported data format: %u", chunkID);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a supported Shorten file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Unsupported data format", @"")
recoverySuggestion:NSLocalizedString(@"The file's data format is not supported.", @"")];
return NO;
}
return YES;
}
- (BOOL)parseRIFFChunk:(const uint8_t *)chunkData size:(size_t)size error:(NSError **)error
{
NSParameterAssert(chunkData != nullptr);
NSParameterAssert(size >= 28);
uintptr_t offset = 0;
auto chunkID = OSReadBigInt32(chunkData, offset);
offset += 4;
if(chunkID != 'WAVE') {
os_log_error(gSFBAudioDecoderLog, "Missing 'WAVE' in 'RIFF' chunk");
if(error)
*error = GenericShortenInvalidFormatErrorForURL(_inputSource.url);
return NO;
}
auto sawFormatChunk = false;
uint32_t dataChunkSize = 0;
uint16_t blockAlign = 0;
while(offset < size) {
chunkID = OSReadBigInt32(chunkData, offset);
offset += 4;
auto chunkSize = OSReadLittleInt32(chunkData, offset);
offset += 4;
switch(chunkID) {