@stream-io/noise-cancellation-react-native 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +10 -0
- package/LICENSE +219 -0
- package/README.md +9 -0
- package/android/build.gradle +90 -0
- package/android/gradle.properties +5 -0
- package/android/src/main/AndroidManifest.xml +3 -0
- package/android/src/main/AndroidManifestNew.xml +2 -0
- package/android/src/main/java/io/getstream/rn/noisecancellation/NoiseCancellationAudioProcessingController.kt +15 -0
- package/android/src/main/java/io/getstream/rn/noisecancellation/NoiseCancellationReactNative.kt +26 -0
- package/android/src/main/java/io/getstream/rn/noisecancellation/NoiseCancellationReactNativeModule.kt +55 -0
- package/android/src/main/java/io/getstream/rn/noisecancellation/NoiseCancellationReactNativePackage.kt +17 -0
- package/dist/commonjs/index.js +140 -0
- package/dist/commonjs/index.js.map +1 -0
- package/dist/commonjs/package.json +1 -0
- package/dist/commonjs/types.js +2 -0
- package/dist/commonjs/types.js.map +1 -0
- package/dist/module/index.js +132 -0
- package/dist/module/index.js.map +1 -0
- package/dist/module/package.json +1 -0
- package/dist/module/types.js +2 -0
- package/dist/module/types.js.map +1 -0
- package/dist/typescript/index.d.ts +77 -0
- package/dist/typescript/index.d.ts.map +1 -0
- package/dist/typescript/types.d.ts +27 -0
- package/dist/typescript/types.d.ts.map +1 -0
- package/ios/Classes/AudioFilters.swift +22 -0
- package/ios/Classes/AudioManager.h +19 -0
- package/ios/Classes/AudioManager.m +50 -0
- package/ios/Classes/AudioProcessingAdapter.h +26 -0
- package/ios/Classes/AudioProcessingAdapter.m +105 -0
- package/ios/Classes/NeuralEngineProvider.swift +12 -0
- package/ios/Classes/NoiseCancellationFilter.swift +83 -0
- package/ios/Classes/NoiseCancellationManagerObjc.m +32 -0
- package/ios/Classes/StreamAudioFilterCapturePostProcessingModule.swift +88 -0
- package/ios/Classes/StreamAudioProcessingModule.swift +58 -0
- package/ios/Headers/NoiseCancellationManagerObjc.h +12 -0
- package/ios/NoiseCancellationManager.swift +42 -0
- package/ios/NoiseCancellationReactNative-Bridging-Header.h +2 -0
- package/ios/NoiseCancellationReactNative.mm +23 -0
- package/ios/NoiseCancellationReactNative.swift +45 -0
- package/ios/Utils/DisposableBag/DisposableBag.swift +82 -0
- package/ios/Utils/Queues/LockQueuing.swift +22 -0
- package/ios/Utils/Queues/RecursiveQueue.swift +40 -0
- package/ios/Utils/Queues/UnfairQueue.swift +57 -0
- package/ios/Utils/SerialActor/SerialActor.swift +64 -0
- package/ios/Utils/SerialActor/SerialActorQueue.swift +84 -0
- package/package.json +69 -0
- package/src/index.ts +141 -0
- package/src/types.ts +30 -0
- package/stream-io-noise-cancellation-react-native.podspec +49 -0
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import stream_react_native_webrtc
|
|
3
|
+
|
|
4
|
+
/// A protocol defining requirements for an audio filter capture post-processing module.
|
|
5
|
+
public protocol AudioFilterCapturePostProcessingModule: RTCAudioCustomProcessingDelegate {
|
|
6
|
+
|
|
7
|
+
/// The currently active audio filter.
|
|
8
|
+
var audioFilter: AudioFilter? { get }
|
|
9
|
+
|
|
10
|
+
/// Sets the audio filter for processing captured audio.
|
|
11
|
+
/// - Parameter audioFilter: The audio filter to set.
|
|
12
|
+
func setAudioFilter(_ audioFilter: AudioFilter?)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/// A class that handles post-processing of captured audio streams using custom audio filtering.
|
|
16
|
+
open class StreamAudioFilterCapturePostProcessingModule: NSObject,
|
|
17
|
+
AudioFilterCapturePostProcessingModule, @unchecked Sendable
|
|
18
|
+
{
|
|
19
|
+
|
|
20
|
+
/// The audio filter for processing audio streams.
|
|
21
|
+
public private(set) var audioFilter: AudioFilter?
|
|
22
|
+
|
|
23
|
+
/// The sample rate for audio processing.
|
|
24
|
+
public private(set) var sampleRate: Int = 0
|
|
25
|
+
|
|
26
|
+
/// The number of audio channels for processing.
|
|
27
|
+
public private(set) var channels: Int = 0
|
|
28
|
+
|
|
29
|
+
/// Initializes a new instance of `StreamCapturePostProcessingModule`.
|
|
30
|
+
override public init() {
|
|
31
|
+
super.init()
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// MARK: - Accessors
|
|
35
|
+
|
|
36
|
+
/// Sets the audio filter asynchronously.
|
|
37
|
+
/// - Parameter audioFilter: The audio filter to set for processing.
|
|
38
|
+
open func setAudioFilter(_ audioFilter: AudioFilter?) {
|
|
39
|
+
let oldValue = self.audioFilter
|
|
40
|
+
oldValue?.release()
|
|
41
|
+
|
|
42
|
+
guard oldValue?.id != audioFilter?.id else {
|
|
43
|
+
return
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if let newValue = audioFilter, sampleRate > 0, channels > 0 {
|
|
47
|
+
/// If new filter is set and sample rate & channels are valid, initialize the filter.
|
|
48
|
+
newValue.initialize(sampleRate: sampleRate, channels: channels)
|
|
49
|
+
self.audioFilter = newValue
|
|
50
|
+
} else {
|
|
51
|
+
/// Set audio filter to `nil` if conditions not met.
|
|
52
|
+
self.audioFilter = nil
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// MARK: - RTCAudioCustomProcessingDelegate
|
|
57
|
+
|
|
58
|
+
/// Handles initialization of audio processing.
|
|
59
|
+
/// - Parameters:
|
|
60
|
+
/// - sampleRateHz: The sample rate in Hz.
|
|
61
|
+
/// - channels: The number of audio channels.
|
|
62
|
+
open func audioProcessingInitialize(
|
|
63
|
+
sampleRate sampleRateHz: Int,
|
|
64
|
+
channels: Int
|
|
65
|
+
) {
|
|
66
|
+
sampleRate = sampleRateHz
|
|
67
|
+
self.channels = channels
|
|
68
|
+
audioFilter?.initialize(
|
|
69
|
+
sampleRate: sampleRateHz,
|
|
70
|
+
channels: channels
|
|
71
|
+
)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/// Handles audio processing on received audio buffers.
|
|
75
|
+
/// - Parameter audioBuffer: The incoming audio buffer to process.
|
|
76
|
+
open func audioProcessingProcess(audioBuffer: RTCAudioBuffer) {
|
|
77
|
+
guard let audioFilter else {
|
|
78
|
+
return
|
|
79
|
+
}
|
|
80
|
+
var audioBuffer = audioBuffer
|
|
81
|
+
audioFilter.applyEffect(to: &audioBuffer)
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/// Handles release of audio processing resources.
|
|
85
|
+
open func audioProcessingRelease() {
|
|
86
|
+
audioFilter = nil
|
|
87
|
+
}
|
|
88
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2024 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
import stream_react_native_webrtc
|
|
7
|
+
|
|
8
|
+
/// A protocol defining requirements for an audio processing module that supports audio filters.
|
|
9
|
+
public protocol AudioProcessingModule: RTCAudioProcessingModule, Sendable {
|
|
10
|
+
|
|
11
|
+
/// The currently active audio filter.
|
|
12
|
+
var activeAudioFilter: AudioFilter? { get }
|
|
13
|
+
|
|
14
|
+
/// Sets the audio filter to be used for audio processing.
|
|
15
|
+
/// - Parameter filter: The audio filter to set.
|
|
16
|
+
func setAudioFilter(_ filter: AudioFilter?)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/// A custom audio processing module that integrates with an audio filter for stream processing.
|
|
20
|
+
open class StreamAudioFilterProcessingModule: RTCDefaultAudioProcessingModule,
|
|
21
|
+
AudioProcessingModule, @unchecked Sendable
|
|
22
|
+
{
|
|
23
|
+
|
|
24
|
+
private let _capturePostProcessingDelegate: AudioFilterCapturePostProcessingModule
|
|
25
|
+
|
|
26
|
+
/// Initializes a new instance of `StreamAudioFilterProcessingModule`.
|
|
27
|
+
/// - Parameters:
|
|
28
|
+
/// - config: Optional configuration for audio processing.
|
|
29
|
+
/// - renderPreProcessingDelegate: Optional delegate for render pre-processing.
|
|
30
|
+
public init(
|
|
31
|
+
config: RTCAudioProcessingConfig? = nil,
|
|
32
|
+
capturePostProcessingDelegate: AudioFilterCapturePostProcessingModule =
|
|
33
|
+
StreamAudioFilterCapturePostProcessingModule(),
|
|
34
|
+
renderPreProcessingDelegate: RTCAudioCustomProcessingDelegate? = nil
|
|
35
|
+
) {
|
|
36
|
+
_capturePostProcessingDelegate = capturePostProcessingDelegate
|
|
37
|
+
super.init(
|
|
38
|
+
config: config,
|
|
39
|
+
capturePostProcessingDelegate: capturePostProcessingDelegate,
|
|
40
|
+
renderPreProcessingDelegate: renderPreProcessingDelegate
|
|
41
|
+
)
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
override public func apply(_ config: RTCAudioProcessingConfig) {
|
|
45
|
+
super.apply(config)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/// Retrieves the identifier of the currently active audio filter.
|
|
49
|
+
public var activeAudioFilter: AudioFilter? {
|
|
50
|
+
_capturePostProcessingDelegate.audioFilter
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/// Sets the audio filter for stream processing.
|
|
54
|
+
/// - Parameter filter: The audio filter to set.
|
|
55
|
+
public func setAudioFilter(_ filter: AudioFilter?) {
|
|
56
|
+
_capturePostProcessingDelegate.setAudioFilter(filter)
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import Foundation
|
|
2
|
+
import StreamVideoNoiseCancellation
|
|
3
|
+
import stream_react_native_webrtc
|
|
4
|
+
|
|
5
|
+
@objc
|
|
6
|
+
public final class NoiseCancellationManager: NSObject {
|
|
7
|
+
// MARK: - Singleton Instance
|
|
8
|
+
private static let _sharedInstance = NoiseCancellationManager()
|
|
9
|
+
|
|
10
|
+
// Public static method to get the instance
|
|
11
|
+
@objc
|
|
12
|
+
public static func getInstance() -> NoiseCancellationManager {
|
|
13
|
+
return _sharedInstance
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// MARK: - Properties
|
|
17
|
+
public let processingModule = StreamAudioFilterProcessingModule()
|
|
18
|
+
public var noiseCancellationFilter: NoiseCancellationFilter!
|
|
19
|
+
public var noiseCancellationProcessor: NoiseCancellationProcessor!
|
|
20
|
+
|
|
21
|
+
// Private initializer to enforce the singleton pattern
|
|
22
|
+
private override init() {}
|
|
23
|
+
|
|
24
|
+
// MARK: - Processor Registration
|
|
25
|
+
@objc
|
|
26
|
+
public func registerProcessor() {
|
|
27
|
+
// Initialize the noise cancellation processor and filter
|
|
28
|
+
noiseCancellationProcessor = NoiseCancellationProcessor()
|
|
29
|
+
noiseCancellationFilter = NoiseCancellationFilter(
|
|
30
|
+
name: "noise-cancellation",
|
|
31
|
+
initialize: noiseCancellationProcessor.initialize,
|
|
32
|
+
process: noiseCancellationProcessor.process,
|
|
33
|
+
release: noiseCancellationProcessor.release)
|
|
34
|
+
|
|
35
|
+
AudioManager.sharedInstance().audioProcessingModule = processingModule
|
|
36
|
+
|
|
37
|
+
// Set up the audio processing module with AudioManager
|
|
38
|
+
let options = WebRTCModuleOptions.sharedInstance()
|
|
39
|
+
|
|
40
|
+
options.audioProcessingModule = AudioManager.sharedInstance().audioProcessingModule
|
|
41
|
+
}
|
|
42
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
#import <React/RCTBridgeModule.h>
|
|
2
|
+
|
|
3
|
+
@interface RCT_EXTERN_MODULE(NoiseCancellationReactNative, NSObject)
|
|
4
|
+
|
|
5
|
+
RCT_EXTERN_METHOD(registerProcessor:(RCTPromiseResolveBlock)resolve
|
|
6
|
+
withRejecter:(RCTPromiseRejectBlock)reject)
|
|
7
|
+
|
|
8
|
+
RCT_EXTERN_METHOD(isEnabled:(RCTPromiseResolveBlock)resolve
|
|
9
|
+
withRejecter:(RCTPromiseRejectBlock)reject)
|
|
10
|
+
|
|
11
|
+
RCT_EXTERN_METHOD(setEnabled:(BOOL)enabled
|
|
12
|
+
withResolver:(RCTPromiseResolveBlock)resolve
|
|
13
|
+
withRejecter:(RCTPromiseRejectBlock)reject)
|
|
14
|
+
|
|
15
|
+
RCT_EXTERN_METHOD(deviceSupportsAdvancedAudioProcessing:(RCTPromiseResolveBlock)resolve
|
|
16
|
+
withRejecter:(RCTPromiseRejectBlock)reject)
|
|
17
|
+
|
|
18
|
+
+ (BOOL)requiresMainQueueSetup
|
|
19
|
+
{
|
|
20
|
+
return NO;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
@end
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import StreamVideoNoiseCancellation
|
|
2
|
+
|
|
3
|
+
@objc(NoiseCancellationReactNative)
|
|
4
|
+
class NoiseCancellationReactNative: NSObject {
|
|
5
|
+
|
|
6
|
+
@objc(registerProcessor:withRejecter:)
|
|
7
|
+
func registerProcessor(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
|
|
8
|
+
// Delegate the processor registration logic to the singleton using getInstance()
|
|
9
|
+
NoiseCancellationManager.getInstance().registerProcessor()
|
|
10
|
+
resolve(true)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
@objc(isEnabled:withRejecter:)
|
|
14
|
+
func isEnabled(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
|
|
15
|
+
resolve(NoiseCancellationManager.getInstance().processingModule.activeAudioFilter != nil)
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
@objc(setEnabled:withResolver:withRejecter:)
|
|
19
|
+
func setEnabled(enabled: Bool, resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
|
|
20
|
+
if NoiseCancellationManager.getInstance().noiseCancellationFilter == nil {
|
|
21
|
+
reject(
|
|
22
|
+
"NOISE_CANCELLATION_FILTER_NOT_REGISTERED",
|
|
23
|
+
"Noise cancellation filter not registered",
|
|
24
|
+
nil
|
|
25
|
+
)
|
|
26
|
+
return
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
if enabled {
|
|
30
|
+
NoiseCancellationManager.getInstance().processingModule.setAudioFilter(NoiseCancellationManager.getInstance().noiseCancellationFilter)
|
|
31
|
+
} else {
|
|
32
|
+
if NoiseCancellationManager.getInstance().processingModule.activeAudioFilter != nil {
|
|
33
|
+
NoiseCancellationManager.getInstance().processingModule.setAudioFilter(nil)
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
resolve(true)
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
@objc(deviceSupportsAdvancedAudioProcessing:withRejecter:)
|
|
42
|
+
func deviceSupportsAdvancedAudioProcessing(resolve: RCTPromiseResolveBlock, reject: RCTPromiseRejectBlock) {
|
|
43
|
+
resolve(neuralEngineExists)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2025 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Combine
|
|
6
|
+
import Foundation
|
|
7
|
+
|
|
8
|
+
public final class DisposableBag: @unchecked Sendable {
|
|
9
|
+
|
|
10
|
+
private final class Storage {
|
|
11
|
+
private var storage: [String: AnyCancellable] = [:]
|
|
12
|
+
private let queue = UnfairQueue()
|
|
13
|
+
|
|
14
|
+
deinit {
|
|
15
|
+
storage.values.forEach { $0.cancel() }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
func insert(
|
|
19
|
+
_ cancellable: AnyCancellable,
|
|
20
|
+
with key: String = UUID().uuidString
|
|
21
|
+
) {
|
|
22
|
+
queue.sync {
|
|
23
|
+
storage[key]?.cancel()
|
|
24
|
+
storage[key] = cancellable
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
func remove(_ key: String) {
|
|
29
|
+
queue.sync {
|
|
30
|
+
storage[key]?.cancel()
|
|
31
|
+
storage[key] = nil
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
func removeAll() {
|
|
36
|
+
queue.sync {
|
|
37
|
+
storage.values.forEach { $0.cancel() }
|
|
38
|
+
storage = [:]
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
var isEmpty: Bool { queue.sync { storage.isEmpty } }
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
private let storage: Storage = .init()
|
|
46
|
+
|
|
47
|
+
public init() {}
|
|
48
|
+
|
|
49
|
+
public func insert(
|
|
50
|
+
_ cancellable: AnyCancellable,
|
|
51
|
+
with key: String = UUID().uuidString
|
|
52
|
+
) {
|
|
53
|
+
storage.insert(cancellable, with: key)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public func remove(_ key: String) {
|
|
57
|
+
storage.remove(key)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
public func removeAll() {
|
|
61
|
+
storage.removeAll()
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
public var isEmpty: Bool { storage.isEmpty }
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
extension AnyCancellable {
|
|
68
|
+
public func store(
|
|
69
|
+
in disposableBag: DisposableBag?,
|
|
70
|
+
key: String = UUID().uuidString
|
|
71
|
+
) { disposableBag?.insert(self, with: key) }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
extension Task {
|
|
75
|
+
|
|
76
|
+
func eraseToAnyCancellable() -> AnyCancellable { .init(cancel) }
|
|
77
|
+
|
|
78
|
+
public func store(
|
|
79
|
+
in disposableBag: DisposableBag,
|
|
80
|
+
key: String = UUID().uuidString
|
|
81
|
+
) { disposableBag.insert(.init(cancel), with: key) }
|
|
82
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2025 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
|
|
7
|
+
/// A protocol defining a lock-based synchronization interface.
|
|
8
|
+
///
|
|
9
|
+
/// Types conforming to `LockQueuing` provide thread-safe access to resources
|
|
10
|
+
/// by executing blocks of code within a lock, ensuring mutual exclusion.
|
|
11
|
+
protocol LockQueuing: Sendable {
|
|
12
|
+
|
|
13
|
+
/// Executes a block within a lock, ensuring exclusive access.
|
|
14
|
+
///
|
|
15
|
+
/// This method should guarantee that only one thread can execute the
|
|
16
|
+
/// provided block at a time, using the underlying lock mechanism.
|
|
17
|
+
///
|
|
18
|
+
/// - Parameter block: The block of code to execute safely within the lock.
|
|
19
|
+
/// - Returns: The value returned by the block, if any.
|
|
20
|
+
/// - Throws: Rethrows any errors thrown by the block.
|
|
21
|
+
func sync<T>(_ block: () throws -> T) rethrows -> T
|
|
22
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2025 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
|
|
7
|
+
/// A synchronization utility implementing a recursive locking mechanism.
|
|
8
|
+
///
|
|
9
|
+
/// This class provides a way to synchronize access to resources using `NSRecursiveLock`,
|
|
10
|
+
/// which allows the same thread to acquire the lock multiple times without deadlocking.
|
|
11
|
+
/// This is useful in recursive or reentrant code where multiple methods that may call each other
|
|
12
|
+
/// need to access a shared resource.
|
|
13
|
+
///
|
|
14
|
+
/// `NSRecursiveLock` is an Objective-C-based recursive lock that provides thread safety in situations
|
|
15
|
+
/// where the same thread needs to acquire the lock more than once. Unlike `os_unfair_lock`, which is non-recursive
|
|
16
|
+
/// and prioritizes performance, `NSRecursiveLock` ensures that the same thread can enter critical sections
|
|
17
|
+
/// repeatedly, avoiding deadlock in reentrant code scenarios.
|
|
18
|
+
///
|
|
19
|
+
/// While `NSRecursiveLock` has more overhead than `os_unfair_lock`, it is ideal for more complex code flows
|
|
20
|
+
/// where reentrancy or recursive method calls require safe locking. This makes it a better fit than
|
|
21
|
+
/// `os_unfair_lock` when you need the flexibility to enter the lock multiple times on the same thread.
|
|
22
|
+
public final class RecursiveQueue: LockQueuing, @unchecked Sendable {
|
|
23
|
+
|
|
24
|
+
/// The recursive lock instance.
|
|
25
|
+
private let lock = NSRecursiveLock()
|
|
26
|
+
|
|
27
|
+
/// Initializes a new instance of `RecursiveQueue`.
|
|
28
|
+
public init() {}
|
|
29
|
+
|
|
30
|
+
/// Executes a block with mutual exclusion via a recursive lock.
|
|
31
|
+
///
|
|
32
|
+
/// - Parameter block: The block of code to execute safely under the lock.
|
|
33
|
+
/// - Returns: The value returned by the block, if any.
|
|
34
|
+
/// - Throws: Rethrows any errors thrown by the block.
|
|
35
|
+
public func sync<T>(_ block: () throws -> T) rethrows -> T {
|
|
36
|
+
lock.lock()
|
|
37
|
+
defer { lock.unlock() }
|
|
38
|
+
return try block()
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2025 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
|
|
7
|
+
/// A synchronization utility implementing an unfair locking mechanism.
|
|
8
|
+
///
|
|
9
|
+
/// This class provides a way to synchronize access to resources using `os_unfair_lock`,
|
|
10
|
+
/// which offers a fast and efficient locking mechanism but can lead to priority inversion.
|
|
11
|
+
///
|
|
12
|
+
/// `os_unfair_lock` stands out for its direct approach to synchronization, providing high-performance,
|
|
13
|
+
/// low-level locking that is especially beneficial when you need to protect small sections of code or data
|
|
14
|
+
/// swiftly. It operates with minimal overhead, avoiding the complexities of context switching or thread management,
|
|
15
|
+
/// which is a stark contrast to DispatchQueue.
|
|
16
|
+
///
|
|
17
|
+
/// When using a DispatchQueue, there is inherent overhead because it schedules tasks and potentially shifts
|
|
18
|
+
/// execution onto a specific thread, depending on the queue's configuration (main or background). This can
|
|
19
|
+
/// introduce delays as tasks are queued and executed according to the system's scheduling algorithms,
|
|
20
|
+
/// which might not be as immediate as the direct locking mechanism provided by `os_unfair_lock`.
|
|
21
|
+
///
|
|
22
|
+
/// The lock's efficiency and speed are particularly advantageous in high-performance contexts where the
|
|
23
|
+
/// additional overhead of dispatching tasks and managing thread execution in a DispatchQueue could result
|
|
24
|
+
/// in unnecessary latency, making `os_unfair_lock` the superior choice for scenarios where rapid, lightweight
|
|
25
|
+
/// synchronization is paramount.
|
|
26
|
+
public final class UnfairQueue: LockQueuing, @unchecked Sendable {
|
|
27
|
+
|
|
28
|
+
/// The unfair lock variable, managed as an unsafe mutable pointer to `os_unfair_lock`.
|
|
29
|
+
private let lock: os_unfair_lock_t
|
|
30
|
+
|
|
31
|
+
/// Initializes a new instance of `UnfairQueue`.
|
|
32
|
+
///
|
|
33
|
+
/// It allocates memory for an `os_unfair_lock` and initializes it.
|
|
34
|
+
public init() {
|
|
35
|
+
lock = UnsafeMutablePointer<os_unfair_lock>.allocate(capacity: 1)
|
|
36
|
+
lock.initialize(to: os_unfair_lock())
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/// Deinitializes the instance, deallocating the unfair lock.
|
|
40
|
+
deinit {
|
|
41
|
+
lock.deallocate()
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Executes a block of code, ensuring mutual exclusion via an unfair lock.
|
|
45
|
+
///
|
|
46
|
+
/// The method locks before the block executes and unlocks after the block completes.
|
|
47
|
+
/// It's designed to be exception-safe, unlocking even if an error is thrown within the block.
|
|
48
|
+
///
|
|
49
|
+
/// - Parameter block: The block of code to execute safely under the lock.
|
|
50
|
+
/// - Returns: The value returned by the block, if any.
|
|
51
|
+
/// - Throws: Rethrows any errors that are thrown by the block.
|
|
52
|
+
public func sync<T>(_ block: () throws -> T) rethrows -> T {
|
|
53
|
+
os_unfair_lock_lock(lock)
|
|
54
|
+
defer { os_unfair_lock_unlock(lock) }
|
|
55
|
+
return try block()
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2025 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
|
|
7
|
+
actor SerialActor {
|
|
8
|
+
/// Declare a private variable to store the previous task.
|
|
9
|
+
private var previousTask: Task<Void, Error>?
|
|
10
|
+
private let disposableBag = DisposableBag()
|
|
11
|
+
|
|
12
|
+
deinit {
|
|
13
|
+
disposableBag.removeAll()
|
|
14
|
+
previousTask = nil
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
nonisolated func cancel() {
|
|
18
|
+
disposableBag.removeAll()
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/// Executes a block of code asynchronously in a serial manner.
|
|
22
|
+
///
|
|
23
|
+
/// This method ensures that only one operation runs at a time within this actor.
|
|
24
|
+
/// It waits for the previous operation to finish before starting the next one.
|
|
25
|
+
///
|
|
26
|
+
/// - Parameters:
|
|
27
|
+
/// - block: A block of code to execute asynchronously. The block is declared as
|
|
28
|
+
/// `Sendable`, meaning it can be safely sent across threads, and `escaping`,
|
|
29
|
+
/// meaning it can be executed asynchronously. The block can return any value
|
|
30
|
+
/// and can throw errors.
|
|
31
|
+
///
|
|
32
|
+
/// - Throws: Any error thrown by the provided block.
|
|
33
|
+
/// - Returns: The value returned by the provided block.
|
|
34
|
+
func execute<T: Sendable>(_ block: @Sendable @escaping () async throws -> T) async throws -> T {
|
|
35
|
+
/// Create a new task that runs the provided block of code within a closure.
|
|
36
|
+
/// This closure captures the `previousTask` variable by value.
|
|
37
|
+
let task = Task<T, Error> { [previousTask] in
|
|
38
|
+
/// Wait for the previous task to finish by awaiting its result.
|
|
39
|
+
/// If the previous task is nil, this line does nothing.
|
|
40
|
+
_ = await previousTask?.result
|
|
41
|
+
|
|
42
|
+
try Task.checkCancellation()
|
|
43
|
+
|
|
44
|
+
/// Execute the provided block of code and re-throw any errors.
|
|
45
|
+
return try await block()
|
|
46
|
+
}
|
|
47
|
+
task.store(in: disposableBag)
|
|
48
|
+
|
|
49
|
+
/// Create a void task that we can store for synchronization
|
|
50
|
+
let voidTask = Task<Void, Error> {
|
|
51
|
+
_ = try await task.value
|
|
52
|
+
}
|
|
53
|
+
voidTask.store(in: disposableBag)
|
|
54
|
+
|
|
55
|
+
/// Update the `previousTask` variable to point to the void task.
|
|
56
|
+
previousTask = voidTask
|
|
57
|
+
|
|
58
|
+
try Task.checkCancellation()
|
|
59
|
+
|
|
60
|
+
/// Wait for the newly created task to finish by awaiting its value.
|
|
61
|
+
/// This will re-throw any errors thrown by the block.
|
|
62
|
+
return try await task.value
|
|
63
|
+
}
|
|
64
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
//
|
|
2
|
+
// Copyright © 2025 Stream.io Inc. All rights reserved.
|
|
3
|
+
//
|
|
4
|
+
|
|
5
|
+
import Foundation
|
|
6
|
+
|
|
7
|
+
/// A thread-safe utility for executing asynchronous tasks serially.
|
|
8
|
+
///
|
|
9
|
+
/// `SerialActorQueue` ensures that tasks submitted to it are executed one at
|
|
10
|
+
/// a time, in the order they are received. This is particularly useful for
|
|
11
|
+
/// managing shared resources or maintaining a predictable task execution order.
|
|
12
|
+
public final class SerialActorQueue: Sendable {
|
|
13
|
+
|
|
14
|
+
/// The internal serial actor responsible for task execution.
|
|
15
|
+
/// This actor ensures tasks are run serially.
|
|
16
|
+
private let actor = SerialActor()
|
|
17
|
+
|
|
18
|
+
/// A disposableBag to keep track of the nested tasks. On deallocation allows us to cancel them
|
|
19
|
+
/// and stop any execution.
|
|
20
|
+
private let disposableBag = DisposableBag()
|
|
21
|
+
|
|
22
|
+
/// Initializes a new `SerialActorQueue` instance.
|
|
23
|
+
public init() {}
|
|
24
|
+
|
|
25
|
+
deinit {
|
|
26
|
+
actor.cancel()
|
|
27
|
+
disposableBag.removeAll()
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
public func cancelAll() {
|
|
31
|
+
actor.cancel()
|
|
32
|
+
disposableBag.removeAll()
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/// Submits an asynchronous task to be executed serially.
|
|
36
|
+
///
|
|
37
|
+
/// - Parameters:
|
|
38
|
+
/// - file: The file from which the method is called. Defaults to `#file`.
|
|
39
|
+
/// - functionName: The function name from which the method is called. Defaults to `#function`.
|
|
40
|
+
/// - line: The line number from which the method is called. Defaults to `#line`.
|
|
41
|
+
/// - block: The task to execute. This block must be asynchronous and throwable.
|
|
42
|
+
///
|
|
43
|
+
/// This method logs any errors encountered during the execution of the task.
|
|
44
|
+
public func async(
|
|
45
|
+
file: StaticString = #file,
|
|
46
|
+
functionName: StaticString = #function,
|
|
47
|
+
line: UInt = #line,
|
|
48
|
+
_ block: @Sendable @escaping () async throws -> Void
|
|
49
|
+
) {
|
|
50
|
+
Task {
|
|
51
|
+
do {
|
|
52
|
+
try Task.checkCancellation()
|
|
53
|
+
// Execute the task serially via the actor.
|
|
54
|
+
try await actor.execute(block)
|
|
55
|
+
} catch {
|
|
56
|
+
if error is CancellationError { /* No-op */ }
|
|
57
|
+
else {
|
|
58
|
+
// Log any errors encountered during task execution.
|
|
59
|
+
// log.error(
|
|
60
|
+
// error,
|
|
61
|
+
// functionName: functionName,
|
|
62
|
+
// fileName: file,
|
|
63
|
+
// lineNumber: line
|
|
64
|
+
// )
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
}.store(in: disposableBag)
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/// Submits an asynchronous task to be executed serially and waits for it to complete.
|
|
71
|
+
///
|
|
72
|
+
/// - Parameter block: The task to execute. This block must be asynchronous and throwable.
|
|
73
|
+
/// - Throws: Rethrows any error encountered during the execution of the task.
|
|
74
|
+
/// - Returns: The value returned by the provided block.
|
|
75
|
+
///
|
|
76
|
+
/// Use this method when you need to wait for the completion of the submitted task
|
|
77
|
+
/// and handle its results or errors immediately.
|
|
78
|
+
public func sync<T: Sendable>(
|
|
79
|
+
_ block: @Sendable @escaping () async throws -> T
|
|
80
|
+
) async throws -> T {
|
|
81
|
+
// Execute the task serially and wait for its completion.
|
|
82
|
+
try await actor.execute(block)
|
|
83
|
+
}
|
|
84
|
+
}
|