forked from sbooth/SFBAudioEngine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSFBTrueAudioDecoder.mm
324 lines (250 loc) · 9.71 KB
/
SFBTrueAudioDecoder.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
//
// Copyright (c) 2011-2025 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
#import <algorithm>
#import <memory>
#import <os/log.h>
#import <tta-cpp/libtta.h>
#import "SFBTrueAudioDecoder.h"
#import "NSData+SFBExtensions.h"
#import "NSError+SFBURLPresentation.h"
SFBAudioDecoderName const SFBAudioDecoderNameTrueAudio = @"org.sbooth.AudioEngine.Decoder.TrueAudio";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyTrueAudioFormat = @"format";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyTrueAudioNumberChannels = @"nch";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyTrueAudioBitsPerSample = @"bps";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyTrueAudioSampleRate = @"sps";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyTrueAudioSamples = @"samples";
namespace {
struct TTACallbacks final : TTA_io_callback
{
SFBAudioDecoder *mDecoder;
};
TTAint32 read_callback(struct _tag_TTA_io_callback *io, TTAuint8 *buffer, TTAuint32 size) noexcept
{
TTACallbacks *iocb = static_cast<TTACallbacks *>(io);
NSInteger bytesRead;
if(![iocb->mDecoder->_inputSource readBytes:buffer length:size bytesRead:&bytesRead error:nil])
return -1;
return static_cast<TTAint32>(bytesRead);
}
TTAint64 seek_callback(struct _tag_TTA_io_callback *io, TTAint64 offset) noexcept
{
TTACallbacks *iocb = static_cast<TTACallbacks *>(io);
if(![iocb->mDecoder->_inputSource seekToOffset:offset error:nil])
return -1;
return offset;
}
} /* namespace */
@interface SFBTrueAudioDecoder ()
{
@private
std::unique_ptr<tta::tta_decoder> _decoder;
std::unique_ptr<TTACallbacks> _callbacks;
AVAudioFramePosition _framePosition;
AVAudioFramePosition _frameLength;
TTAuint32 _framesToSkip;
}
@end
@implementation SFBTrueAudioDecoder
+ (void)load
{
[SFBAudioDecoder registerSubclass:[self class]];
}
+ (NSSet *)supportedPathExtensions
{
return [NSSet setWithObject:@"tta"];
}
+ (NSSet *)supportedMIMETypes
{
return [NSSet setWithObject:@"audio/x-tta"];
}
+ (SFBAudioDecoderName)decoderName
{
return SFBAudioDecoderNameTrueAudio;
}
+ (BOOL)testInputSource:(SFBInputSource *)inputSource formatIsSupported:(SFBTernaryTruthValue *)formatIsSupported error:(NSError **)error
{
NSParameterAssert(inputSource != nil);
NSParameterAssert(formatIsSupported != NULL);
NSData *header = [inputSource readHeaderOfLength:SFBTrueAudioDetectionSize skipID3v2Tag:YES error:error];
if(!header)
return NO;
if([header isTrueAudioHeader])
*formatIsSupported = SFBTernaryTruthValueTrue;
else
*formatIsSupported = SFBTernaryTruthValueFalse;
return YES;
}
- (BOOL)decodingIsLossless
{
return YES;
}
- (BOOL)openReturningError:(NSError **)error
{
if(![super openReturningError:error])
return NO;
_callbacks = std::make_unique<TTACallbacks>();
_callbacks->read = read_callback;
_callbacks->write = nullptr;
_callbacks->seek = seek_callback;
_callbacks->mDecoder = self;
TTA_info streamInfo;
try {
_decoder = std::make_unique<tta::tta_decoder>(static_cast<TTA_io_callback *>(_callbacks.get()));
_decoder->init_get_info(&streamInfo, 0);
}
catch(const tta::tta_exception& e) {
os_log_error(gSFBAudioDecoderLog, "Error creating True Audio decoder: %d", e.code());
return NO;
}
if(!_decoder) {
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid True Audio file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a True Audio file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
AVAudioChannelLayout *channelLayout = nil;
switch(streamInfo.nch) {
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 | streamInfo.nch)];
break;
}
AudioStreamBasicDescription processingStreamDescription{};
processingStreamDescription.mFormatID = kAudioFormatLinearPCM;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion"
processingStreamDescription.mFormatFlags = kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsSignedInteger;
#pragma clang diagnostic pop
processingStreamDescription.mSampleRate = streamInfo.sps;
processingStreamDescription.mChannelsPerFrame = streamInfo.nch;
processingStreamDescription.mBitsPerChannel = streamInfo.bps;
processingStreamDescription.mBytesPerPacket = ((streamInfo.bps + 7) / 8) * processingStreamDescription.mChannelsPerFrame;
processingStreamDescription.mFramesPerPacket = 1;
processingStreamDescription.mBytesPerFrame = processingStreamDescription.mBytesPerPacket / processingStreamDescription.mFramesPerPacket;
processingStreamDescription.mReserved = 0;
// True Audio supports 16 to 24 bits per sample
switch(streamInfo.bps) {
case 16:
case 24:
processingStreamDescription.mFormatFlags |= kAudioFormatFlagIsPacked;
break;
case 17 ... 23:
// Align high because Apple's AudioConverter doesn't handle low alignment
processingStreamDescription.mFormatFlags |= kAudioFormatFlagIsAlignedHigh;
break;
default:
{
os_log_error(gSFBAudioDecoderLog, "Unsupported bit depth: %d", streamInfo.bps);
_decoder.reset();
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a supported True Audio file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Bit depth not supported", @"")
recoverySuggestion:NSLocalizedString(@"The file's bit depth is not supported.", @"")];
return NO;
}
}
_processingFormat = [[AVAudioFormat alloc] initWithStreamDescription:&processingStreamDescription channelLayout:channelLayout];
_frameLength = streamInfo.samples;
// Set up the source format
AudioStreamBasicDescription sourceStreamDescription{};
sourceStreamDescription.mFormatID = kSFBAudioFormatTrueAudio;
sourceStreamDescription.mSampleRate = streamInfo.sps;
sourceStreamDescription.mChannelsPerFrame = streamInfo.nch;
sourceStreamDescription.mBitsPerChannel = streamInfo.bps;
_sourceFormat = [[AVAudioFormat alloc] initWithStreamDescription:&sourceStreamDescription channelLayout:channelLayout];
// Populate codec properties
_properties = @{
SFBAudioDecodingPropertiesKeyTrueAudioFormat: @(streamInfo.format),
SFBAudioDecodingPropertiesKeyTrueAudioNumberChannels: @(streamInfo.nch),
SFBAudioDecodingPropertiesKeyTrueAudioBitsPerSample: @(streamInfo.bps),
SFBAudioDecodingPropertiesKeyTrueAudioSampleRate: @(streamInfo.sps),
SFBAudioDecodingPropertiesKeyTrueAudioSamples: @(streamInfo.samples),
};
return YES;
}
- (BOOL)closeReturningError:(NSError **)error
{
_decoder.reset();
_callbacks.reset();
return [super closeReturningError:error];
}
- (BOOL)isOpen
{
return _decoder != 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;
try {
while(_framesToSkip > 0) {
auto framesToSkip = std::min(_framesToSkip, frameLength);
auto bytesToSkip = framesToSkip * _processingFormat.streamDescription->mBytesPerFrame;
auto framesSkipped = _decoder->process_stream(static_cast<TTAuint8 *>(buffer.audioBufferList->mBuffers[0].mData), bytesToSkip);
// EOS reached finishing seek
if(framesSkipped == 0)
return YES;
_framesToSkip -= static_cast<TTAuint32>(framesSkipped);
}
auto bytesToRead = frameLength * _processingFormat.streamDescription->mBytesPerFrame;
auto framesRead = static_cast<AVAudioFrameCount>(_decoder->process_stream(static_cast<TTAuint8 *>(buffer.audioBufferList->mBuffers[0].mData), bytesToRead));
// EOS
if(framesRead == 0)
return YES;
buffer.frameLength = framesRead;
_framePosition += framesRead;
return YES;
}
catch(const tta::tta_exception& e) {
os_log_error(gSFBAudioDecoderLog, "True Audio decoding error: %d", e.code());
if(error)
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain code:SFBAudioDecoderErrorCodeInternalError userInfo:@{ NSURLErrorKey: _inputSource.url }];
return NO;
}
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error
{
NSParameterAssert(frame >= 0);
TTAuint32 seconds = static_cast<TTAuint32>(frame / _processingFormat.sampleRate);
TTAuint32 frame_start = 0;
try {
_decoder->set_position(seconds, &frame_start);
}
catch(const tta::tta_exception& e) {
os_log_error(gSFBAudioDecoderLog, "True Audio seek error: %d", e.code());
if(error)
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain code:SFBAudioDecoderErrorCodeInternalError userInfo:@{ NSURLErrorKey: _inputSource.url }];
return NO;
}
_framePosition = frame;
// We need to skip some samples from start of the frame if required
_framesToSkip = static_cast<UInt32>((seconds - frame_start) * _processingFormat.sampleRate + 0.5);
return YES;
}
@end