Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changes/runtime-audio-processing-features
Original file line number Diff line number Diff line change
@@ -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"
5 changes: 5 additions & 0 deletions Sources/LiveKit/Protocols/TrackDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
30 changes: 27 additions & 3 deletions Sources/LiveKit/Track/Local/LocalAudioTrack.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<AudioProcessingOptions?>(nil)

init(name: String,
source: Track.Source,
track: RTCMediaTrack,
Expand Down Expand Up @@ -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.
Expand All @@ -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.
Expand Down Expand Up @@ -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<Livekit_AudioTrackFeature> {
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 {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 9 additions & 0 deletions Sources/LiveKit/Types/AudioProcessingOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Livekit_AudioTrackFeature> {
Set([
echoCancellation ? .tfEchoCancellation : nil,
noiseSuppression ? .tfNoiseSuppression : nil,
autoGainControl ? .tfAutoGainControl : nil,
].compactMap(\.self))
}
}

/// The caller's request for one audio processing component: enabled flag plus
Expand Down
8 changes: 0 additions & 8 deletions Sources/LiveKit/Types/Options/AudioCaptureOptions.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,12 +135,4 @@ extension AudioCaptureOptions {
highpassFilterMode: highpassFilterMode,
)
}

func toFeatures() -> Set<Livekit_AudioTrackFeature> {
Set([
echoCancellation ? .tfEchoCancellation : nil,
noiseSuppression ? .tfNoiseSuppression : nil,
autoGainControl ? .tfAutoGainControl : nil,
].compactMap(\.self))
}
}
32 changes: 32 additions & 0 deletions Tests/LiveKitCoreTests/PublishTrackTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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<Livekit_AudioTrackFeature> = [.tfEchoCancellation, .tfNoiseSuppression, .tfAutoGainControl]
var remoteFeatures: Set<Livekit_AudioTrackFeature> = []

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()
Expand Down
82 changes: 82 additions & 0 deletions Tests/LiveKitCoreTests/Track/LocalAudioTrackFeaturesTests.swift
Original file line number Diff line number Diff line change
@@ -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<Livekit_AudioTrackFeature> = [
.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 }
}
}
Loading