-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathSFBAudioPlayer.mm
1219 lines (999 loc) · 44.1 KB
/
SFBAudioPlayer.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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Copyright (c) 2006-2025 Stephen F. Booth <[email protected]>
// Part of https://github.com/sbooth/SFBAudioEngine
// MIT license
//
#import <atomic>
#import <cmath>
#import <deque>
#import <mutex>
#import <objc/runtime.h>
#import <AVAudioFormat+SFBFormatTransformation.h>
#import <SFBUnfairLock.hpp>
#import "SFBAudioPlayer.h"
#import "SFBAudioPlayerNode+Internal.h"
#import "HostTimeUtilities.hpp"
#import "SFBAudioDecoder.h"
#import "SFBCStringForOSType.h"
#import "StringDescribingAVAudioFormat.h"
namespace {
/// Objective-C associated object key indicating if a decoder has been canceled
constexpr char _decoderIsCanceledKey = '\0';
using DecoderQueue = std::deque<id <SFBPCMDecoding>>;
const os_log_t _audioPlayerLog = os_log_create("org.sbooth.AudioEngine", "AudioPlayer");
/// Possible `SFBAudioPlayer` flag values
enum AudioPlayerFlags : unsigned int {
/// Cached value of `_audioEngine.isRunning`
eAudioPlayerFlagEngineIsRunning = 1u << 0,
/// Set if there is a decoder being enqueued on the player node that has not yet started decoding
eAudioPlayerFlagHavePendingDecoder = 1u << 1,
/// Set if the pending decoder becomes active when the player is not playing
eAudioPlayerFlagPendingDecoderBecameActive = 1u << 2,
};
#if !TARGET_OS_IPHONE
/// Returns the name of `audioUnit.deviceID`
///
/// This is the value of `kAudioObjectPropertyName` in the output scope on the main element
NSString * _Nullable AudioDeviceName(AUAudioUnit * _Nonnull audioUnit) noexcept
{
NSCParameterAssert(audioUnit != nil);
AudioObjectPropertyAddress address = {
.mSelector = kAudioObjectPropertyName,
.mScope = kAudioObjectPropertyScopeOutput,
.mElement = kAudioObjectPropertyElementMain
};
CFStringRef name = nullptr;
UInt32 dataSize = sizeof(name);
OSStatus result = AudioObjectGetPropertyData(audioUnit.deviceID, &address, 0, nullptr, &dataSize, &name);
if(result != noErr) {
os_log_error(_audioPlayerLog, "AudioObjectGetPropertyData (kAudioObjectPropertyName, kAudioObjectPropertyScopeOutput, kAudioObjectPropertyElementMain) failed: %d '%{public}.4s'", result, SFBCStringForOSType(result));
return nil;
}
return (__bridge_transfer NSString *)name;
}
#endif /* !TARGET_OS_IPHONE */
} /* namespace */
@interface SFBAudioPlayer ()
{
@private
/// The underlying `AVAudioEngine` instance
AVAudioEngine *_engine;
/// The dispatch queue used to access `_engine`
dispatch_queue_t _engineQueue;
/// The player driving the audio processing graph
SFBAudioPlayerNode *_playerNode;
/// The lock used to protect access to `_queuedDecoders`
SFB::UnfairLock _queueLock;
/// Decoders enqueued for non-gapless playback
DecoderQueue _queuedDecoders;
/// The lock used to protect access to `_nowPlaying`
SFB::UnfairLock _nowPlayingLock;
/// The currently rendering decoder
id <SFBPCMDecoding> _nowPlaying;
/// Flags
std::atomic_uint _flags;
}
/// Returns true if the internal queue of decoders is empty
- (BOOL)internalDecoderQueueIsEmpty;
/// Removes all decoders from the internal decoder queue
- (void)clearInternalDecoderQueue;
/// Inserts `decoder` at the end of the internal decoder queue
- (BOOL)pushDecoderToInternalQueue:(id <SFBPCMDecoding>)decoder;
/// Removes and returns the first decoder from the internal decoder queue
- (nullable id <SFBPCMDecoding>)popDecoderFromInternalQueue;
/// Called to process `AVAudioEngineConfigurationChangeNotification`
- (void)handleAudioEngineConfigurationChange:(NSNotification *)notification;
#if TARGET_OS_IPHONE
/// Called to process `AVAudioSessionInterruptionNotification`
- (void)handleAudioSessionInterruption:(NSNotification *)notification;
#endif /* TARGET_OS_IPHONE */
/// Configures the player to render audio from `decoder` and enqueues `decoder` on the player node
/// - parameter forImmediatePlayback: If `YES` the internal decoder queue is cleared and the player node is reset
/// - parameter error: An optional pointer to an `NSError` object to receive error information
/// - returns: `YES` if the player was successfully configured
- (BOOL)configureForAndEnqueueDecoder:(nonnull id <SFBPCMDecoding>)decoder forImmediatePlayback:(BOOL)forImmediatePlayback error:(NSError **)error;
/// Configures the audio processing graph for playback of audio with `format`, replacing the audio player node if necessary
///
/// This method does nothing if the current rendering format is equal to `format`
/// - important: This stops the audio engine if reconfiguration is necessary
/// - parameter format: The desired audio format
/// - parameter forceUpdate: Whether the graph should be rebuilt even if the current rendering format is equal to `format`
/// - returns: `YES` if the processing graph was successfully configured
- (BOOL)configureProcessingGraphForFormat:(nonnull AVAudioFormat *)format forceUpdate:(BOOL)forceUpdate;
@end
@implementation SFBAudioPlayer
- (instancetype)init
{
if((self = [super init])) {
_engineQueue = dispatch_queue_create("org.sbooth.AudioEngine.AudioPlayer.AVAudioEngineIsolationQueue", DISPATCH_QUEUE_SERIAL);
if(!_engineQueue) {
os_log_error(_audioPlayerLog, "Unable to create AVAudioEngine isolation dispatch queue: dispatch_queue_create failed");
return nil;
}
// Create the audio processing graph
_engine = [[AVAudioEngine alloc] init];
if(![self configureProcessingGraphForFormat:[[AVAudioFormat alloc] initStandardFormatWithSampleRate:44100 channels:2] forceUpdate:NO]) {
os_log_error(_audioPlayerLog, "Unable to create audio processing graph for 44.1 kHz stereo");
return nil;
}
// Register for configuration change notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioEngineConfigurationChange:) name:AVAudioEngineConfigurationChangeNotification object:_engine];
#if TARGET_OS_IPHONE
// Register for audio session interruption notifications
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleAudioSessionInterruption:) name:AVAudioSessionInterruptionNotification object:[AVAudioSession sharedInstance]];
#endif /* TARGET_OS_IPHONE */
}
return self;
}
#pragma mark - Playlist Management
- (BOOL)playURL:(NSURL *)url error:(NSError **)error
{
NSParameterAssert(url != nil);
if(![self enqueueURL:url forImmediatePlayback:YES error:error])
return NO;
return [self playReturningError:error];
}
- (BOOL)playDecoder:(id <SFBPCMDecoding>)decoder error:(NSError **)error
{
NSParameterAssert(decoder != nil);
if(![self enqueueDecoder:decoder forImmediatePlayback:YES error:error])
return NO;
return [self playReturningError:error];
}
- (BOOL)enqueueURL:(NSURL *)url error:(NSError **)error
{
NSParameterAssert(url != nil);
return [self enqueueURL:url forImmediatePlayback:NO error:error];
}
- (BOOL)enqueueURL:(NSURL *)url forImmediatePlayback:(BOOL)forImmediatePlayback error:(NSError **)error
{
NSParameterAssert(url != nil);
SFBAudioDecoder *decoder = [[SFBAudioDecoder alloc] initWithURL:url error:error];
if(!decoder)
return NO;
return [self enqueueDecoder:decoder forImmediatePlayback:forImmediatePlayback error:error];
}
- (BOOL)enqueueDecoder:(id <SFBPCMDecoding>)decoder error:(NSError **)error
{
NSParameterAssert(decoder != nil);
return [self enqueueDecoder:decoder forImmediatePlayback:NO error:error];
}
- (BOOL)enqueueDecoder:(id <SFBPCMDecoding>)decoder forImmediatePlayback:(BOOL)forImmediatePlayback error:(NSError **)error
{
NSParameterAssert(decoder != nil);
// Open the decoder if necessary
if(!decoder.isOpen && ![decoder openReturningError:error])
return NO;
// Reconfigure the audio processing graph for the decoder's processing format if requested
if(forImmediatePlayback) {
_flags.fetch_or(eAudioPlayerFlagHavePendingDecoder, std::memory_order_acq_rel);
const auto result = [self configureForAndEnqueueDecoder:decoder forImmediatePlayback:YES error:error];
if(!result)
_flags.fetch_and(~eAudioPlayerFlagHavePendingDecoder, std::memory_order_acq_rel);
return result;
}
// To preserve the order of enqueued decoders, when the internal queue is not empty
// enqueue all decoders there regardless of format compability with _playerNode
// This prevents incorrect playback order arising from the scenario where
// decoders A and AA have formats supported by _playerNode and decoder B does not;
// bypassing the internal queue for supported formats when enqueueing A, B, AA
// would result in playback order A, AA, B
else if(self.internalDecoderQueueIsEmpty && [_playerNode supportsFormat:decoder.processingFormat]) {
_flags.fetch_or(eAudioPlayerFlagHavePendingDecoder, std::memory_order_acq_rel);
// Enqueuing is expected to succeed since the formats are compatible
return [_playerNode enqueueDecoder:decoder error:error];
}
// If the internal queue is not empty or _playerNode doesn't support
// the decoder's processing format add the decoder to our internal queue
else {
if(![self pushDecoderToInternalQueue:decoder]) {
if(error)
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
return NO;
}
return YES;
}
}
- (BOOL)formatWillBeGaplessIfEnqueued:(AVAudioFormat *)format
{
NSParameterAssert(format != nil);
return [_playerNode supportsFormat:format];
}
- (void)clearQueue
{
[_playerNode clearQueue];
[self clearInternalDecoderQueue];
}
- (BOOL)queueIsEmpty
{
return _playerNode.queueIsEmpty && self.internalDecoderQueueIsEmpty;
}
#pragma mark - Playback Control
- (BOOL)playReturningError:(NSError **)error
{
if((_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) && _playerNode.isPlaying)
return YES;
__block BOOL engineStarted = NO;
__block NSError *err = nil;
dispatch_async_and_wait(_engineQueue, ^{
engineStarted = [_engine startAndReturnError:&err];
if(engineStarted) {
_flags.fetch_or(eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
[_playerNode play];
}
else
_flags.fetch_and(~eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
});
if(!engineStarted) {
os_log_error(_audioPlayerLog, "Error starting AVAudioEngine: %{public}@", err);
if(error)
*error = err;
return NO;
}
#if DEBUG
NSAssert(self.playbackState == SFBAudioPlayerPlaybackStatePlaying, @"Incorrect playback state in -playReturningError:");
#endif /* DEBUG */
if([_delegate respondsToSelector:@selector(audioPlayer:playbackStateChanged:)])
[_delegate audioPlayer:self playbackStateChanged:SFBAudioPlayerPlaybackStatePlaying];
return YES;
}
- (void)pause
{
if(!((_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) && _playerNode.isPlaying))
return;
[_playerNode pause];
#if DEBUG
NSAssert(self.playbackState == SFBAudioPlayerPlaybackStatePaused, @"Incorrect playback state in -pause");
#endif /* DEBUG */
if([_delegate respondsToSelector:@selector(audioPlayer:playbackStateChanged:)])
[_delegate audioPlayer:self playbackStateChanged:SFBAudioPlayerPlaybackStatePaused];
}
- (void)resume
{
if(!((_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) && !_playerNode.isPlaying))
return;
[_playerNode play];
#if DEBUG
NSAssert(self.playbackState == SFBAudioPlayerPlaybackStatePlaying, @"Incorrect playback state in -resume");
#endif /* DEBUG */
if([_delegate respondsToSelector:@selector(audioPlayer:playbackStateChanged:)])
[_delegate audioPlayer:self playbackStateChanged:SFBAudioPlayerPlaybackStatePlaying];
}
- (void)stop
{
if(!(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning))
return;
dispatch_async_and_wait(_engineQueue, ^{
[_engine stop];
_flags.fetch_and(~eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
[_playerNode stop];
});
[self clearInternalDecoderQueue];
#if DEBUG
NSAssert(self.playbackState == SFBAudioPlayerPlaybackStateStopped, @"Incorrect playback state in -stop");
#endif /* DEBUG */
if([_delegate respondsToSelector:@selector(audioPlayer:playbackStateChanged:)])
[_delegate audioPlayer:self playbackStateChanged:SFBAudioPlayerPlaybackStateStopped];
}
- (BOOL)togglePlayPauseReturningError:(NSError **)error
{
switch(self.playbackState) {
case SFBAudioPlayerPlaybackStatePlaying:
[self pause];
return YES;
case SFBAudioPlayerPlaybackStatePaused:
[self resume];
return YES;
case SFBAudioPlayerPlaybackStateStopped:
return [self playReturningError:error];
}
}
- (void)reset
{
dispatch_async_and_wait(_engineQueue, ^{
[_playerNode reset];
[_engine reset];
});
[self clearInternalDecoderQueue];
}
#pragma mark - Player State
- (BOOL)engineIsRunning
{
__block BOOL isRunning;
dispatch_async_and_wait(_engineQueue, ^{
isRunning = _engine.isRunning;
#if DEBUG
NSAssert(static_cast<bool>(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) == isRunning, @"Cached value for _engine.isRunning invalid");
#endif /* DEBUG */
});
return isRunning;
}
- (BOOL)playerNodeIsPlaying
{
return _playerNode.isPlaying;
}
- (SFBAudioPlayerPlaybackState)playbackState
{
if(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning)
return _playerNode.isPlaying ? SFBAudioPlayerPlaybackStatePlaying : SFBAudioPlayerPlaybackStatePaused;
else
return SFBAudioPlayerPlaybackStateStopped;
}
- (BOOL)isPlaying
{
return (_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) && _playerNode.isPlaying;
}
- (BOOL)isPaused
{
return (_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) && !_playerNode.isPlaying;
}
- (BOOL)isStopped
{
return !(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning);
}
- (BOOL)isReady
{
return _playerNode.isReady;
}
- (id<SFBPCMDecoding>)currentDecoder
{
return _playerNode.currentDecoder;
}
- (id<SFBPCMDecoding>)nowPlaying
{
std::lock_guard<SFB::UnfairLock> lock(_nowPlayingLock);
return _nowPlaying;
}
- (void)setNowPlaying:(id<SFBPCMDecoding>)nowPlaying
{
{
std::lock_guard<SFB::UnfairLock> lock(_nowPlayingLock);
#if DEBUG
NSAssert(_nowPlaying != nowPlaying, @"Unnecessary _nowPlaying change to %@", nowPlaying);
#endif /* DEBUG */
_nowPlaying = nowPlaying;
}
os_log_debug(_audioPlayerLog, "Now playing changed to %{public}@", nowPlaying);
if([_delegate respondsToSelector:@selector(audioPlayer:nowPlayingChanged:)])
[_delegate audioPlayer:self nowPlayingChanged:nowPlaying];
}
#pragma mark - Playback Properties
- (AVAudioFramePosition)framePosition
{
return self.playbackPosition.framePosition;
}
- (AVAudioFramePosition)frameLength
{
return self.playbackPosition.frameLength;
}
- (SFBPlaybackPosition)playbackPosition
{
return _playerNode.playbackPosition;
}
- (NSTimeInterval)currentTime
{
return self.playbackTime.currentTime;
}
- (NSTimeInterval)totalTime
{
return self.playbackTime.totalTime;
}
- (SFBPlaybackTime)playbackTime
{
return _playerNode.playbackTime;
}
- (BOOL)getPlaybackPosition:(SFBPlaybackPosition *)playbackPosition andTime:(SFBPlaybackTime *)playbackTime
{
return [_playerNode getPlaybackPosition:playbackPosition andTime:playbackTime];
}
#pragma mark - Seeking
- (BOOL)seekForward
{
return [_playerNode seekForward:3];
}
- (BOOL)seekBackward
{
return [_playerNode seekBackward:3];
}
- (BOOL)seekForward:(NSTimeInterval)secondsToSkip
{
return [_playerNode seekForward:secondsToSkip];
}
- (BOOL)seekBackward:(NSTimeInterval)secondsToSkip
{
return [_playerNode seekBackward:secondsToSkip];
}
- (BOOL)seekToTime:(NSTimeInterval)timeInSeconds
{
return [_playerNode seekToTime:timeInSeconds];
}
- (BOOL)seekToPosition:(double)position
{
return [_playerNode seekToPosition:position];
}
- (BOOL)seekToFrame:(AVAudioFramePosition)frame
{
return [_playerNode seekToFrame:frame];
}
- (BOOL)supportsSeeking
{
return _playerNode.supportsSeeking;
}
#if !TARGET_OS_IPHONE
#pragma mark - Volume Control
- (float)volume
{
return [self volumeForChannel:0];
}
- (BOOL)setVolume:(float)volume error:(NSError **)error
{
return [self setVolume:volume forChannel:0 error:error];
}
- (float)volumeForChannel:(AudioObjectPropertyElement)channel
{
__block float volume = std::nanf("1");
dispatch_async_and_wait(_engineQueue, ^{
AudioUnitParameterValue channelVolume;
OSStatus result = AudioUnitGetParameter(_engine.outputNode.audioUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, channel, &channelVolume);
if(result != noErr) {
os_log_error(_audioPlayerLog, "AudioUnitGetParameter (kHALOutputParam_Volume, kAudioUnitScope_Global, %u) failed: %d '%{public}.4s'", channel, result, SFBCStringForOSType(result));
return;
}
volume = channelVolume;
});
return volume;
}
- (BOOL)setVolume:(float)volume forChannel:(AudioObjectPropertyElement)channel error:(NSError **)error
{
os_log_info(_audioPlayerLog, "Setting volume for channel %u to %g", channel, volume);
__block BOOL success = NO;
__block NSError *err = nil;
dispatch_async_and_wait(_engineQueue, ^{
AudioUnitParameterValue channelVolume = volume;
OSStatus result = AudioUnitSetParameter(_engine.outputNode.audioUnit, kHALOutputParam_Volume, kAudioUnitScope_Global, channel, channelVolume, 0);
if(result != noErr) {
os_log_error(_audioPlayerLog, "AudioUnitGetParameter (kHALOutputParam_Volume, kAudioUnitScope_Global, %u) failed: %d '%{public}.4s'", channel, result, SFBCStringForOSType(result));
err = [NSError errorWithDomain:NSOSStatusErrorDomain code:result userInfo:nil];
return;
}
success = YES;
});
if(!success && error)
*error = err;
return success;
}
#pragma mark - Output Device
- (AUAudioObjectID)outputDeviceID
{
__block AUAudioObjectID objectID = kAudioObjectUnknown;
dispatch_async_and_wait(_engineQueue, ^{
objectID = _engine.outputNode.AUAudioUnit.deviceID;
});
return objectID;
}
- (BOOL)setOutputDeviceID:(AUAudioObjectID)outputDeviceID error:(NSError **)error
{
os_log_info(_audioPlayerLog, "Setting output device to 0x%x", outputDeviceID);
__block BOOL result;
__block NSError *err = nil;
dispatch_async_and_wait(_engineQueue, ^{
result = [_engine.outputNode.AUAudioUnit setDeviceID:outputDeviceID error:&err];
});
if(!result) {
os_log_error(_audioPlayerLog, "Error setting output device: %{public}@", err);
if(error)
*error = err;
}
return result;
}
#endif /* !TARGET_OS_IPHONE */
#pragma mark - AVAudioEngine
- (void)withEngine:(SFBAudioPlayerAVAudioEngineBlock)block
{
dispatch_async_and_wait(_engineQueue, ^{
block(_engine);
// SFBAudioPlayer requires that the mixer node be connected to the output node
NSAssert([_engine inputConnectionPointForNode:_engine.outputNode inputBus:0].node == _engine.mainMixerNode, @"Illegal AVAudioEngine configuration");
NSAssert(_engine.isRunning == static_cast<bool>(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning), @"AVAudioEngine may not be started or stopped outside of SFBAudioPlayer");
});
}
#pragma mark - Debugging
-(void)logProcessingGraphDescription:(os_log_t)log type:(os_log_type_t)type
{
dispatch_async(_engineQueue, ^{
NSMutableString *string = [NSMutableString stringWithFormat:@"%@ audio processing graph:\n", self];
const auto playerNode = self->_playerNode;
const auto engine = self->_engine;
AVAudioFormat *inputFormat = playerNode.renderingFormat;
[string appendFormat:@"↓ rendering\n %@\n", SFB::StringDescribingAVAudioFormat(inputFormat)];
AVAudioFormat *outputFormat = [playerNode outputFormatForBus:0];
if(![outputFormat isEqual:inputFormat])
[string appendFormat:@"→ %@\n %@\n", playerNode, SFB::StringDescribingAVAudioFormat(outputFormat)];
else
[string appendFormat:@"→ %@\n", playerNode];
AVAudioConnectionPoint *connectionPoint = [[engine outputConnectionPointsForNode:playerNode outputBus:0] firstObject];
while(connectionPoint.node != engine.mainMixerNode) {
inputFormat = [connectionPoint.node inputFormatForBus:connectionPoint.bus];
outputFormat = [connectionPoint.node outputFormatForBus:connectionPoint.bus];
if(![outputFormat isEqual:inputFormat])
[string appendFormat:@"→ %@\n %@\n", connectionPoint.node, SFB::StringDescribingAVAudioFormat(outputFormat)];
else
[string appendFormat:@"→ %@\n", connectionPoint.node];
connectionPoint = [[engine outputConnectionPointsForNode:connectionPoint.node outputBus:0] firstObject];
}
inputFormat = [engine.mainMixerNode inputFormatForBus:0];
outputFormat = [engine.mainMixerNode outputFormatForBus:0];
if(![outputFormat isEqual:inputFormat])
[string appendFormat:@"→ %@\n %@\n", engine.mainMixerNode, SFB::StringDescribingAVAudioFormat(outputFormat)];
else
[string appendFormat:@"→ %@\n", engine.mainMixerNode];
inputFormat = [engine.outputNode inputFormatForBus:0];
outputFormat = [engine.outputNode outputFormatForBus:0];
if(![outputFormat isEqual:inputFormat])
[string appendFormat:@"→ %@\n %@]", engine.outputNode, SFB::StringDescribingAVAudioFormat(outputFormat)];
else
[string appendFormat:@"→ %@", engine.outputNode];
#if !TARGET_OS_IPHONE
[string appendFormat:@"\n↓ \"%@\"", AudioDeviceName(engine.outputNode.AUAudioUnit)];
#endif /* !TARGET_OS_IPHONE */
os_log_with_type(log, type, "%{public}@", string);
});
}
#pragma mark - Decoder Queue
- (BOOL)internalDecoderQueueIsEmpty
{
std::lock_guard<SFB::UnfairLock> lock(_queueLock);
return _queuedDecoders.empty();
}
- (void)clearInternalDecoderQueue
{
std::lock_guard<SFB::UnfairLock> lock(_queueLock);
_queuedDecoders.resize(0);
}
- (BOOL)pushDecoderToInternalQueue:(id <SFBPCMDecoding>)decoder
{
try {
std::lock_guard<SFB::UnfairLock> lock(_queueLock);
_queuedDecoders.push_back(decoder);
}
catch(const std::exception& e) {
os_log_error(_audioPlayerLog, "Error pushing %{public}@ to _queuedDecoders: %{public}s", decoder, e.what());
return NO;
}
return YES;
}
- (id <SFBPCMDecoding>)popDecoderFromInternalQueue
{
id <SFBPCMDecoding> decoder = nil;
std::lock_guard<SFB::UnfairLock> lock(_queueLock);
if(!_queuedDecoders.empty()) {
decoder = _queuedDecoders.front();
_queuedDecoders.pop_front();
}
return decoder;
}
#pragma mark - Internals
- (void)handleAudioEngineConfigurationChange:(NSNotification *)notification
{
NSAssert([notification object] == _engine, @"AVAudioEngineConfigurationChangeNotification received for incorrect AVAudioEngine instance");
os_log_debug(_audioPlayerLog, "Received AVAudioEngineConfigurationChangeNotification");
// AVAudioEngine stops itself when interrupted and there is no way to determine if the engine was
// running before this notification was issued unless the state is cached
const bool engineWasRunning = _flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning;
_flags.fetch_and(~eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
// Attempt to preserve the playback state
const BOOL playerNodeWasPlaying = _playerNode.isPlaying;
// AVAudioEngine posts this notification from a dedicated queue
__block BOOL success;
__block NSError *error = nil;
dispatch_async_and_wait(_engineQueue, ^{
[_playerNode pause];
// Force an update of the audio processing graph
success = [self configureProcessingGraphForFormat:_playerNode.renderingFormat forceUpdate:YES];
if(!success) {
os_log_error(_audioPlayerLog, "Unable to create audio processing graph for %{public}@", SFB::StringDescribingAVAudioFormat(_playerNode.renderingFormat));
error = [NSError errorWithDomain:SFBAudioPlayerNodeErrorDomain code:SFBAudioPlayerNodeErrorCodeFormatNotSupported userInfo:nil];
return;
}
// Restart AVAudioEngine if previously running
if(engineWasRunning) {
BOOL engineStarted = [_engine startAndReturnError:&error];
if(!engineStarted) {
os_log_error(_audioPlayerLog, "Error starting AVAudioEngine: %{public}@", error);
return;
}
_flags.fetch_or(eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
// Restart the player node if needed
if(playerNodeWasPlaying)
[_playerNode play];
}
});
// Success in this context means the graph is in a working state, not that the engine was restarted successfully
if(!success) {
if([_delegate respondsToSelector:@selector(audioPlayer:encounteredError:)])
[_delegate audioPlayer:self encounteredError:error];
return;
}
if((engineWasRunning != static_cast<bool>(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) || playerNodeWasPlaying != _playerNode.isPlaying) && [_delegate respondsToSelector:@selector(audioPlayer:playbackStateChanged:)])
[_delegate audioPlayer:self playbackStateChanged:self.playbackState];
if([_delegate respondsToSelector:@selector(audioPlayerAVAudioEngineConfigurationChange:)])
[_delegate audioPlayerAVAudioEngineConfigurationChange:self];
}
#if TARGET_OS_IPHONE
- (void)handleAudioSessionInterruption:(NSNotification *)notification
{
NSUInteger interruptionType = [[[notification userInfo] objectForKey:AVAudioSessionInterruptionTypeKey] unsignedIntegerValue];
switch(interruptionType) {
case AVAudioSessionInterruptionTypeBegan:
os_log_debug(_audioPlayerLog, "Received AVAudioSessionInterruptionNotification (AVAudioSessionInterruptionTypeBegan)");
[self pause];
break;
case AVAudioSessionInterruptionTypeEnded:
os_log_debug(_audioPlayerLog, "Received AVAudioSessionInterruptionNotification (AVAudioSessionInterruptionTypeEnded)");
// AVAudioEngine stops itself when AVAudioSessionInterruptionNotification is received
// However, eAudioPlayerFlagEngineIsRunning indicates if the engine was running before the interruption
if(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) {
_flags.fetch_and(~eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
dispatch_async_and_wait(_engineQueue, ^{
NSError *error = nil;
BOOL engineStarted = [_engine startAndReturnError:&error];
if(engineStarted)
_flags.fetch_or(eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
else
os_log_error(_audioPlayerLog, "Error starting AVAudioEngine: %{public}@", error);
});
}
break;
default:
os_log_error(_audioPlayerLog, "Unknown value %lu for AVAudioSessionInterruptionTypeKey", static_cast<unsigned long>(interruptionType));
break;
}
}
#endif /* TARGET_OS_IPHONE */
- (BOOL)configureForAndEnqueueDecoder:(id <SFBPCMDecoding>)decoder forImmediatePlayback:(BOOL)forImmediatePlayback error:(NSError **)error
{
NSParameterAssert(decoder != nil);
// Attempt to preserve the playback state
const bool engineWasRunning = _flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning;
const BOOL playerNodeWasPlaying = _playerNode.isPlaying;
__block BOOL success = YES;
// If the current SFBAudioPlayerNode doesn't support the decoder's format (required for gapless join),
// reconfigure AVAudioEngine with a new SFBAudioPlayerNode with the correct format
if(auto format = decoder.processingFormat; ![_playerNode supportsFormat:format])
dispatch_async_and_wait(_engineQueue, ^{
success = [self configureProcessingGraphForFormat:format forceUpdate:NO];
});
if(!success) {
if(error)
*error = [NSError errorWithDomain:SFBAudioPlayerNodeErrorDomain code:SFBAudioPlayerNodeErrorCodeFormatNotSupported userInfo:nil];
if(self.nowPlaying)
self.nowPlaying = nil;
return NO;
}
if(forImmediatePlayback) {
[self clearInternalDecoderQueue];
success = [_playerNode resetAndEnqueueDecoder:decoder error:error];
}
else
success = [_playerNode enqueueDecoder:decoder error:error];
// Failure is unlikely since the audio processing graph was reconfigured for the decoder's processing format
if(!success) {
if(self.nowPlaying)
self.nowPlaying = nil;
return NO;
}
// AVAudioEngine may have been stopped in `-configureProcessingGraphForFormat:forceUpdate:`
// If this is the case and it was previously running, restart it and the player node
// as appropriate
if(engineWasRunning && !(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning)) {
__block BOOL engineStarted = NO;
__block NSError *err = nil;
dispatch_async_and_wait(_engineQueue, ^{
engineStarted = [_engine startAndReturnError:&err];
if(engineStarted) {
_flags.fetch_or(eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
if(playerNodeWasPlaying)
[_playerNode play];
}
});
if(!engineStarted) {
os_log_error(_audioPlayerLog, "Error starting AVAudioEngine: %{public}@", err);
if(error)
*error = err;
return NO;
}
}
#if DEBUG
NSAssert(engineWasRunning == static_cast<bool>(_flags.load(std::memory_order_acquire) & eAudioPlayerFlagEngineIsRunning) && playerNodeWasPlaying == _playerNode.isPlaying, @"Incorrect playback state in -configureForAndEnqueueDecoder:forImmediatePlayback:error:");
#endif /* DEBUG */
return YES;
}
- (BOOL)configureProcessingGraphForFormat:(AVAudioFormat *)format forceUpdate:(BOOL)forceUpdate
{
NSParameterAssert(format != nil);
// SFBAudioPlayerNode requires the standard format
if(!format.isStandard) {
AVAudioFormat *standardEquivalentFormat = [format standardEquivalent];
if(!standardEquivalentFormat) {
os_log_error(_audioPlayerLog, "Unable to convert format %{public}@ to standard equivalent", SFB::StringDescribingAVAudioFormat(format));
return NO;
}
format = standardEquivalentFormat;
}
// _playerNode may be nil since this method is called from -init
const auto formatsEqual = [format isEqual:_playerNode.renderingFormat];
if(formatsEqual && !forceUpdate)
return YES;
// Even if the engine isn't running, call stop to force release of any render resources
// Empirically this is necessary when transitioning between formats with different
// channel counts, although it seems that it shouldn't be
[_engine stop];
_flags.fetch_and(~eAudioPlayerFlagEngineIsRunning, std::memory_order_acq_rel);
if(_playerNode.isPlaying)
[_playerNode stop];
// Avoid creating a new SFBAudioPlayerNode if not necessary
SFBAudioPlayerNode *playerNode = nil;
if(!formatsEqual) {
playerNode = [[SFBAudioPlayerNode alloc] initWithFormat:format];
if(!playerNode) {
os_log_error(_audioPlayerLog, "Unable to create SFBAudioPlayerNode with format %{public}@", SFB::StringDescribingAVAudioFormat(format));
return NO;
}
playerNode.delegate = self;
}
AVAudioOutputNode *outputNode = _engine.outputNode;
AVAudioMixerNode *mixerNode = _engine.mainMixerNode;
// SFBAudioPlayer requires that the main mixer node be connected to the output node
NSAssert([_engine inputConnectionPointForNode:outputNode inputBus:0].node == mixerNode, @"Illegal AVAudioEngine configuration");
AVAudioFormat *outputNodeOutputFormat = [outputNode outputFormatForBus:0];
AVAudioFormat *mixerNodeOutputFormat = [mixerNode outputFormatForBus:0];
const auto outputFormatsMismatch = outputNodeOutputFormat.channelCount != mixerNodeOutputFormat.channelCount || outputNodeOutputFormat.sampleRate != mixerNodeOutputFormat.sampleRate;
if(outputFormatsMismatch) {
os_log_debug(_audioPlayerLog,
"Mismatch between output formats for main mixer and output nodes:\n mainMixerNode: %{public}@\n outputNode: %{public}@",
SFB::StringDescribingAVAudioFormat(mixerNodeOutputFormat),
SFB::StringDescribingAVAudioFormat(outputNodeOutputFormat));
[_engine disconnectNodeInput:outputNode bus:0];
// Reconnect the mixer and output nodes using the output node's output format
[_engine connect:mixerNode to:outputNode format:outputNodeOutputFormat];
}
if(playerNode) {
AVAudioConnectionPoint *playerNodeOutputConnectionPoint = nil;
if(_playerNode) {
playerNodeOutputConnectionPoint = [[_engine outputConnectionPointsForNode:_playerNode outputBus:0] firstObject];
[_engine detachNode:_playerNode];
// When an audio player node is deallocated the destructor synchronously waits
// for decoder cancelation (if there is an active decoder) and then for any
// final events to be processed and delegate messages sent.
// The potential therefore exists to block the calling thread for a perceptible amount
// of time, especially if the delegate callouts take longer than ideal.
//
// In my measurements the baseline with an empty delegate implementation of
// -audioPlayer:decoderCanceled:framesRendered: seems to be around 100 µsec
//
// Assuming there are no external references to the audio player node,
// setting it to nil here sends -dealloc
_playerNode = nil;
}
_playerNode = playerNode;
[_engine attachNode:_playerNode];
// Reconnect the player node to the next node in the processing chain
// This is the mixer node in the default configuration, but additional nodes may
// have been inserted between the player and mixer nodes. In this case allow the delegate
// to make any necessary adjustments based on the format change if desired.
if(playerNodeOutputConnectionPoint && playerNodeOutputConnectionPoint.node != mixerNode) {
if([_delegate respondsToSelector:@selector(audioPlayer:reconfigureProcessingGraph:withFormat:)]) {
AVAudioNode *node = [_delegate audioPlayer:self reconfigureProcessingGraph:_engine withFormat:format];
// Ensure the delegate returned a valid node
NSAssert(node != nil, @"nil AVAudioNode returned by -audioPlayer:reconfigureProcessingGraph:withFormat:");
[_engine connect:_playerNode to:node format:format];
}
else
[_engine connect:_playerNode to:playerNodeOutputConnectionPoint.node format:format];
}
else
[_engine connect:_playerNode to:mixerNode format:format];
}
// AVAudioMixerNode handles sample rate conversion, but it may require input buffer sizes
// (maximum frames per slice) greater than the default for AVAudioSourceNode (1156).
//
// For high sample rates, the sample rate conversion can require more rendered frames than are available by default.
// For example, 192 KHz audio converted to 44.1 HHz requires approximately (192 / 44.1) * 512 = 2229 frames
// So if the input and output sample rates on the mixer don't match, adjust
// kAudioUnitProperty_MaximumFramesPerSlice to ensure enough audio data is passed per render cycle
// See http://lists.apple.com/archives/coreaudio-api/2009/Oct/msg00150.html
if(format.sampleRate > outputNodeOutputFormat.sampleRate) {
os_log_debug(_audioPlayerLog, "AVAudioMixerNode input sample rate (%g Hz) and output sample rate (%g Hz) don't match", format.sampleRate, outputNodeOutputFormat.sampleRate);
// 512 is the nominal "standard" value for kAudioUnitProperty_MaximumFramesPerSlice
const double ratio = format.sampleRate / outputNodeOutputFormat.sampleRate;
const auto maximumFramesToRender = static_cast<AUAudioFrameCount>(std::ceil(512 * ratio));
if(auto audioUnit = _playerNode.AUAudioUnit; audioUnit.maximumFramesToRender < maximumFramesToRender) {
const auto renderResourcesAllocated = audioUnit.renderResourcesAllocated;
if(renderResourcesAllocated)
[audioUnit deallocateRenderResources];
os_log_debug(_audioPlayerLog, "Adjusting SFBAudioPlayerNode's maximumFramesToRender to %u", maximumFramesToRender);
audioUnit.maximumFramesToRender = maximumFramesToRender;
NSError *error;
if(renderResourcesAllocated && ![audioUnit allocateRenderResourcesAndReturnError:&error]) {
os_log_error(_audioPlayerLog, "Error allocating AUAudioUnit render resources for SFBAudioPlayerNode: %{public}@", error);
}
}
}
#if DEBUG