-
Notifications
You must be signed in to change notification settings - Fork 99
Expand file tree
/
Copy pathSFBAudioDecoder.m
More file actions
528 lines (440 loc) · 20.7 KB
/
Copy pathSFBAudioDecoder.m
File metadata and controls
528 lines (440 loc) · 20.7 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
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
//
// SPDX-FileCopyrightText: 2006 Stephen F. Booth <contact@sbooth.dev>
// SPDX-License-Identifier: MIT
//
// Part of https://github.com/sbooth/SFBAudioEngine
//
#import "SFBAudioDecoder.h"
#import "SFBAudioDecoder+Internal.h"
#import "SFBLocalizedNameForURL.h"
#import <os/log.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) {
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) {
switch (err.code) {
case SFBAudioDecoderErrorCodeUnknownDecoder:
if ([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
return NSLocalizedString(@"The requested PCM decoder is unavailable.",
@"");
}
break;
case SFBAudioDecoderErrorCodeInvalidFormat:
if ([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
return NSLocalizedString(@"The format is invalid or unknown.", @"");
}
break;
case SFBAudioDecoderErrorCodeUnsupportedFormat:
if ([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
return NSLocalizedString(@"The PCM audio format is unsupported.", @"");
}
break;
case SFBAudioDecoderErrorCodeInternalError:
if ([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
return NSLocalizedString(@"An internal decoder error occurred.", @"");
}
break;
case SFBAudioDecoderErrorCodeDecodingError:
if ([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
return NSLocalizedString(
@"An error occurred during PCM audio decoding.", @"");
}
break;
case SFBAudioDecoderErrorCodeSeekError:
if ([userInfoKey isEqualToString:NSLocalizedDescriptionKey]) {
return NSLocalizedString(@"An error occurred seeking to the requested "
@"PCM frame position.",
@"");
}
break;
}
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;
if (detectContentType) {
// If the input source can't be opened decoding is destined to fail; give up now
if (!inputSource.isOpen && ![inputSource openReturningError:error]) {
return nil;
}
// Instead of failing for non-seekable inputs just skip content type detection
if (!inputSource.supportsSeeking) {
os_log_error(gSFBAudioDecoderLog, "Unable to detect content type for non-seekable input source %{public}@",
inputSource);
detectContentType = NO;
}
}
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) {
NSMutableDictionary *userInfo = [NSMutableDictionary
dictionaryWithObject:
NSLocalizedString(@"The file's extension may be missing or may not match the file's type.",
@"")
forKey:NSLocalizedRecoverySuggestionErrorKey];
if (inputSource.url) {
userInfo[NSLocalizedDescriptionKey] = [NSString
localizedStringWithFormat:NSLocalizedString(
@"The type of the file “%@” could not be determined.", @""),
SFBLocalizedNameForURL(inputSource.url)];
userInfo[NSURLErrorKey] = inputSource.url;
} else {
userInfo[NSLocalizedDescriptionKey] =
NSLocalizedString(@"The type of the file could not be determined.", @"");
}
*error = [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
userInfo:userInfo];
}
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:nil];
}
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 {
_sourceFormat = nil;
_processingFormat = nil;
_properties = nil;
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();
}
- (NSError *)invalidFormatError:(NSString *)formatName {
return [self invalidFormatError:formatName
recoverySuggestion:NSLocalizedString(@"The file's extension may not match the file's type.", @"")];
}
- (NSError *)invalidFormatError:(NSString *)formatName recoverySuggestion:(NSString *)recoverySuggestion {
NSParameterAssert(formatName != nil);
NSParameterAssert(recoverySuggestion != nil);
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:recoverySuggestion
forKey:NSLocalizedRecoverySuggestionErrorKey];
if (_inputSource.url) {
userInfo[NSLocalizedDescriptionKey] =
[NSString localizedStringWithFormat:NSLocalizedString(@"The file “%@” is not a valid %@ file.", @""),
SFBLocalizedNameForURL(_inputSource.url), formatName];
userInfo[NSURLErrorKey] = _inputSource.url;
} else {
userInfo[NSLocalizedDescriptionKey] = [NSString
localizedStringWithFormat:NSLocalizedString(@"The file is not a valid %@ file.", @""), formatName];
}
return [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInvalidFormat
userInfo:userInfo];
}
- (NSError *)unsupportedFormatError:(NSString *)formatName recoverySuggestion:(NSString *)recoverySuggestion {
NSParameterAssert(formatName != nil);
NSParameterAssert(recoverySuggestion != nil);
NSMutableDictionary *userInfo = [NSMutableDictionary dictionaryWithObject:recoverySuggestion
forKey:NSLocalizedRecoverySuggestionErrorKey];
if (_inputSource.url) {
userInfo[NSLocalizedDescriptionKey] = [NSString
localizedStringWithFormat:NSLocalizedString(@"The file “%@” is not a supported %@ file.", @""),
SFBLocalizedNameForURL(_inputSource.url), formatName];
userInfo[NSURLErrorKey] = _inputSource.url;
} else {
userInfo[NSLocalizedDescriptionKey] = [NSString
localizedStringWithFormat:NSLocalizedString(@"The file is not a supported %@ file.", @""), formatName];
}
return [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeUnsupportedFormat
userInfo:userInfo];
}
- (NSError *)genericInternalError {
NSDictionary *userInfo = nil;
if (_inputSource.url) {
userInfo = [NSDictionary dictionaryWithObject:_inputSource.url forKey:NSURLErrorKey];
}
return [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeInternalError
userInfo:userInfo];
}
- (NSError *)genericDecodingError {
NSDictionary *userInfo = nil;
if (_inputSource.url) {
userInfo = [NSDictionary dictionaryWithObject:_inputSource.url forKey:NSURLErrorKey];
}
return [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeDecodingError
userInfo:userInfo];
}
- (NSError *)genericSeekError {
NSDictionary *userInfo = nil;
if (_inputSource.url) {
userInfo = [NSDictionary dictionaryWithObject:_inputSource.url forKey:NSURLErrorKey];
}
return [NSError errorWithDomain:SFBAudioDecoderErrorDomain
code:SFBAudioDecoderErrorCodeSeekError
userInfo:userInfo];
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ %p: \"%@\">", [self class], (__bridge void *)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;
}
if (a < b) {
return NSOrderedDescending;
}
return NSOrderedSame;
}];
}
@end