-
Notifications
You must be signed in to change notification settings - Fork 91
/
Copy pathSFBAudioDecoder.m
395 lines (326 loc) · 12.2 KB
/
SFBAudioDecoder.m
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
//
// Copyright (c) 2006-2025 Stephen F. Booth <me@sbooth.org>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
@import os.log;
#import "SFBAudioDecoder.h"
#import "SFBAudioDecoder+Internal.h"
#import "NSError+SFBURLPresentation.h"
// NSError domain for AudioDecoder and subclasses
NSErrorDomain const SFBAudioDecoderErrorDomain = @"org.sbooth.AudioEngine.AudioDecoder";
os_log_t gSFBAudioDecoderLog = NULL;
static void SFBCreateAudioDecoderLog(void) __attribute__ ((constructor));
static void SFBCreateAudioDecoderLog(void)
{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
gSFBAudioDecoderLog = os_log_create("org.sbooth.AudioEngine", "AudioDecoder");
});
}
@interface SFBAudioDecoderSubclassInfo : NSObject
@property (nonatomic) Class klass;
@property (nonatomic) int priority;
@end
@implementation SFBAudioDecoder
@synthesize inputSource = _inputSource;
@synthesize sourceFormat = _sourceFormat;
@synthesize processingFormat = _processingFormat;
@synthesize properties = _properties;
@dynamic decodingIsLossless;
@dynamic framePosition;
@dynamic frameLength;
static NSMutableArray *_registeredSubclasses = nil;
+ (void)load
{
[NSError setUserInfoValueProviderForDomain:SFBAudioDecoderErrorDomain provider:^id(NSError *err, NSErrorUserInfoKey userInfoKey) {
if([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
switch(err.code) {
case SFBAudioDecoderErrorCodeInternalError:
return NSLocalizedString(@"An internal decoder error occurred.", @"");
case SFBAudioDecoderErrorCodeUnknownDecoder:
return NSLocalizedString(@"The requested decoder is unavailable.", @"");
case SFBAudioDecoderErrorCodeInvalidFormat:
return NSLocalizedString(@"The format is invalid, unknown, or unsupported.", @"");
}
}
return nil;
}];
}
+ (NSSet *)supportedPathExtensions
{
NSMutableSet *result = [NSMutableSet set];
for(SFBAudioDecoderSubclassInfo *subclassInfo in _registeredSubclasses) {
NSSet *supportedPathExtensions = [subclassInfo.klass supportedPathExtensions];
[result unionSet:supportedPathExtensions];
}
return result;
}
+ (NSSet *)supportedMIMETypes
{
NSMutableSet *result = [NSMutableSet set];
for(SFBAudioDecoderSubclassInfo *subclassInfo in _registeredSubclasses) {
NSSet *supportedMIMETypes = [subclassInfo.klass supportedMIMETypes];
[result unionSet:supportedMIMETypes];
}
return result;
}
+ (SFBAudioDecoderName)decoderName
{
[self doesNotRecognizeSelector:_cmd];
__builtin_unreachable();
}
+ (BOOL)testInputSource:(SFBInputSource *)inputSource formatIsSupported:(SFBTernaryTruthValue *)formatIsSupported error:(NSError **)error
{
[self doesNotRecognizeSelector:_cmd];
__builtin_unreachable();
}
+ (BOOL)handlesPathsWithExtension:(NSString *)extension
{
NSString *lowercaseExtension = extension.lowercaseString;
for(SFBAudioDecoderSubclassInfo *subclassInfo in _registeredSubclasses) {
NSSet *supportedPathExtensions = [subclassInfo.klass supportedPathExtensions];
if([supportedPathExtensions containsObject:lowercaseExtension])
return YES;
}
return NO;
}
+ (BOOL)handlesMIMEType:(NSString *)mimeType
{
NSString *lowercaseMIMEType = mimeType.lowercaseString;
for(SFBAudioDecoderSubclassInfo *subclassInfo in _registeredSubclasses) {
NSSet *supportedMIMETypes = [subclassInfo.klass supportedMIMETypes];
if([supportedMIMETypes containsObject:lowercaseMIMEType])
return YES;
}
return NO;
}
- (instancetype)initWithURL:(NSURL *)url
{
return [self initWithURL:url detectContentType:YES mimeTypeHint:nil error:nil];
}
- (instancetype)initWithURL:(NSURL *)url error:(NSError **)error
{
return [self initWithURL:url detectContentType:YES mimeTypeHint:nil error:error];
}
- (instancetype)initWithURL:(NSURL *)url detectContentType:(BOOL)detectContentType error:(NSError **)error
{
return [self initWithURL:url detectContentType:detectContentType mimeTypeHint:nil error:error];
}
- (instancetype)initWithURL:(NSURL *)url mimeTypeHint:(NSString *)mimeTypeHint error:(NSError **)error
{
return [self initWithURL:url detectContentType:YES mimeTypeHint:mimeTypeHint error:error];
}
- (instancetype)initWithURL:(NSURL *)url detectContentType:(BOOL)detectContentType mimeTypeHint:(NSString *)mimeTypeHint error:(NSError **)error
{
NSParameterAssert(url != nil);
SFBInputSource *inputSource = [SFBInputSource inputSourceForURL:url flags:0 error:error];
if(!inputSource)
return nil;
return [self initWithInputSource:inputSource detectContentType:detectContentType mimeTypeHint:mimeTypeHint error:error];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource
{
return [self initWithInputSource:inputSource detectContentType:YES mimeTypeHint:nil error:nil];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource error:(NSError **)error
{
return [self initWithInputSource:inputSource detectContentType:YES mimeTypeHint:nil error:error];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource detectContentType:(BOOL)detectContentType error:(NSError **)error
{
return [self initWithInputSource:inputSource detectContentType:detectContentType mimeTypeHint:nil error:error];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource mimeTypeHint:(NSString *)mimeTypeHint error:(NSError **)error
{
return [self initWithInputSource:inputSource detectContentType:YES mimeTypeHint:mimeTypeHint error:error];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource detectContentType:(BOOL)detectContentType mimeTypeHint:(NSString *)mimeTypeHint error:(NSError **)error
{
NSParameterAssert(inputSource != nil);
NSString *lowercaseExtension = inputSource.url.pathExtension.lowercaseString;
NSString *lowercaseMIMEType = mimeTypeHint.lowercaseString;
// Instead of failing for non-seekable inputs just skip content type detection
if(detectContentType && !inputSource.supportsSeeking) {
os_log_error(gSFBAudioDecoderLog, "Unable to detect content type for non-seekable input source %{public}@", inputSource);
detectContentType = NO;
}
// If the input source can't be opened decoding is destined to fail; give up now
if(detectContentType && !inputSource.isOpen && ![inputSource openReturningError:error])
return nil;
int score = 10;
Class subclass = nil;
for(SFBAudioDecoderSubclassInfo *subclassInfo in _registeredSubclasses) {
int currentScore = 0;
Class klass = subclassInfo.klass;
if(lowercaseMIMEType) {
NSSet *supportedMIMETypes = [klass supportedMIMETypes];
if([supportedMIMETypes containsObject:lowercaseMIMEType])
currentScore += 40;
}
if(lowercaseExtension) {
NSSet *supportedPathExtensions = [klass supportedPathExtensions];
if([supportedPathExtensions containsObject:lowercaseExtension])
currentScore += 20;
}
if(detectContentType) {
SFBTernaryTruthValue formatSupported;
if([klass testInputSource:inputSource formatIsSupported:&formatSupported error:error]) {
switch(formatSupported) {
case SFBTernaryTruthValueTrue:
currentScore += 75;
break;
case SFBTernaryTruthValueFalse:
break;
case SFBTernaryTruthValueUnknown:
currentScore += 10;
break;
default:
os_log_fault(gSFBAudioDecoderLog, "Unknown SFBTernaryTruthValue %li", (long)formatSupported);
break;
}
}
else
os_log_error(gSFBAudioDecoderLog, "Error testing %{public}@ format support for %{public}@", klass, inputSource);
}
if(currentScore > score) {
score = currentScore;
subclass = klass;
}
}
if(!subclass) {
os_log_debug(gSFBAudioDecoderLog, "Unable to determine content type for %{public}@", inputSource);
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
descriptionFormatStringForURL:NSLocalizedString(@"The type of the file “%@” could not be determined.", @"")
url:inputSource.url
failureReason:NSLocalizedString(@"Unknown file type", @"")
recoverySuggestion:NSLocalizedString(@"The file's extension may be missing or may not match the file's type.", @"")];
return nil;
}
if((self = [[subclass alloc] init])) {
_inputSource = inputSource;
#if DEBUG
os_log_debug(gSFBAudioDecoderLog, "Created %{public}@ based on score of %i", self, score);
#endif /* DEBUG */
}
return self;
}
- (instancetype)initWithURL:(NSURL *)url decoderName:(SFBAudioDecoderName)decoderName
{
return [self initWithURL:url decoderName:decoderName error:nil];
}
- (instancetype)initWithURL:(NSURL *)url decoderName:(SFBAudioDecoderName)decoderName error:(NSError **)error
{
NSParameterAssert(url != nil);
SFBInputSource *inputSource = [SFBInputSource inputSourceForURL:url flags:0 error:error];
if(!inputSource)
return nil;
return [self initWithInputSource:inputSource decoderName:decoderName error:error];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource decoderName:(SFBAudioDecoderName)decoderName
{
return [self initWithInputSource:inputSource decoderName:decoderName error:nil];
}
- (instancetype)initWithInputSource:(SFBInputSource *)inputSource decoderName:(SFBAudioDecoderName)decoderName error:(NSError **)error
{
NSParameterAssert(inputSource != nil);
Class subclass = nil;
for(SFBAudioDecoderSubclassInfo *subclassInfo in _registeredSubclasses) {
SFBAudioDecoderName subclassDecoderName = [subclassInfo.klass decoderName];
if(subclassDecoderName == decoderName) {
subclass = subclassInfo.klass;
break;
}
}
if(!subclass) {
os_log_error(gSFBAudioDecoderLog, "SFBAudioDecoder unknown decoder: \"%{public}@\"", decoderName);
if(error)
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeUnknownDecoder
userInfo:@{ NSURLErrorKey: inputSource.url }];
return nil;
}
if((self = [[subclass alloc] init]))
_inputSource = inputSource;
return self;
}
- (void)dealloc
{
[self closeReturningError:nil];
}
- (BOOL)openReturningError:(NSError **)error
{
if(!_inputSource.isOpen)
return [_inputSource openReturningError:error];
return YES;
}
- (BOOL)closeReturningError:(NSError **)error
{
if(_inputSource.isOpen)
return [_inputSource closeReturningError:error];
return YES;
}
- (BOOL)isOpen
{
[self doesNotRecognizeSelector:_cmd];
__builtin_unreachable();
}
- (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
{
[self doesNotRecognizeSelector:_cmd];
__builtin_unreachable();
}
- (BOOL)supportsSeeking
{
return _inputSource.supportsSeeking;
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame error:(NSError **)error
{
[self doesNotRecognizeSelector:_cmd];
__builtin_unreachable();
}
- (NSString *)description
{
return [NSString stringWithFormat:@"<%@ %p: \"%@\">", [self class], self, [[NSFileManager defaultManager] displayNameAtPath:_inputSource.url.path]];
}
@end
@implementation SFBAudioDecoderSubclassInfo
@end
@implementation SFBAudioDecoder (SFBAudioDecoderSubclassRegistration)
+ (void)registerSubclass:(Class)subclass
{
[self registerSubclass:subclass priority:0];
}
+ (void)registerSubclass:(Class)subclass priority:(int)priority
{
// NSAssert([subclass isKindOfClass:[self class]], @"Unable to register class '%@' because it is not a subclass of SFBAudioDecoder", NSStringFromClass(subclass));
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_registeredSubclasses = [NSMutableArray array];
});
SFBAudioDecoderSubclassInfo *subclassInfo = [[SFBAudioDecoderSubclassInfo alloc] init];
subclassInfo.klass = subclass;
subclassInfo.priority = priority;
[_registeredSubclasses addObject:subclassInfo];
// N.B. `sortUsingComparator:` sorts in ascending order
// To sort the array in descending order the comparator is reversed
[_registeredSubclasses sortUsingComparator:^NSComparisonResult(id _Nonnull obj1, id _Nonnull obj2) {
int a = ((SFBAudioDecoderSubclassInfo *)obj1).priority;
int b = ((SFBAudioDecoderSubclassInfo *)obj2).priority;
if(a > b)
return NSOrderedAscending;
else if(a < b)
return NSOrderedDescending;
else
return NSOrderedSame;
}];
}
@end