-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathSFBMonkeysAudioDecoder.mm
392 lines (316 loc) · 15.2 KB
/
SFBMonkeysAudioDecoder.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
//
// Copyright (c) 2011-2025 Stephen F. Booth <me@sbooth.org>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
#import <memory>
#import <os/log.h>
#define PLATFORM_APPLE
#include <MAC/All.h>
#include <MAC/IO.h>
#include <MAC/MACLib.h>
#undef PLATFORM_APPLE
#import "SFBMonkeysAudioDecoder.h"
#import "NSData+SFBExtensions.h"
#import "NSError+SFBURLPresentation.h"
SFBAudioDecoderName const SFBAudioDecoderNameMonkeysAudio = @"org.sbooth.AudioEngine.Decoder.MonkeysAudio";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioFileVersion = @"APE_INFO_FILE_VERSION";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioCompressionLevel = @"APE_INFO_COMPRESSION_LEVEL";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioFormatFlags = @"APE_INFO_FORMAT_FLAGS";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioSampleRate = @"APE_INFO_SAMPLE_RATE";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioBitsPerSample = @"APE_INFO_BITS_PER_SAMPLE";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioBytesPerSample = @"APE_INFO_BYTES_PER_SAMPLE";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioChannels = @"APE_INFO_CHANNELS";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioBlockAlignment = @"APE_INFO_BLOCK_ALIGN";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioBlocksPerFrame = @"APE_INFO_BLOCKS_PER_FRAME";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioFinalFrameBlocks = @"APE_INFO_FINAL_FRAME_BLOCKS";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioTotalFrames = @"APE_INFO_TOTAL_FRAMES";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioWAVHeaderBytes = @"APE_INFO_WAV_HEADER_BYTES";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioWAVTerminatingBytes = @"APE_INFO_WAV_TERMINATING_BYTES";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioWAVDataBytes = @"APE_INFO_WAV_DATA_BYTES";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioWAVTotalBytes = @"APE_INFO_WAV_TOTAL_BYTES";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioAPETotalBytes = @"APE_INFO_APE_TOTAL_BYTES";
//SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioTotalBlocks = @"APE_INFO_TOTAL_BLOCKS";
//SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioLengthMilliseconds = @"APE_INFO_LENGTH_MS";
//SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioAverageBitrate = @"APE_INFO_AVERAGE_BITRATE";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioDecompressedBitrate = @"APE_INFO_DECOMPRESSED_BITRATE";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioAPL = @"APE_INFO_APL";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioTotalBlocks = @"APE_DECOMPRESS_TOTAL_BLOCKS";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioLengthMilliseconds = @"APE_DECOMPRESS_LENGTH_MS";
SFBAudioDecodingPropertiesKey const SFBAudioDecodingPropertiesKeyMonkeysAudioAverageBitrate = @"APE_DECOMPRESS_AVERAGE_BITRATE";
namespace {
// The I/O interface for MAC
class APEIOInterface final : public APE::CIO
{
public:
explicit APEIOInterface(SFBInputSource *inputSource)
: mInputSource(inputSource)
{}
int Open(const wchar_t * pName, bool bOpenReadOnly) override
{
#pragma unused(pName)
#pragma unused(bOpenReadOnly)
return ERROR_INVALID_INPUT_FILE;
}
int Close() override
{
return ERROR_SUCCESS;
}
int Read(void * pBuffer, unsigned int nBytesToRead, unsigned int * pBytesRead) override
{
NSInteger bytesRead;
if(![mInputSource readBytes:pBuffer length:nBytesToRead bytesRead:&bytesRead error:nil])
return ERROR_IO_READ;
*pBytesRead = static_cast<unsigned int>(bytesRead);
return ERROR_SUCCESS;
}
int Write(const void * pBuffer, unsigned int nBytesToWrite, unsigned int * pBytesWritten) override
{
#pragma unused(pBuffer)
#pragma unused(nBytesToWrite)
#pragma unused(pBytesWritten)
return ERROR_IO_WRITE;
}
int Seek(APE::int64 nPosition, APE::SeekMethod nMethod) override
{
if(!mInputSource.supportsSeeking)
return ERROR_IO_READ;
NSInteger offset = nPosition;
switch(nMethod) {
case APE::SeekFileBegin:
// offset remains unchanged
break;
case APE::SeekFileCurrent: {
NSInteger inputSourceOffset;
if([mInputSource getOffset:&inputSourceOffset error:nil])
offset += inputSourceOffset;
break;
}
case APE::SeekFileEnd: {
NSInteger inputSourceLength;
if([mInputSource getLength:&inputSourceLength error:nil])
offset += inputSourceLength;
break;
}
}
return ![mInputSource seekToOffset:offset error:nil];
}
int Create(const wchar_t * pName) override
{
#pragma unused(pName)
return ERROR_IO_WRITE;
}
int Delete() override
{
return ERROR_IO_WRITE;
}
int SetEOF() override
{
return ERROR_IO_WRITE;
}
unsigned char * GetBuffer(int * pnBufferBytes) override
{
#pragma unused(pnBufferBytes)
return nullptr;
}
APE::int64 GetPosition() override
{
NSInteger offset;
if(![mInputSource getOffset:&offset error:nil])
return -1;
return offset;
}
APE::int64 GetSize() override
{
NSInteger length;
if(![mInputSource getLength:&length error:nil])
return -1;
return length;
}
int GetName(wchar_t * pBuffer) override
{
#pragma unused(pBuffer)
return ERROR_SUCCESS;
}
private:
SFBInputSource *mInputSource;
};
} /* namespace */
@interface SFBMonkeysAudioDecoder ()
{
@private
std::unique_ptr<APEIOInterface> _ioInterface;
std::unique_ptr<APE::IAPEDecompress> _decompressor;
}
@end
@implementation SFBMonkeysAudioDecoder
+ (void)load
{
[SFBAudioDecoder registerSubclass:[self class]];
}
+ (NSSet *)supportedPathExtensions
{
return [NSSet setWithObject:@"ape"];
}
+ (NSSet *)supportedMIMETypes
{
return [NSSet setWithArray:@[@"audio/monkeys-audio", @"audio/x-monkeys-audio"]];
}
+ (SFBAudioDecoderName)decoderName
{
return SFBAudioDecoderNameMonkeysAudio;
}
+ (BOOL)testInputSource:(SFBInputSource *)inputSource formatIsSupported:(SFBTernaryTruthValue *)formatIsSupported error:(NSError **)error
{
NSParameterAssert(inputSource != nil);
NSParameterAssert(formatIsSupported != NULL);
NSData *header = [inputSource readHeaderOfLength:SFBAPEDetectionSize skipID3v2Tag:YES error:error];
if(!header)
return NO;
if([header isAPEHeader])
*formatIsSupported = SFBTernaryTruthValueTrue;
else
*formatIsSupported = SFBTernaryTruthValueFalse;
return YES;
}
- (BOOL)decodingIsLossless
{
return YES;
}
- (BOOL)openReturningError:(NSError **)error
{
if(![super openReturningError:error])
return NO;
auto ioInterface = std::make_unique<APEIOInterface>(_inputSource);
auto decompressor = std::unique_ptr<APE::IAPEDecompress>(CreateIAPEDecompressEx(ioInterface.get(), nullptr));
if(!decompressor) {
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The file “%@” is not a valid Monkey's Audio file.", @"")
url:_inputSource.url
failureReason:NSLocalizedString(@"Not a Monkey's Audio file", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
return NO;
}
_decompressor = std::move(decompressor);
_ioInterface = std::move(ioInterface);
AVAudioChannelLayout *channelLayout = nil;
switch(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_CHANNELS)) {
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 | static_cast<UInt32>(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_CHANNELS)))];
break;
}
// The file format
AudioStreamBasicDescription processingStreamDescription{};
processingStreamDescription.mFormatID = kAudioFormatLinearPCM;
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-anon-enum-enum-conversion"
processingStreamDescription.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked;
#pragma clang diagnostic pop
processingStreamDescription.mBitsPerChannel = static_cast<UInt32>(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_BITS_PER_SAMPLE));
processingStreamDescription.mSampleRate = _decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_SAMPLE_RATE);
processingStreamDescription.mChannelsPerFrame = static_cast<UInt32>(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_CHANNELS));
processingStreamDescription.mBytesPerPacket = (processingStreamDescription.mBitsPerChannel / 8) * processingStreamDescription.mChannelsPerFrame;
processingStreamDescription.mFramesPerPacket = 1;
processingStreamDescription.mBytesPerFrame = processingStreamDescription.mBytesPerPacket / processingStreamDescription.mFramesPerPacket;
processingStreamDescription.mReserved = 0;
_processingFormat = [[AVAudioFormat alloc] initWithStreamDescription:&processingStreamDescription channelLayout:channelLayout];
// Set up the source format
AudioStreamBasicDescription sourceStreamDescription{};
sourceStreamDescription.mFormatID = kSFBAudioFormatMonkeysAudio;
sourceStreamDescription.mBitsPerChannel = static_cast<UInt32>(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_BITS_PER_SAMPLE));
sourceStreamDescription.mSampleRate = _decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_SAMPLE_RATE);
sourceStreamDescription.mChannelsPerFrame = static_cast<UInt32>(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_CHANNELS));
_sourceFormat = [[AVAudioFormat alloc] initWithStreamDescription:&sourceStreamDescription channelLayout:channelLayout];
// Populate codec properties
_properties = @{
SFBAudioDecodingPropertiesKeyMonkeysAudioFileVersion: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_FILE_VERSION)),
SFBAudioDecodingPropertiesKeyMonkeysAudioCompressionLevel: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_COMPRESSION_LEVEL)),
SFBAudioDecodingPropertiesKeyMonkeysAudioFormatFlags: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_FORMAT_FLAGS)),
SFBAudioDecodingPropertiesKeyMonkeysAudioSampleRate: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_SAMPLE_RATE)),
SFBAudioDecodingPropertiesKeyMonkeysAudioBitsPerSample: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_BITS_PER_SAMPLE)),
SFBAudioDecodingPropertiesKeyMonkeysAudioBytesPerSample: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_BYTES_PER_SAMPLE)),
SFBAudioDecodingPropertiesKeyMonkeysAudioChannels: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_CHANNELS)),
SFBAudioDecodingPropertiesKeyMonkeysAudioBlockAlignment: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_BLOCK_ALIGN)),
SFBAudioDecodingPropertiesKeyMonkeysAudioBlocksPerFrame: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_BLOCKS_PER_FRAME)),
SFBAudioDecodingPropertiesKeyMonkeysAudioFinalFrameBlocks: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_FINAL_FRAME_BLOCKS)),
SFBAudioDecodingPropertiesKeyMonkeysAudioTotalFrames: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_TOTAL_FRAMES)),
SFBAudioDecodingPropertiesKeyMonkeysAudioWAVHeaderBytes: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_WAV_HEADER_BYTES)),
SFBAudioDecodingPropertiesKeyMonkeysAudioWAVTerminatingBytes: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_WAV_TERMINATING_BYTES)),
SFBAudioDecodingPropertiesKeyMonkeysAudioWAVDataBytes: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_WAV_DATA_BYTES)),
SFBAudioDecodingPropertiesKeyMonkeysAudioWAVTotalBytes: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_WAV_TOTAL_BYTES)),
SFBAudioDecodingPropertiesKeyMonkeysAudioAPETotalBytes: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_APE_TOTAL_BYTES)),
// SFBAudioDecodingPropertiesKeyMonkeysAudioTotalBlocks: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_TOTAL_BLOCKS)),
// SFBAudioDecodingPropertiesKeyMonkeysAudioLengthMilliseconds: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_LENGTH_MS)),
// SFBAudioDecodingPropertiesKeyMonkeysAudioAverageBitrate: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_AVERAGE_BITRATE)),
// APE_INFO_FRAME_BITRATE
SFBAudioDecodingPropertiesKeyMonkeysAudioDecompressedBitrate: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_DECOMPRESSED_BITRATE)),
// APE_INFO_PEAK_LEVEL
// APE_INFO_SEEK_BIT
// APE_INFO_SEEK_BYTE
// APE_INFO_WAV_HEADER_DATA
// APE_INFO_WAV_TERMINATING_DATA
// APE_INFO_WAVEFORMATEX
// APE_INFO_IO_SOURCE
// APE_INFO_FRAME_BYTES
// APE_INFO_FRAME_BLOCKS
// APE_INFO_TAG
SFBAudioDecodingPropertiesKeyMonkeysAudioAPL: _decompressor->GetInfo(APE::IAPEDecompress::APE_INFO_APL) ? @YES : @NO,
// APE_DECOMPRESS_CURRENT_BLOCK
// APE_DECOMPRESS_CURRENT_MS
SFBAudioDecodingPropertiesKeyMonkeysAudioTotalBlocks: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_DECOMPRESS_TOTAL_BLOCKS)),
SFBAudioDecodingPropertiesKeyMonkeysAudioLengthMilliseconds: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_DECOMPRESS_LENGTH_MS)),
// APE_DECOMPRESS_CURRENT_BITRATE
SFBAudioDecodingPropertiesKeyMonkeysAudioAverageBitrate: @(_decompressor->GetInfo(APE::IAPEDecompress::APE_DECOMPRESS_AVERAGE_BITRATE)),
// APE_DECOMPRESS_CURRENT_FRAME
};
return YES;
}
- (BOOL)closeReturningError:(NSError **)error
{
_ioInterface.reset();
_decompressor.reset();
return [super closeReturningError:error];
}
- (BOOL)isOpen
{
return _decompressor != nullptr;
}
- (AVAudioFramePosition)framePosition
{
return _decompressor->GetInfo(APE::IAPEDecompress::APE_DECOMPRESS_CURRENT_BLOCK);
}
- (AVAudioFramePosition)frameLength
{
return _decompressor->GetInfo(APE::IAPEDecompress::APE_DECOMPRESS_TOTAL_BLOCKS);
}
- (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;
int64_t blocksRead = 0;
if(_decompressor->GetData(static_cast<unsigned char *>(buffer.audioBufferList->mBuffers[0].mData), static_cast<int64_t>(frameLength), &blocksRead)) {
os_log_error(gSFBAudioDecoderLog, "Monkey's Audio invalid checksum");
if(error)
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain code:SFBAudioDecoderErrorCodeInternalError userInfo:@{ NSURLErrorKey: _inputSource.url }];
return NO;
}
buffer.frameLength = static_cast<AVAudioFrameCount>(blocksRead);
return YES;
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error
{
NSParameterAssert(frame >= 0);
return _decompressor->Seek(frame) == ERROR_SUCCESS;
}
@end