From 49d3072270f31d597e25ee647669d61d71671627 Mon Sep 17 00:00:00 2001 From: Hiroshi Horie <548776+hiroshihorie@users.noreply.github.com> Date: Tue, 24 Nov 2026 17:47:22 +0800 Subject: [PATCH] Report runtime audio processing changes in the audio track features LocalAudioTrack.setAudioProcessingOptions(_:) changes echo cancellation, noise suppression and auto gain control at runtime, but the features sent to the server were still derived from the immutable captureOptions, and LocalTrackPublication only re-sent them on set(track:) and on Krisp delegate changes. The server kept advertising the publish-time features. The track now records the options once WebRTC accepts them (applied or stored), on the RTC executor so concurrent calls are recorded in the order they were applied, and derives its features from them. A rejected call throws before anything is recorded, so it leaves the features unchanged. The publication is notified through a new internal track delegate protocol and re-sends the features when they differ from the last ones sent. A runtime change made before publishing is picked up by the AddTrackRequest and the first feature update. Co-Authored-By: Claude Opus 5.5 --- .changes/runtime-audio-processing-features | 1 + Sources/LiveKit/Protocols/TrackDelegate.swift | 5 ++ .../LiveKit/Track/Local/LocalAudioTrack.swift | 30 ++++++- .../LocalTrackPublication.swift | 8 ++ .../Types/AudioProcessingOptions.swift | 9 ++ .../Types/Options/AudioCaptureOptions.swift | 8 -- .../LiveKitCoreTests/PublishTrackTests.swift | 32 ++++++++ .../Track/LocalAudioTrackFeaturesTests.swift | 82 +++++++++++++++++++ 8 files changed, 164 insertions(+), 11 deletions(-) create mode 100644 .changes/runtime-audio-processing-features create mode 100644 Tests/LiveKitCoreTests/Track/LocalAudioTrackFeaturesTests.swift diff --git a/.changes/runtime-audio-processing-features b/.changes/runtime-audio-processing-features new file mode 100644 index 000000000..179c295a2 --- /dev/null +++ b/.changes/runtime-audio-processing-features @@ -0,0 +1 @@ +patch type="fixed" "Fix the audio features reported to the server not following `LocalAudioTrack.setAudioProcessingOptions(_:)`. After a successful runtime change the track now reports echo cancellation, noise suppression and auto gain control from the new options, and re-sends them when published" diff --git a/Sources/LiveKit/Protocols/TrackDelegate.swift b/Sources/LiveKit/Protocols/TrackDelegate.swift index 8a68f9f9a..2bd715783 100644 --- a/Sources/LiveKit/Protocols/TrackDelegate.swift +++ b/Sources/LiveKit/Protocols/TrackDelegate.swift @@ -35,3 +35,8 @@ protocol TrackDelegateInternal: TrackDelegate { /// Used to report track state mutation to TrackPublication if attached. func track(_ track: Track, didMutateState newState: Track.State, oldState: Track.State) } + +protocol LocalAudioTrackDelegateInternal: TrackDelegate { + /// Notify LocalTrackPublication that the audio features it reports to the server may have changed. + func localAudioTrackDidUpdateAudioFeatures(_ track: LocalAudioTrack) +} diff --git a/Sources/LiveKit/Track/Local/LocalAudioTrack.swift b/Sources/LiveKit/Track/Local/LocalAudioTrack.swift index 840ecc2f4..237c9b7bb 100644 --- a/Sources/LiveKit/Track/Local/LocalAudioTrack.swift +++ b/Sources/LiveKit/Track/Local/LocalAudioTrack.swift @@ -32,6 +32,9 @@ public class LocalAudioTrack: Track, LocalTrackProtocol, AudioTrackProtocol, @un let _frameWatcherState = StateSync(FrameWatcherState()) + /// The options last accepted by ``setAudioProcessingOptions(_:)``, or `nil` before any runtime change. + let runtimeAudioProcessing = StateSync(nil) + init(name: String, source: Track.Source, track: RTCMediaTrack, @@ -117,6 +120,9 @@ public class LocalAudioTrack: Track, LocalTrackProtocol, AudioTrackProtocol, @un /// the active sender. Effective APM configuration is shared by the WebRTC voice engine, /// so conflicting updates from multiple local audio tracks are last-writer-wins. /// + /// Once the options are accepted, the echo cancellation, noise suppression and auto gain + /// control features this track reports to the server follow them instead of ``captureOptions``. + /// /// - Returns: Whether the options were applied immediately or stored for reapplication. /// - Throws: ``AudioProcessingOptionsError`` when the options cannot be applied. /// - Note: Blocks the calling thread until WebRTC's signaling thread applies the options. @@ -129,8 +135,12 @@ public class LocalAudioTrack: Track, LocalTrackProtocol, AudioTrackProtocol, @un message: "Media track is not an audio track", ) } - return try audioTrack.setAudioProcessingOptions(options.toRTCType()).toLKType() + let result = try audioTrack.setAudioProcessingOptions(options.toRTCType()).toLKType() + // Recorded on the RTC executor, so concurrent calls are recorded in the order WebRTC applied them. + runtimeAudioProcessing.mutate { $0 = options } + return result } + notifyAudioFeaturesMayHaveChanged() // Track-level options reach the ADM through the sender, so inform the // session observer here to keep the session mode in sync with the // requested voice processing implementation. @@ -166,15 +176,29 @@ public class LocalAudioTrack: Track, LocalTrackProtocol, AudioTrackProtocol, @un } extension LocalAudioTrack { - /// Everything the server is told about this track: capture processing, publish options and Krisp. + /// The voice processing options this track asks for: the last options accepted at runtime, + /// otherwise the ones it was captured with. + var audioProcessing: AudioProcessingOptions { + runtimeAudioProcessing.copy() ?? captureOptions.audioProcessing + } + + /// Everything the server is told about this track: voice processing, publish options and Krisp. func features(publishOptions: AudioPublishOptions?) -> Set { - var features = captureOptions.toFeatures() + var features = audioProcessing.toFeatures() features.formUnion(publishOptions?.toFeatures() ?? []) if AudioManager.shared.capturePostProcessingDelegate?.audioProcessingName == kLiveKitKrispAudioProcessorName { features.insert(.tfEnhancedNoiseCancellation) } return features } + + /// Asks the publication, if any, to re-send ``features(publishOptions:)``. It sends only when they changed. + func notifyAudioFeaturesMayHaveChanged() { + delegates.notify(label: { "track.didUpdateAudioFeatures" }) { [weak self] delegate in + guard let self, let delegate = delegate as? LocalAudioTrackDelegateInternal else { return } + delegate.localAudioTrackDidUpdateAudioFeatures(self) + } + } } public extension LocalAudioTrack { diff --git a/Sources/LiveKit/TrackPublications/LocalTrackPublication.swift b/Sources/LiveKit/TrackPublications/LocalTrackPublication.swift index 4b3d69703..c04f175c2 100644 --- a/Sources/LiveKit/TrackPublications/LocalTrackPublication.swift +++ b/Sources/LiveKit/TrackPublications/LocalTrackPublication.swift @@ -93,6 +93,14 @@ extension LocalTrackPublication { } } +extension LocalTrackPublication: LocalAudioTrackDelegateInternal { + func localAudioTrackDidUpdateAudioFeatures(_ track: LocalAudioTrack) { + // A replaced track may still deliver a queued notification. + guard self.track === track else { return } + sendAudioTrackFeatures() + } +} + extension LocalTrackPublication: VideoCapturerDelegate { public func capturer(_: VideoCapturer, didUpdate _: Dimensions?) { Task.detached { diff --git a/Sources/LiveKit/Types/AudioProcessingOptions.swift b/Sources/LiveKit/Types/AudioProcessingOptions.swift index 50b63d36d..e0cf3a7f4 100644 --- a/Sources/LiveKit/Types/AudioProcessingOptions.swift +++ b/Sources/LiveKit/Types/AudioProcessingOptions.swift @@ -86,6 +86,15 @@ extension AudioProcessingOptions { (echoCancellation && echoCancellationMode != .software) || (noiseSuppression && noiseSuppressionMode != .software) } + + /// The audio track features these options report to the server. + func toFeatures() -> Set { + Set([ + echoCancellation ? .tfEchoCancellation : nil, + noiseSuppression ? .tfNoiseSuppression : nil, + autoGainControl ? .tfAutoGainControl : nil, + ].compactMap(\.self)) + } } /// The caller's request for one audio processing component: enabled flag plus diff --git a/Sources/LiveKit/Types/Options/AudioCaptureOptions.swift b/Sources/LiveKit/Types/Options/AudioCaptureOptions.swift index d83e6128a..c38023873 100644 --- a/Sources/LiveKit/Types/Options/AudioCaptureOptions.swift +++ b/Sources/LiveKit/Types/Options/AudioCaptureOptions.swift @@ -135,12 +135,4 @@ extension AudioCaptureOptions { highpassFilterMode: highpassFilterMode, ) } - - func toFeatures() -> Set { - Set([ - echoCancellation ? .tfEchoCancellation : nil, - noiseSuppression ? .tfNoiseSuppression : nil, - autoGainControl ? .tfAutoGainControl : nil, - ].compactMap(\.self)) - } } diff --git a/Tests/LiveKitCoreTests/PublishTrackTests.swift b/Tests/LiveKitCoreTests/PublishTrackTests.swift index b66225246..64284a3e2 100644 --- a/Tests/LiveKitCoreTests/PublishTrackTests.swift +++ b/Tests/LiveKitCoreTests/PublishTrackTests.swift @@ -73,6 +73,38 @@ struct PublishTrackTests { } } + /// The server keeps the features it was last sent, so a runtime processing change has to re-send them. + @Test func runtimeAudioProcessingChangeUpdatesFeatures() async throws { + try await TestEnvironment.withRooms([RoomTestingOptions(canPublish: true), RoomTestingOptions(canSubscribe: true)]) { rooms in + let publisher = rooms[0].localParticipant + let publisherIdentity = try #require(publisher.identity) + let remote = try #require(rooms[1].remoteParticipants[publisherIdentity]) + + let track = TestAudioTrack() + let publication = try await publisher.publish(audioTrack: track) + + let voiceFeatures: Set = [.tfEchoCancellation, .tfNoiseSuppression, .tfAutoGainControl] + var remoteFeatures: Set = [] + + var deadline = Date().addingTimeInterval(15) + while !remoteFeatures.isSuperset(of: voiceFeatures), Date() < deadline { + try await Task.sleep(nanoseconds: 100_000_000) + remoteFeatures = Set(remote.trackPublications[publication.sid]?._state.latestInfo?.audioFeatures ?? []) + } + #expect(remoteFeatures.isSuperset(of: voiceFeatures)) + + try track.setAudioProcessingOptions(.noProcessing) + + deadline = Date().addingTimeInterval(15) + while !remoteFeatures.isDisjoint(with: voiceFeatures), Date() < deadline { + try await Task.sleep(nanoseconds: 100_000_000) + remoteFeatures = Set(remote.trackPublications[publication.sid]?._state.latestInfo?.audioFeatures ?? []) + } + #expect(publication._state.audioTrackFeatures?.isDisjoint(with: voiceFeatures) == true) + #expect(remoteFeatures.isDisjoint(with: voiceFeatures)) + } + } + @Test func publishWithoutPermissions() async throws { try await TestEnvironment.withRoom(RoomTestingOptions(canPublish: false)) { room in let audioTrack = await LocalAudioTrack.createTrack() diff --git a/Tests/LiveKitCoreTests/Track/LocalAudioTrackFeaturesTests.swift b/Tests/LiveKitCoreTests/Track/LocalAudioTrackFeaturesTests.swift new file mode 100644 index 000000000..c080a6e4a --- /dev/null +++ b/Tests/LiveKitCoreTests/Track/LocalAudioTrackFeaturesTests.swift @@ -0,0 +1,82 @@ +/* + * Copyright 2026 LiveKit + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation +@testable import LiveKit +import Testing +#if canImport(LiveKitTestSupport) +import LiveKitTestSupport +#endif + +@Suite(.serialized, .tags(.media, .audio)) +struct LocalAudioTrackFeaturesTests { + private static let voiceFeatures: Set = [ + .tfEchoCancellation, .tfNoiseSuppression, .tfAutoGainControl, + ] + + @Test func processingOptionsMapToFeatures() { + #expect(AudioProcessingOptions().toFeatures() == Self.voiceFeatures) + #expect(AudioProcessingOptions.noProcessing.toFeatures().isEmpty) + + let echoCancellationOnly = AudioProcessingOptions( + echoCancellation: true, + autoGainControl: false, + noiseSuppression: false, + highpassFilter: true, + echoCancellationMode: .software, + ) + #expect(echoCancellationOnly.toFeatures() == [.tfEchoCancellation]) + } + + @Test func featuresFollowCaptureOptionsUntilRuntimeChange() { + let track = TestAudioTrack() + #expect(track.features(publishOptions: nil) == Self.voiceFeatures) + #expect(track.audioProcessing == track.captureOptions.audioProcessing) + + track.runtimeAudioProcessing.mutate { $0 = .noProcessing } + + #expect(track.audioProcessing == .noProcessing) + #expect(track.features(publishOptions: nil).isEmpty) + #expect(track.features(publishOptions: AudioPublishOptions(dtx: false)) == [.tfNoDtx]) + } + + @Test func acceptedRuntimeOptionsUpdateFeaturesAndNotifyPublication() async throws { + let track = TestAudioTrack() + let delegate = FeaturesDelegate() + track.add(delegate: delegate) + + let result = try track.setAudioProcessingOptions(.noProcessing) + #expect(result == .applied || result == .stored) + #expect(track.audioProcessing == .noProcessing) + #expect(track.features(publishOptions: nil).isEmpty) + + let deadline = Date().addingTimeInterval(5) + while delegate.updateCount == 0, Date() < deadline { + try await Task.sleep(nanoseconds: 10_000_000) + } + #expect(delegate.updateCount == 1) + } +} + +private final class FeaturesDelegate: NSObject, LocalAudioTrackDelegateInternal, Sendable { + private let updates = StateSync(0) + + var updateCount: Int { updates.copy() } + + func localAudioTrackDidUpdateAudioFeatures(_: LocalAudioTrack) { + updates.mutate { $0 += 1 } + } +}