-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathSFBDoPDecoder.m
More file actions
305 lines (239 loc) · 10.5 KB
/
Copy pathSFBDoPDecoder.m
File metadata and controls
305 lines (239 loc) · 10.5 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
//
// SPDX-FileCopyrightText: 2014 Stephen F. Booth <contact@sbooth.dev>
// SPDX-License-Identifier: MIT
//
// Part of https://github.com/sbooth/SFBAudioEngine
//
#import "SFBDoPDecoder.h"
#import "SFBAudioDecoder+Internal.h"
#import "SFBDSDDecoder.h"
#import "SFBLocalizedNameForURL.h"
#import <os/log.h>
#import <stdint.h>
#define DSD_PACKETS_PER_DOP_FRAME (16 / kSFBPCMFramesPerDSDPacket)
#define BUFFER_SIZE_PACKETS 4096
// Bit reversal lookup table from http://graphics.stanford.edu/~seander/bithacks.html#BitReverseTable
static const unsigned char sBitReverseTable256[256] = {
#define R2(n) n, n + 2 * 64, n + 1 * 64, n + 3 * 64
#define R4(n) R2(n), R2(n + 2 * 16), R2(n + 1 * 16), R2(n + 3 * 16)
#define R6(n) R4(n), R4(n + 2 * 4), R4(n + 1 * 4), R4(n + 3 * 4)
R6(0), R6(2), R6(1), R6(3)};
// Support DSD64, DSD128, and DSD256 (64x, 128x, and 256x the CD sample rate of 44.1 kHz)
// as well as the 48.0 kHz variants 6.144 MHz and 12.288 MHz
static BOOL IsSupportedDoPSampleRate(Float64 sampleRate) {
switch ((uint32_t)sampleRate) {
case kSFBSampleRateDSD64:
case kSFBSampleRateDSD128:
case kSFBSampleRateDSD256:
case kSFBSampleRateDSD128Variant:
case kSFBSampleRateDSD256Variant:
return YES;
default:
return NO;
}
}
@interface SFBDoPDecoder () {
@private
AVAudioCompressedBuffer *_buffer;
unsigned char _marker;
BOOL _reverseBits;
}
@end
@implementation SFBDoPDecoder
@synthesize processingFormat = _processingFormat;
- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error {
NSParameterAssert(url != nil);
SFBInputSource *inputSource = [SFBInputSource inputSourceForURL:url flags:0 error:error];
if (!inputSource) {
return nil;
}
return [self initWithInputSource:inputSource error:error];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource error:(NSError **)error {
NSParameterAssert(inputSource != nil);
SFBDSDDecoder *decoder = [[SFBDSDDecoder alloc] initWithInputSource:inputSource error:error];
if (!decoder) {
return nil;
}
return [self initWithDecoder:decoder error:error];
}
- (instancetype)initWithDecoder:(id<SFBDSDDecoding>)decoder error:(NSError **)error {
NSParameterAssert(decoder != nil);
if ((self = [super init])) {
_decoder = decoder;
_marker = 0x05;
}
return self;
}
- (SFBInputSource *)inputSource {
return _decoder.inputSource;
}
- (AVAudioFormat *)sourceFormat {
return _decoder.sourceFormat;
}
- (BOOL)decodingIsLossless {
return _decoder.decodingIsLossless;
}
- (NSDictionary *)properties {
return _decoder.properties;
}
- (BOOL)openReturningError:(NSError **)error {
if (!_decoder.isOpen && ![_decoder openReturningError:error]) {
return NO;
}
const AudioStreamBasicDescription *asbd = _decoder.processingFormat.streamDescription;
if (asbd->mFormatID != kSFBAudioFormatDSD) {
if (error) {
NSMutableDictionary *userInfo = [NSMutableDictionary
dictionaryWithObject:NSLocalizedString(@"DSD over PCM requires DSD audio input.", @"")
forKey:NSLocalizedRecoverySuggestionErrorKey];
if (_decoder.inputSource.url != nil) {
userInfo[NSLocalizedDescriptionKey] =
[NSString localizedStringWithFormat:NSLocalizedString(@"The file “%@” is not a DSD file.", @""),
SFBLocalizedNameForURL(_decoder.inputSource.url)];
userInfo[NSURLErrorKey] = _decoder.inputSource.url;
} else {
userInfo[NSLocalizedDescriptionKey] = NSLocalizedString(@"The file is not a DSD file.", @"");
}
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
userInfo:userInfo];
}
return NO;
}
if (!IsSupportedDoPSampleRate(asbd->mSampleRate)) {
os_log_error(gSFBAudioDecoderLog, "Unsupported DSD sample rate for DoP: %g", asbd->mSampleRate);
if (error) {
NSMutableDictionary *userInfo = [NSMutableDictionary
dictionaryWithObject:NSLocalizedString(@"The sample rate is not supported for DSD over PCM.", @"")
forKey:NSLocalizedRecoverySuggestionErrorKey];
if (_decoder.inputSource.url != nil) {
userInfo[NSLocalizedDescriptionKey] = [NSString
localizedStringWithFormat:NSLocalizedString(@"The format of the file “%@” is not supported.",
@""),
SFBLocalizedNameForURL(_decoder.inputSource.url)];
userInfo[NSURLErrorKey] = _decoder.inputSource.url;
} else {
userInfo[NSLocalizedDescriptionKey] =
NSLocalizedString(@"The format of the file is not supported.", @"");
}
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
userInfo:userInfo];
}
return NO;
}
_reverseBits = (asbd->mFormatFlags & kAudioFormatFlagIsBigEndian) == 0;
// Generate non-interleaved 24-bit big endian output
AudioStreamBasicDescription processingStreamDescription = {0};
processingStreamDescription.mFormatID = kAudioFormatLinearPCM /*kSFBAudioFormatDoP*/;
processingStreamDescription.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked |
kAudioFormatFlagIsNonInterleaved | kAudioFormatFlagIsBigEndian;
processingStreamDescription.mSampleRate =
asbd->mSampleRate / (kSFBPCMFramesPerDSDPacket * DSD_PACKETS_PER_DOP_FRAME);
processingStreamDescription.mChannelsPerFrame = asbd->mChannelsPerFrame;
processingStreamDescription.mBitsPerChannel = 24;
processingStreamDescription.mBytesPerPacket = 3;
processingStreamDescription.mFramesPerPacket = 1;
processingStreamDescription.mBytesPerFrame =
processingStreamDescription.mBytesPerPacket / processingStreamDescription.mFramesPerPacket;
_processingFormat = [[AVAudioFormat alloc] initWithStreamDescription:&processingStreamDescription
channelLayout:_decoder.processingFormat.channelLayout];
_buffer = [[AVAudioCompressedBuffer alloc]
initWithFormat:_decoder.processingFormat
packetCapacity:BUFFER_SIZE_PACKETS
maximumPacketSize:(kSFBBytesPerDSDPacketPerChannel * _decoder.processingFormat.channelCount)];
_buffer.packetCount = 0;
return YES;
}
- (BOOL)closeReturningError:(NSError **)error {
_buffer = nil;
return [_decoder closeReturningError:error];
}
- (BOOL)isOpen {
return _buffer != nil;
}
- (AVAudioFramePosition)framePosition {
return _decoder.packetPosition / DSD_PACKETS_PER_DOP_FRAME;
}
- (AVAudioFramePosition)frameLength {
return _decoder.packetCount / DSD_PACKETS_PER_DOP_FRAME;
}
- (BOOL)decodeIntoBuffer:(AVAudioBuffer *)buffer error:(NSError **)error {
NSParameterAssert(buffer != nil);
NSParameterAssert([buffer isKindOfClass:[AVAudioPCMBuffer class]]);
return [self decodeIntoBuffer:(AVAudioPCMBuffer *)buffer
frameLength:((AVAudioPCMBuffer *)buffer).frameCapacity
error:error];
}
- (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 = MIN(frameLength, buffer.frameCapacity);
if (frameLength == 0) {
return YES;
}
AVAudioFrameCount framesRead = 0;
for (;;) {
AVAudioFrameCount framesRemaining = frameLength - framesRead;
// Grab the DSD audio
AVAudioPacketCount dsdPacketsRemaining = framesRemaining * DSD_PACKETS_PER_DOP_FRAME;
if (![_decoder decodeIntoBuffer:_buffer
packetCount:MIN(_buffer.packetCapacity, dsdPacketsRemaining)
error:error]) {
return NO;
}
AVAudioPacketCount dsdPacketsDecoded = _buffer.packetCount;
if (dsdPacketsDecoded == 0) {
break;
}
// Convert to DoP
// NB: Currently DSDIFFDecoder and DSFDecoder only produce interleaved output
AVAudioFrameCount framesDecoded = dsdPacketsDecoded / DSD_PACKETS_PER_DOP_FRAME;
unsigned char marker = _marker;
AVAudioChannelCount channelCount = _processingFormat.channelCount;
for (AVAudioChannelCount channel = 0; channel < channelCount; ++channel) {
const unsigned char *input = (const unsigned char *)_buffer.data + channel;
unsigned char *output = (unsigned char *)buffer.audioBufferList->mBuffers[channel].mData +
buffer.audioBufferList->mBuffers[channel].mDataByteSize;
// The DoP marker should match across channels
marker = _marker;
for (AVAudioFrameCount i = 0; i < framesDecoded; ++i) {
// Insert the DoP marker
*output++ = marker;
// Copy the DSD bits
*output++ = _reverseBits ? sBitReverseTable256[*input] : *input;
input += channelCount;
*output++ = _reverseBits ? sBitReverseTable256[*input] : *input;
input += channelCount;
marker = marker == 0x05 ? 0xfa : 0x05;
}
}
_marker = marker;
buffer.frameLength += framesDecoded;
framesRead += framesDecoded;
// All requested frames were read
if (framesRead == frameLength) {
break;
}
}
return YES;
}
- (BOOL)supportsSeeking {
return _decoder.supportsSeeking;
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error {
NSParameterAssert(frame >= 0);
if (![_decoder seekToPacket:(frame * DSD_PACKETS_PER_DOP_FRAME) error:error]) {
return NO;
}
_buffer.packetCount = 0;
_buffer.byteLength = 0;
return YES;
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ %p: %@>", [self class], (__bridge void *)self, _decoder];
}
@end