-
Notifications
You must be signed in to change notification settings - Fork 90
/
Copy pathAudioPlayerNode.mm
1425 lines (1156 loc) · 53 KB
/
AudioPlayerNode.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 <algorithm>
#import <cassert>
#import <cmath>
#import <cstring>
#import <exception>
#import <system_error>
#import <AVFAudio/AVFAudio.h>
#import "AudioPlayerNode.h"
#import "AVAudioChannelLayoutsAreEquivalent.h"
#import "HostTimeUtilities.hpp"
#import "NSError+SFBURLPresentation.h"
#import "SFBAudioDecoder.h"
#import "StringDescribingAVAudioFormat.h"
namespace {
/// The minimum number of frames to write to the ring buffer
constexpr AVAudioFrameCount kRingBufferChunkSize = 2048;
/// libdispatch destructor function for `NSError` objects
void release_nserror_f(void * _Nullable context)
{
(void)(__bridge_transfer NSError *)context;
}
/// libdispatch function that calls `ProcessPendingEvents` on `context`
void process_pending_events_f(void *context) noexcept
{
#if DEBUG
assert(context != nullptr);
#endif /* DEBUG */
auto that = static_cast<SFB::AudioPlayerNode *>(context);
that->ProcessPendingEvents();
}
} /* namespace */
namespace SFB {
/// Returns the next event identification number
/// - note: Event identification numbers are unique across all event types
uint64_t NextEventIdentificationNumber() noexcept
{
static std::atomic_uint64_t nextIdentificationNumber = 1;
static_assert(std::atomic_uint64_t::is_always_lock_free, "Lock-free std::atomic_uint64_t required");
return nextIdentificationNumber.fetch_add(1);
}
const os_log_t AudioPlayerNode::sLog = os_log_create("org.sbooth.AudioEngine", "AudioPlayerNode");
#pragma mark - Decoder State
/// State for tracking/syncing decoding progress
struct AudioPlayerNode::DecoderState final {
using atomic_ptr = std::atomic<DecoderState *>;
static_assert(atomic_ptr::is_always_lock_free, "Lock-free std::atomic<DecoderState *> required");
/// Monotonically increasing instance counter
const uint64_t mSequenceNumber = sSequenceNumber++;
/// The sample rate of the audio converter's output format
const double mSampleRate = 0;
/// Decodes audio from the source representation to PCM
const id <SFBPCMDecoding> mDecoder = nil;
private:
static constexpr AVAudioFrameCount kDefaultFrameCapacity = 1024;
/// Possible `DecoderState` flag values
enum DecoderStateFlags : unsigned int {
/// Decoding started
eFlagDecodingStarted = 1u << 0,
/// Decoding complete
eFlagDecodingComplete = 1u << 1,
/// Rendering started
eFlagRenderingStarted = 1u << 2,
/// Rendering complete
eFlagRenderingComplete = 1u << 3,
/// A seek has been requested
eFlagSeekPending = 1u << 4,
/// Decoder canceled
eFlagCanceled = 1u << 5,
};
/// Flags
std::atomic_uint mFlags = 0;
static_assert(std::atomic_uint::is_always_lock_free, "Lock-free std::atomic_uint required");
/// The number of frames decoded
std::atomic_int64_t mFramesDecoded = 0;
/// The number of frames converted
std::atomic_int64_t mFramesConverted = 0;
/// The number of frames rendered
std::atomic_int64_t mFramesRendered = 0;
/// The total number of audio frames
std::atomic_int64_t mFrameLength = 0;
/// The desired seek offset
std::atomic_int64_t mFrameToSeek = SFBUnknownFramePosition;
static_assert(std::atomic_int64_t::is_always_lock_free, "Lock-free std::atomic_int64_t required");
/// Converts audio from the decoder's processing format to another PCM variant at the same sample rate
AVAudioConverter *mConverter = nil;
/// Buffer used internally for buffering during conversion
AVAudioPCMBuffer *mDecodeBuffer = nil;
/// Next sequence number to use
static uint64_t sSequenceNumber;
public:
DecoderState(id <SFBPCMDecoding> _Nonnull decoder, AVAudioFormat * _Nonnull format, AVAudioFrameCount frameCapacity = kDefaultFrameCapacity)
: mFrameLength{decoder.frameLength}, mDecoder{decoder}, mSampleRate{format.sampleRate}
{
#if DEBUG
assert(decoder != nil);
assert(format != nil);
#endif /* DEBUG */
mConverter = [[AVAudioConverter alloc] initFromFormat:mDecoder.processingFormat toFormat:format];
if(!mConverter) {
os_log_error(sLog, "Error creating AVAudioConverter converting from %{public}@ to %{public}@", mDecoder.processingFormat, format);
throw std::runtime_error("Error creating AVAudioConverter");
}
// The logic in this class assumes no SRC is performed by mConverter
assert(mConverter.inputFormat.sampleRate == mConverter.outputFormat.sampleRate);
mDecodeBuffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:mConverter.inputFormat frameCapacity:frameCapacity];
if(!mDecodeBuffer)
throw std::system_error(std::error_code(ENOMEM, std::generic_category()));
if(const auto framePosition = decoder.framePosition; framePosition != 0) {
mFramesDecoded.store(framePosition);
mFramesConverted.store(framePosition);
mFramesRendered.store(framePosition);
}
}
AVAudioFramePosition FramePosition() const noexcept
{
return IsSeekPending() ? mFrameToSeek.load() : mFramesRendered.load();
}
AVAudioFramePosition FrameLength() const noexcept
{
return mFrameLength.load();
}
bool DecodeAudio(AVAudioPCMBuffer * _Nonnull buffer, NSError **error = nullptr) noexcept
{
#if DEBUG
assert(buffer != nil);
assert(buffer.frameCapacity == mDecodeBuffer.frameCapacity);
#endif /* DEBUG */
if(![mDecoder decodeIntoBuffer:mDecodeBuffer frameLength:mDecodeBuffer.frameCapacity error:error])
return false;
if(mDecodeBuffer.frameLength == 0) {
mFlags.fetch_or(eFlagDecodingComplete, std::memory_order_acq_rel);
#if false
// Some formats may not know the exact number of frames in advance
// without processing the entire file, which is a potentially slow operation
mFrameLength.store(mDecoder.framePosition);
#endif /* false */
buffer.frameLength = 0;
return true;
}
this->mFramesDecoded.fetch_add(mDecodeBuffer.frameLength);
// Only PCM to PCM conversions are performed
if(![mConverter convertToBuffer:buffer fromBuffer:mDecodeBuffer error:error])
return false;
mFramesConverted.fetch_add(buffer.frameLength);
// If `buffer` is not full but -decodeIntoBuffer:frameLength:error: returned `YES`
// decoding is complete
if(buffer.frameLength != buffer.frameCapacity)
mFlags.fetch_or(eFlagDecodingComplete, std::memory_order_acq_rel);
return true;
}
/// Returns `true` if `eFlagDecodingStarted` is set
bool HasDecodingStarted() const noexcept
{
return mFlags.load(std::memory_order_acquire) & eFlagDecodingStarted;
}
/// Sets `eFlagDecodingStarted`
void SetDecodingStarted() noexcept
{
mFlags.fetch_or(eFlagDecodingStarted, std::memory_order_acq_rel);
}
/// Returns `true` if `eFlagDecodingComplete` is set
bool IsDecodingComplete() const noexcept
{
return mFlags.load(std::memory_order_acquire) & eFlagDecodingComplete;
}
/// Returns `true` if `eFlagRenderingStarted` is set
bool HasRenderingStarted() const noexcept
{
return mFlags.load(std::memory_order_acquire) & eFlagRenderingStarted;
}
/// Sets `eFlagRenderingStarted`
void SetRenderingStarted() noexcept
{
mFlags.fetch_or(eFlagRenderingStarted, std::memory_order_acq_rel);
}
/// Returns `true` if `eFlagRenderingComplete` is set
bool IsRenderingComplete() const noexcept
{
return mFlags.load(std::memory_order_acquire) & eFlagRenderingComplete;
}
/// Sets `eFlagRenderingComplete`
void SetRenderingComplete() noexcept
{
mFlags.fetch_or(eFlagRenderingComplete, std::memory_order_acq_rel);
}
/// Returns `true` if `eFlagCanceled` is set
bool IsCanceled() const noexcept
{
return mFlags.load(std::memory_order_acquire) & eFlagCanceled;
}
/// Sets `eFlagCanceled`
void SetCanceled() noexcept
{
mFlags.fetch_or(eFlagCanceled, std::memory_order_acq_rel);
}
/// Returns the number of frames available to render.
///
/// This is the difference between the number of frames converted and the number of frames rendered
AVAudioFramePosition FramesAvailableToRender() const noexcept
{
return mFramesConverted.load() - mFramesRendered.load();
}
/// Returns `true` if there are no frames available to render.
bool AllAvailableFramesRendered() const noexcept
{
return FramesAvailableToRender() == 0;
}
/// Returns the number of frames rendered.
AVAudioFramePosition FramesRendered() const noexcept
{
return mFramesRendered.load();
}
/// Adds `count` number of frames to the total count of frames rendered.
void AddFramesRendered(AVAudioFramePosition count) noexcept
{
mFramesRendered.fetch_add(count);
}
/// Returns `true` if `eFlagSeekPending` is set
bool IsSeekPending() const noexcept
{
return mFlags.load(std::memory_order_acquire) & eFlagSeekPending;
}
/// Sets the pending seek request to `frame`
void RequestSeekToFrame(AVAudioFramePosition frame) noexcept
{
mFrameToSeek.store(frame);
mFlags.fetch_or(eFlagSeekPending, std::memory_order_acq_rel);
}
/// Performs the pending seek request, if present
bool PerformSeekIfRequired() noexcept
{
if(!IsSeekPending())
return true;
auto seekOffset = mFrameToSeek.load();
os_log_debug(sLog, "Seeking to frame %lld in %{public}@ ", seekOffset, mDecoder);
if([mDecoder seekToFrame:seekOffset error:nil])
// Reset the converter to flush any buffers
[mConverter reset];
else
os_log_debug(sLog, "Error seeking to frame %lld", seekOffset);
const auto newFrame = mDecoder.framePosition;
if(newFrame != seekOffset) {
os_log_debug(sLog, "Inaccurate seek to frame %lld, got %lld", seekOffset, newFrame);
seekOffset = newFrame;
}
// Clear the seek request
mFlags.fetch_and(~eFlagSeekPending, std::memory_order_acq_rel);
// Update the frame counters accordingly
// A seek is handled in essentially the same way as initial playback
if(newFrame != SFBUnknownFramePosition) {
mFramesDecoded.store(newFrame);
mFramesConverted.store(seekOffset);
mFramesRendered.store(seekOffset);
}
return newFrame != SFBUnknownFramePosition;
}
};
uint64_t AudioPlayerNode::DecoderState::sSequenceNumber = 1;
} /* namespace SFB */
#pragma mark - AudioPlayerNode
SFB::AudioPlayerNode::AudioPlayerNode(AVAudioFormat *format, uint32_t ringBufferSize)
: mRenderingFormat{format}
{
#if DEBUG
assert(format != nil);
#endif /* DEBUG */
os_log_debug(sLog, "Created <AudioPlayerNode: %p>, rendering format %{public}@", this, SFB::StringDescribingAVAudioFormat(mRenderingFormat));
// Allocate and initialize the decoder state array
mActiveDecoders = new DecoderStateArray;
for(auto& atomic_ptr : *mActiveDecoders)
atomic_ptr.store(nullptr, std::memory_order_release);
// ========================================
// Decoding Setup
// Create the dispatch queue used for decoding
dispatch_queue_attr_t attr = dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_USER_INITIATED, 0);
if(!attr) {
os_log_error(sLog, "dispatch_queue_attr_make_with_qos_class failed");
throw std::runtime_error("dispatch_queue_attr_make_with_qos_class failed");
}
mDecodingQueue = dispatch_queue_create_with_target("AudioPlayerNode.Decoding", attr, DISPATCH_TARGET_QUEUE_DEFAULT);
if(!mDecodingQueue) {
os_log_error(sLog, "Unable to create decoding dispatch queue: dispatch_queue_create_with_target failed");
throw std::runtime_error("dispatch_queue_create_with_target failed");
}
mDecodingGroup = dispatch_group_create();
if(!mDecodingGroup) {
os_log_error(sLog, "Unable to decoding dispatch group: dispatch_group_create failed");
throw std::runtime_error("dispatch_group_create failed");
}
// ========================================
// Rendering Setup
// Allocate the audio ring buffer moving audio from the decoder queue to the render block
if(!mAudioRingBuffer.Allocate(*(mRenderingFormat.streamDescription), ringBufferSize)) {
os_log_error(sLog, "Unable to create audio ring buffer: SFB::AudioRingBuffer::Allocate failed");
throw std::runtime_error("SFB::AudioRingBuffer::Allocate failed");
}
// Set up the render block
mRenderBlock = ^OSStatus(BOOL *isSilence, const AudioTimeStamp *timestamp, AVAudioFrameCount frameCount, AudioBufferList *outputData) {
return Render(*isSilence, *timestamp, frameCount, outputData);
};
// ========================================
// Event Processing Setup
// The decode event ring buffer is written to by the decoding queue and read from by the event queue
if(!mDecodeEventRingBuffer.Allocate(256)) {
os_log_error(sLog, "Unable to create decode event ring buffer: SFB::RingBuffer::Allocate failed");
throw std::runtime_error("SFB::RingBuffer::Allocate failed");
}
// The render event ring buffer is written to by the render block and read from by the event queue
if(!mRenderEventRingBuffer.Allocate(256)) {
os_log_error(sLog, "Unable to create render event ring buffer: SFB::RingBuffer::Allocate failed");
throw std::runtime_error("SFB::RingBuffer::Allocate failed");
}
// Create the dispatch queue used for event processing, reusing the same attributes
mEventProcessingQueue = dispatch_queue_create_with_target("AudioPlayerNode.Events", attr, DISPATCH_TARGET_QUEUE_DEFAULT);
if(!mEventProcessingQueue) {
os_log_error(sLog, "Unable to create event processing dispatch queue: dispatch_queue_create_with_target failed");
throw std::runtime_error("dispatch_queue_create_with_target failed");
}
// Create the dispatch group used to track event processing initiated from the decoding queue
mEventProcessingGroup = dispatch_group_create();
if(!mEventProcessingGroup) {
os_log_error(sLog, "Unable to create event processing dispatch group: dispatch_group_create failed");
throw std::runtime_error("dispatch_group_create failed");
}
// Create the dispatch source used to trigger event processing from the render block
mEventProcessingSource = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_OR, 0, 0, mEventProcessingQueue);
if(!mEventProcessingSource) {
os_log_error(sLog, "Unable to create event processing dispatch source: dispatch_source_create failed");
throw std::runtime_error("dispatch_source_create failed");
}
dispatch_set_context(mEventProcessingSource, this);
dispatch_source_set_event_handler_f(mEventProcessingSource, process_pending_events_f);
// Start processing events from the render block
dispatch_activate(mEventProcessingSource);
}
SFB::AudioPlayerNode::~AudioPlayerNode()
{
Stop();
// Cancel any further event processing initiated by the render block
dispatch_source_cancel(mEventProcessingSource);
// Wait for the current decoder to complete cancelation
dispatch_group_wait(mDecodingGroup, DISPATCH_TIME_FOREVER);
// Wait for event processing initiated by the decoding queue to complete
dispatch_group_wait(mEventProcessingGroup, DISPATCH_TIME_FOREVER);
// Delete any remaining decoder state
for(auto& atomic_ptr : *mActiveDecoders)
delete atomic_ptr.exchange(nullptr);
delete mActiveDecoders;
os_log_debug(sLog, "<AudioPlayerNode: %p> destroyed", this);
}
#pragma mark - Playback Properties
SFBPlaybackPosition SFB::AudioPlayerNode::PlaybackPosition() const noexcept
{
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState)
return SFBInvalidPlaybackPosition;
return { .framePosition = decoderState->FramePosition(), .frameLength = decoderState->FrameLength() };
}
SFBPlaybackTime SFB::AudioPlayerNode::PlaybackTime() const noexcept
{
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState)
return SFBInvalidPlaybackTime;
SFBPlaybackTime playbackTime = SFBInvalidPlaybackTime;
const auto framePosition = decoderState->FramePosition();
const auto frameLength = decoderState->FrameLength();
if(const auto sampleRate = decoderState->mSampleRate; sampleRate > 0) {
if(framePosition != SFBUnknownFramePosition)
playbackTime.currentTime = framePosition / sampleRate;
if(frameLength != SFBUnknownFrameLength)
playbackTime.totalTime = frameLength / sampleRate;
}
return playbackTime;
}
bool SFB::AudioPlayerNode::GetPlaybackPositionAndTime(SFBPlaybackPosition *playbackPosition, SFBPlaybackTime *playbackTime) const noexcept
{
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState) {
if(playbackPosition)
*playbackPosition = SFBInvalidPlaybackPosition;
if(playbackTime)
*playbackTime = SFBInvalidPlaybackTime;
return false;
}
SFBPlaybackPosition currentPlaybackPosition = { .framePosition = decoderState->FramePosition(), .frameLength = decoderState->FrameLength() };
if(playbackPosition)
*playbackPosition = currentPlaybackPosition;
if(playbackTime) {
SFBPlaybackTime currentPlaybackTime = SFBInvalidPlaybackTime;
if(const auto sampleRate = decoderState->mSampleRate; sampleRate > 0) {
if(currentPlaybackPosition.framePosition != SFBUnknownFramePosition)
currentPlaybackTime.currentTime = currentPlaybackPosition.framePosition / sampleRate;
if(currentPlaybackPosition.frameLength != SFBUnknownFrameLength)
currentPlaybackTime.totalTime = currentPlaybackPosition.frameLength / sampleRate;
}
*playbackTime = currentPlaybackTime;
}
return true;
}
#pragma mark - Seeking
bool SFB::AudioPlayerNode::SeekForward(NSTimeInterval secondsToSkip) noexcept
{
if(secondsToSkip < 0)
secondsToSkip = 0;
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState || !decoderState->mDecoder.supportsSeeking)
return false;
const auto sampleRate = decoderState->mSampleRate;
const auto framePosition = decoderState->FramePosition();
const auto frameLength = decoderState->FrameLength();
auto targetFrame = framePosition + static_cast<AVAudioFramePosition>(secondsToSkip * sampleRate);
if(targetFrame >= frameLength)
targetFrame = std::max(frameLength - 1, 0ll);
decoderState->RequestSeekToFrame(targetFrame);
mDecodingSemaphore.Signal();
return true;
}
bool SFB::AudioPlayerNode::SeekBackward(NSTimeInterval secondsToSkip) noexcept
{
if(secondsToSkip < 0)
secondsToSkip = 0;
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState || !decoderState->mDecoder.supportsSeeking)
return false;
const auto sampleRate = decoderState->mSampleRate;
const auto framePosition = decoderState->FramePosition();
auto targetFrame = framePosition - static_cast<AVAudioFramePosition>(secondsToSkip * sampleRate);
if(targetFrame < 0)
targetFrame = 0;
decoderState->RequestSeekToFrame(targetFrame);
mDecodingSemaphore.Signal();
return true;
}
bool SFB::AudioPlayerNode::SeekToTime(NSTimeInterval timeInSeconds) noexcept
{
if(timeInSeconds < 0)
timeInSeconds = 0;
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState || !decoderState->mDecoder.supportsSeeking)
return false;
const auto sampleRate = decoderState->mSampleRate;
const auto frameLength = decoderState->FrameLength();
auto targetFrame = static_cast<AVAudioFramePosition>(timeInSeconds * sampleRate);
if(targetFrame >= frameLength)
targetFrame = std::max(frameLength - 1, 0ll);
decoderState->RequestSeekToFrame(targetFrame);
mDecodingSemaphore.Signal();
return true;
}
bool SFB::AudioPlayerNode::SeekToPosition(double position) noexcept
{
if(position < 0)
position = 0;
else if(position >= 1)
position = std::nextafter(1.0, 0.0);
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState || !decoderState->mDecoder.supportsSeeking)
return false;
const auto frameLength = decoderState->FrameLength();
const auto targetFrame = static_cast<AVAudioFramePosition>(frameLength * position);
decoderState->RequestSeekToFrame(targetFrame);
mDecodingSemaphore.Signal();
return true;
}
bool SFB::AudioPlayerNode::SeekToFrame(AVAudioFramePosition frame) noexcept
{
if(frame < 0)
frame = 0;
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
if(!decoderState || !decoderState->mDecoder.supportsSeeking)
return false;
const auto frameLength = decoderState->FrameLength();
if(frame >= frameLength)
frame = std::max(frameLength - 1, 0ll);
decoderState->RequestSeekToFrame(frame);
mDecodingSemaphore.Signal();
return true;
}
bool SFB::AudioPlayerNode::SupportsSeeking() const noexcept
{
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
return decoderState ? decoderState->mDecoder.supportsSeeking : false;
}
#pragma mark - Format Information
bool SFB::AudioPlayerNode::SupportsFormat(AVAudioFormat *format) const noexcept
{
#if DEBUG
assert(format != nil);
#endif /* DEBUG */
// Gapless playback requires the same number of channels at the same sample rate with the same channel layout
const auto channelLayoutsAreEquivalent = AVAudioChannelLayoutsAreEquivalent(format.channelLayout, mRenderingFormat.channelLayout);
return format.channelCount == mRenderingFormat.channelCount && format.sampleRate == mRenderingFormat.sampleRate && channelLayoutsAreEquivalent;
}
#pragma mark - Queue Management
bool SFB::AudioPlayerNode::EnqueueDecoder(id <SFBPCMDecoding> decoder, bool reset, NSError **error) noexcept
{
#if DEBUG
assert(decoder != nil);
#endif /* DEBUG */
if(!decoder.isOpen && ![decoder openReturningError:error])
return false;
if(!SupportsFormat(decoder.processingFormat)) {
os_log_error(sLog, "Unsupported decoder processing format: %{public}@", SFB::StringDescribingAVAudioFormat(decoder.processingFormat));
if(error)
*error = [NSError SFB_errorWithDomain:SFBAudioPlayerNodeErrorDomain
code:SFBAudioPlayerNodeErrorCodeFormatNotSupported
descriptionFormatStringForURL:NSLocalizedString(@"The format of the file “%@” is not supported.", @"")
url:decoder.inputSource.url
failureReason:NSLocalizedString(@"Unsupported file format", @"")
recoverySuggestion:NSLocalizedString(@"The file's format is not supported by this player.", @"")];
return false;
}
if(reset) {
// Mute until the decoder becomes active to prevent spurious events
mFlags.fetch_or(eFlagMuteRequested, std::memory_order_acq_rel);
Reset();
}
try {
std::lock_guard<SFB::UnfairLock> lock(mQueueLock);
mQueuedDecoders.push_back(decoder);
}
catch(const std::exception& e) {
os_log_error(sLog, "Error pushing %{public}@ to mQueuedDecoders: %{public}s", decoder, e.what());
if(error)
*error = [NSError errorWithDomain:NSPOSIXErrorDomain code:ENOMEM userInfo:nil];
if(reset)
mFlags.fetch_and(~eFlagMuteRequested, std::memory_order_acq_rel);
return false;
}
os_log_info(sLog, "Enqueued %{public}@", decoder);
DequeueAndProcessDecoder(reset);
return true;
}
id <SFBPCMDecoding> SFB::AudioPlayerNode::DequeueDecoder() noexcept
{
std::lock_guard<SFB::UnfairLock> lock(mQueueLock);
id <SFBPCMDecoding> decoder = nil;
if(!mQueuedDecoders.empty()) {
decoder = mQueuedDecoders.front();
mQueuedDecoders.pop_front();
}
return decoder;
}
id<SFBPCMDecoding> SFB::AudioPlayerNode::CurrentDecoder() const noexcept
{
const auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber();
return decoderState ? decoderState->mDecoder : nil;
}
void SFB::AudioPlayerNode::CancelActiveDecoders(bool cancelAllActive) noexcept
{
auto cancelDecoder = [&](DecoderState * _Nonnull decoderState) {
// If the decoder has already finished decoding, perform the cancelation manually
if(decoderState->IsDecodingComplete()) {
#if DEBUG
os_log_debug(sLog, "Canceling %{public}@ that has completed decoding", decoderState->mDecoder);
#endif /* DEBUG */
// Submit the decoder canceled event
const DecodingEventHeader header{DecodingEventCommand::eCanceled};
if(mDecodeEventRingBuffer.WriteValues(header, decoderState->mSequenceNumber))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoder canceled event");
}
else {
decoderState->SetCanceled();
mDecodingSemaphore.Signal();
}
};
// Cancel all active decoders in sequence
if(auto decoderState = GetActiveDecoderStateWithSmallestSequenceNumber(); decoderState) {
cancelDecoder(decoderState);
if(!cancelAllActive)
return;
decoderState = GetActiveDecoderStateFollowingSequenceNumber(decoderState->mSequenceNumber);
while(decoderState) {
cancelDecoder(decoderState);
decoderState = GetActiveDecoderStateFollowingSequenceNumber(decoderState->mSequenceNumber);
}
}
}
#pragma mark - Decoding
void SFB::AudioPlayerNode::DequeueAndProcessDecoder(bool unmuteNeeded) noexcept
{
dispatch_group_async(mDecodingGroup, mDecodingQueue, ^{
// Dequeue and process the next decoder
if(auto decoder = DequeueDecoder(); decoder) {
// Create the decoder state
DecoderState *decoderState = nullptr;
try {
// When the decoder's processing format and rendering format don't match
// conversion will be performed in DecoderState::DecodeAudio()
decoderState = new DecoderState(decoder, mRenderingFormat, kRingBufferChunkSize);
}
catch(const std::exception& e) {
os_log_error(sLog, "Error creating decoder state: %{public}s", e.what());
NSError *error = [NSError errorWithDomain:SFBAudioPlayerNodeErrorDomain
code:SFBAudioPlayerNodeErrorCodeInternalError
userInfo:@{ NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"An internal error occurred in AudioPlayerNode.", @""),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Error creating DecoderState", @""),
}];
// Submit the error event
const DecodingEventHeader header{DecodingEventCommand::eError};
const auto key = mDispatchKeyCounter.fetch_add(1);
dispatch_queue_set_specific(mEventProcessingQueue, reinterpret_cast<void *>(key), (__bridge_retained void *)error, &release_nserror_f);
if(mDecodeEventRingBuffer.WriteValues(header, key))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoding error event");
return;
}
// Allocate the buffer that is the intermediary between the decoder state and the ring buffer
AVAudioPCMBuffer *buffer = [[AVAudioPCMBuffer alloc] initWithPCMFormat:mRenderingFormat frameCapacity:kRingBufferChunkSize];
if(!buffer) {
os_log_error(sLog, "Error creating AVAudioPCMBuffer with format %{public}@ and frame capacity %d", SFB::StringDescribingAVAudioFormat(mRenderingFormat), kRingBufferChunkSize);
delete decoderState;
NSError *error = [NSError errorWithDomain:SFBAudioPlayerNodeErrorDomain
code:SFBAudioPlayerNodeErrorCodeInternalError
userInfo:@{ NSLocalizedFailureReasonErrorKey: NSLocalizedString(@"An internal error occurred in AudioPlayerNode.", @""),
NSLocalizedRecoverySuggestionErrorKey: NSLocalizedString(@"Error creating AVAudioPCMBuffer", @""),
}];
// Submit the error event
const DecodingEventHeader header{DecodingEventCommand::eError};
const auto key = mDispatchKeyCounter.fetch_add(1);
dispatch_queue_set_specific(mEventProcessingQueue, reinterpret_cast<void *>(key), (__bridge_retained void *)error, &release_nserror_f);
if(mDecodeEventRingBuffer.WriteValues(header, key))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoding error event");
return;
}
// Add the decoder state to the list of active decoders
auto stored = false;
do {
for(auto& atomic_ptr : *mActiveDecoders) {
auto current = atomic_ptr.load(std::memory_order_acquire);
if(current)
continue;
// In essence `mActiveDecoders` is an SPSC queue with `mDecodingQueue` as producer
// and the event processor as consumer, with the stored values used in between production
// and consumption by any number of other threads/queues including the render block.
//
// Slots in `mActiveDecoders` are assigned values in two places: here and the
// event processor. The event processor assigns nullptr to slots before deleting
// the stored value while this code assigns non-null values to slots holding nullptr.
//
// Since `mActiveDecoders[i]` was atomically loaded and has been verified not null,
// it is safe to use store() instead of compare_exchange_strong() because this is the
// only code that could have changed the slot to a non-null value and it is called solely
// from the decoding queue.
// There is the possibility that a non-null value was collected from the slot and the slot
// was assigned nullptr in between load() and the check for null. If this happens the
// assignment could have taken place but didn't.
//
// When `mActiveDecoders` is full this code either needs to wait for a slot to open up or fail.
//
// `mActiveDecoders` may be full when the capacity of mAudioRingBuffer exceeds the
// total number of audio frames for all the decoders in `mActiveDecoders` and audio is not
// being consumed by the render block.
// The default frame capacity for `mAudioRingBuffer` is 16384. With 8 slots available in
// `mActiveDecoders`, the average number of frames a decoder needs to contain for
// all slots to be full is 2048. For audio at 8000 Hz that equates to 0.26 sec and at
// 44,100 Hz 2048 frames equates to 0.05 sec.
// This code elects to wait for a slot to open up instead of failing.
// This isn't a concern in practice since the main use case for this class is music, not
// sequential buffers of 0.05 sec. In normal use it's expected that slots 0 and 1 will
// be the only ones used.
atomic_ptr.store(decoderState, std::memory_order_release);
stored = true;
break;
}
if(!stored) {
os_log_debug(sLog, "No open slots in mActiveDecoders");
struct timespec rqtp = {
.tv_sec = 0,
.tv_nsec = NSEC_PER_SEC / 20
};
nanosleep(&rqtp, nullptr);
}
} while(!stored);
// Clear the mute flags if needed
if(unmuteNeeded)
mFlags.fetch_and(~eFlagIsMuted & ~eFlagMuteRequested, std::memory_order_acq_rel);
os_log_debug(sLog, "Dequeued %{public}@, processing format %{public}@", decoderState->mDecoder, SFB::StringDescribingAVAudioFormat(decoderState->mDecoder.processingFormat));
// Process the decoder until canceled or complete
for(;;) {
// If a seek is pending request a ring buffer reset
if(decoderState->IsSeekPending())
mFlags.fetch_or(eFlagRingBufferNeedsReset, std::memory_order_acq_rel);
// Reset the ring buffer if required, to prevent audible artifacts
if(mFlags.load(std::memory_order_acquire) & eFlagRingBufferNeedsReset) {
mFlags.fetch_and(~eFlagRingBufferNeedsReset, std::memory_order_acq_rel);
// Ensure rendering is muted before performing operations on the ring buffer that aren't thread-safe
if(!(mFlags.load(std::memory_order_acquire) & eFlagIsMuted)) {
if(mNode.engine.isRunning) {
mFlags.fetch_or(eFlagMuteRequested, std::memory_order_acq_rel);
// The render block will clear eFlagMuteRequested and set eFlagIsMuted
while(!(mFlags.load(std::memory_order_acquire) & eFlagIsMuted)) {
auto timeout = mDecodingSemaphore.Wait(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC));
// If the timeout occurred the engine may have stopped since the initial check
// with no subsequent opportunity for the render block to set eFlagIsMuted
if(!timeout && !mNode.engine.isRunning) {
mFlags.fetch_or(eFlagIsMuted, std::memory_order_acq_rel);
mFlags.fetch_and(~eFlagMuteRequested, std::memory_order_acq_rel);
break;
}
}
}
else
mFlags.fetch_or(eFlagIsMuted, std::memory_order_acq_rel);
}
// Perform seek if one is pending
decoderState->PerformSeekIfRequired();
// Reset() is not thread-safe but the render block is outputting silence
mAudioRingBuffer.Reset();
// Clear the mute flag
mFlags.fetch_and(~eFlagIsMuted, std::memory_order_acq_rel);
}
if(decoderState->IsCanceled()) {
os_log_debug(sLog, "Canceling decoding for %{public}@", decoderState->mDecoder);
mFlags.fetch_or(eFlagRingBufferNeedsReset, std::memory_order_acq_rel);
// Submit the decoding canceled event
const DecodingEventHeader header{DecodingEventCommand::eCanceled};
if(mDecodeEventRingBuffer.WriteValues(header, decoderState->mSequenceNumber))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoder canceled event");
return;
}
// Decode and write chunks to the ring buffer
while(mAudioRingBuffer.FramesAvailableToWrite() >= kRingBufferChunkSize) {
if(!decoderState->HasDecodingStarted()) {
os_log_debug(sLog, "Decoding started for %{public}@", decoderState->mDecoder);
decoderState->SetDecodingStarted();
// Submit the decoding started event
const DecodingEventHeader header{DecodingEventCommand::eStarted};
if(mDecodeEventRingBuffer.WriteValues(header, decoderState->mSequenceNumber))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoding started event");
}
// Decode audio into the buffer, converting to the rendering format in the process
if(NSError *error = nil; !decoderState->DecodeAudio(buffer, &error)) {
os_log_error(sLog, "Error decoding audio: %{public}@", error);
if(error) {
// Submit the error event
const DecodingEventHeader header{DecodingEventCommand::eError};
const auto key = mDispatchKeyCounter.fetch_add(1);
dispatch_queue_set_specific(mEventProcessingQueue, reinterpret_cast<void *>(key), (__bridge_retained void *)error, &release_nserror_f);
if(mDecodeEventRingBuffer.WriteValues(header, key))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoding error event");
}
}
// Write the decoded audio to the ring buffer for rendering
const auto framesWritten = mAudioRingBuffer.Write(buffer.audioBufferList, buffer.frameLength);
if(framesWritten != buffer.frameLength)
os_log_error(sLog, "SFB::AudioRingBuffer::Write() failed");
if(decoderState->IsDecodingComplete()) {
// Submit the decoding complete event
const DecodingEventHeader header{DecodingEventCommand::eComplete};
if(mDecodeEventRingBuffer.WriteValues(header, decoderState->mSequenceNumber))
dispatch_group_async_f(mEventProcessingGroup, mEventProcessingQueue, this, process_pending_events_f);
else
os_log_fault(sLog, "Error writing decoding complete event");
os_log_debug(sLog, "Decoding complete for %{public}@", decoderState->mDecoder);
return;
}
}
// Wait for additional space in the ring buffer or for another event signal
mDecodingSemaphore.Wait();
}
}
});
}
#pragma mark - Rendering
OSStatus SFB::AudioPlayerNode::Render(BOOL& isSilence, const AudioTimeStamp& timestamp, AVAudioFrameCount frameCount, AudioBufferList *outputData) noexcept
{
// ========================================
// Pre-rendering
// ========================================
// Mute if requested
if(mFlags.load(std::memory_order_acquire) & eFlagMuteRequested) {
mFlags.fetch_or(eFlagIsMuted, std::memory_order_acq_rel);
mFlags.fetch_and(~eFlagMuteRequested, std::memory_order_acq_rel);
mDecodingSemaphore.Signal();
}
// ========================================
// Rendering
// ========================================
// N.B. The ring buffer must not be read from or written to when eFlagIsMuted is set
// because the decoding queue could be performing non-thread safe operations
// Output silence if not playing or muted
if(const auto flags = mFlags.load(std::memory_order_acquire); !(flags & eFlagIsPlaying) || (flags & eFlagIsMuted)) {
const auto byteCountToZero = mAudioRingBuffer.Format().FrameCountToByteSize(frameCount);
for(UInt32 i = 0; i < outputData->mNumberBuffers; ++i) {
std::memset(outputData->mBuffers[i].mData, 0, byteCountToZero);