fix(calling): organizer mute, device selection, 720p level, and share scale (#82)
Co-authored-by: Gernot Breidenstein <gernot.breidenstein@outlook.de>
@@ -1202,6 +1202,7 @@ impl AppState {
1202
1202
BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),
1203
1203
BackendEvent::Calls(launcher) => {
1204
1204
launcher.set_default_camera(self.call_camera.clone());
1205
launcher.set_default_mic(self.call_mic);
1205
1206
self.call_launcher = Some(launcher);
1206
1207
self.load_own_time_zone(cx);
1207
1208
}
@@ -1202,6 +1202,7 @@ impl AppState {1202
BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),1202
BackendEvent::LiveRetry(retry) => self.live_retry = Some(retry),1203
BackendEvent::Calls(launcher) => {1203
BackendEvent::Calls(launcher) => {1204
launcher.set_default_camera(self.call_camera.clone());1204
launcher.set_default_camera(self.call_camera.clone());1205
launcher.set_default_mic(self.call_mic);1205
self.call_launcher = Some(launcher);1206
self.call_launcher = Some(launcher);1206
self.load_own_time_zone(cx);1207
self.load_own_time_zone(cx);1207
}1208
}@@ -715,6 +715,9 @@ impl AppState {
715
715
pub fn set_call_mic(&mut self, settings: MicSettings, cx: &mut Context<Self>) {
716
716
self.call_mic = settings;
717
717
save_mic(&self.store, settings);
718
if let Some(launcher) = &self.call_launcher {
719
launcher.set_default_mic(settings);
720
}
718
721
self.send_call_command(CallCommand::SetMicSettings(settings));
719
722
cx.notify();
720
723
}
@@ -715,6 +715,9 @@ impl AppState {715
pub fn set_call_mic(&mut self, settings: MicSettings, cx: &mut Context<Self>) {715
pub fn set_call_mic(&mut self, settings: MicSettings, cx: &mut Context<Self>) {716
self.call_mic = settings;716
self.call_mic = settings;717
save_mic(&self.store, settings);717
save_mic(&self.store, settings);718
if let Some(launcher) = &self.call_launcher {719
launcher.set_default_mic(settings);720
}718
self.send_call_command(CallCommand::SetMicSettings(settings));721
self.send_call_command(CallCommand::SetMicSettings(settings));719
cx.notify();722
cx.notify();720
}723
}@@ -8,7 +8,7 @@ use calling::meeting::{LiveMeeting, fetch_live_meeting};
8
8
use calling::{
9
9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,
10
10
CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,
11
MeetingTarget, call_channel,
11
MeetingTarget, MicSettings, call_channel,
12
12
};
13
13
use session::{Session, SessionConfig, Transport};
14
14
@@ -27,6 +27,7 @@ const READY_WAIT: Duration = Duration::from_secs(30);
27
27
pub struct CallLauncher {
28
28
engine: watch::Sender<Option<CallEngine>>,
29
29
default_camera: Mutex<DeviceChoice>,
30
default_mic: Mutex<MicSettings>,
30
31
}
31
32
32
33
impl CallLauncher {
@@ -38,6 +39,7 @@ impl CallLauncher {
38
39
let launcher = Arc::new(CallLauncher {
39
40
engine: watch::channel(None).0,
40
41
default_camera: Mutex::new(DeviceChoice::SystemDefault),
42
default_mic: Mutex::new(MicSettings::default()),
41
43
});
42
44
let running = launcher.clone();
43
45
crate::runtime::handle().spawn(async move {
@@ -49,6 +51,7 @@ impl CallLauncher {
49
51
.await;
50
52
crate::diagnostics::record("calls: engine ready, registered with the registrar");
51
53
engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());
54
engine.set_default_mic(*running.default_mic.lock().expect("mic lock"));
52
55
running.engine.send_replace(Some(engine));
53
56
while let Some(event) = events.recv().await {
54
57
on_event(event);
@@ -79,6 +82,13 @@ impl CallLauncher {
79
82
}
80
83
}
81
84
85
pub fn set_default_mic(&self, mic: MicSettings) {
86
*self.default_mic.lock().expect("mic lock") = mic;
87
if let Some(engine) = self.engine() {
88
engine.set_default_mic(mic);
89
}
90
}
91
82
92
pub fn start_call(&self, spec: CallSpec) -> CallHandle {
83
93
match self.engine() {
84
94
Some(engine) => engine.start_call(spec),
@@ -8,7 +8,7 @@ use calling::meeting::{LiveMeeting, fetch_live_meeting};8
use calling::{8
use calling::{9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,9
AcceptMode, BackgroundCache, CallControl, CallEngine, CallHandle, CallSpec, CallState,10
CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,10
CallUpdate, DefaultBackground, DeviceChoice, EndReason, EngineConfig, EngineEvent,11
MeetingTarget, call_channel,11
MeetingTarget, MicSettings, call_channel,12
};12
};13
use session::{Session, SessionConfig, Transport};13
use session::{Session, SessionConfig, Transport};14
14
@@ -27,6 +27,7 @@ const READY_WAIT: Duration = Duration::from_secs(30);27
pub struct CallLauncher {27
pub struct CallLauncher {28
engine: watch::Sender<Option<CallEngine>>,28
engine: watch::Sender<Option<CallEngine>>,29
default_camera: Mutex<DeviceChoice>,29
default_camera: Mutex<DeviceChoice>,30
default_mic: Mutex<MicSettings>,30
}31
}31
32
32
impl CallLauncher {33
impl CallLauncher {@@ -38,6 +39,7 @@ impl CallLauncher {38
let launcher = Arc::new(CallLauncher {39
let launcher = Arc::new(CallLauncher {39
engine: watch::channel(None).0,40
engine: watch::channel(None).0,40
default_camera: Mutex::new(DeviceChoice::SystemDefault),41
default_camera: Mutex::new(DeviceChoice::SystemDefault),42
default_mic: Mutex::new(MicSettings::default()),41
});43
});42
let running = launcher.clone();44
let running = launcher.clone();43
crate::runtime::handle().spawn(async move {45
crate::runtime::handle().spawn(async move {@@ -49,6 +51,7 @@ impl CallLauncher {49
.await;51
.await;50
crate::diagnostics::record("calls: engine ready, registered with the registrar");52
crate::diagnostics::record("calls: engine ready, registered with the registrar");51
engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());53
engine.set_default_camera(running.default_camera.lock().expect("camera lock").clone());54
engine.set_default_mic(*running.default_mic.lock().expect("mic lock"));52
running.engine.send_replace(Some(engine));55
running.engine.send_replace(Some(engine));53
while let Some(event) = events.recv().await {56
while let Some(event) = events.recv().await {54
on_event(event);57
on_event(event);@@ -79,6 +82,13 @@ impl CallLauncher {79
}82
}80
}83
}81
84
85
pub fn set_default_mic(&self, mic: MicSettings) {86
*self.default_mic.lock().expect("mic lock") = mic;87
if let Some(engine) = self.engine() {88
engine.set_default_mic(mic);89
}90
}91
82
pub fn start_call(&self, spec: CallSpec) -> CallHandle {92
pub fn start_call(&self, spec: CallSpec) -> CallHandle {83
match self.engine() {93
match self.engine() {84
Some(engine) => engine.start_call(spec),94
Some(engine) => engine.start_call(spec),@@ -204,6 +204,7 @@ mod probe {
204
204
let queue = SampleQueue::default();
205
205
let started = calling::sound_capture::start_microphone(
206
206
&calling::DeviceChoice::SystemDefault,
207
None,
207
208
queue.clone(),
208
209
)
209
210
.map_err(|error| failed("microphone", error))?;
@@ -204,6 +204,7 @@ mod probe {204
let queue = SampleQueue::default();204
let queue = SampleQueue::default();205
let started = calling::sound_capture::start_microphone(205
let started = calling::sound_capture::start_microphone(206
&calling::DeviceChoice::SystemDefault,206
&calling::DeviceChoice::SystemDefault,207
None,207
queue.clone(),208
queue.clone(),208
)209
)209
.map_err(|error| failed("microphone", error))?;210
.map_err(|error| failed("microphone", error))?;@@ -10,6 +10,7 @@ use tokio::time::interval;
10
10
11
11
use crate::audio::{ClipGenerator, FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};
12
12
use crate::devices::{self, DeviceChoice};
13
use crate::mic_processing::{MicSettings, NoiseSuppression};
13
14
14
15
const TONE_AMPLITUDE: f32 = 0.3;
15
16
const SOURCE_QUEUE_MS: u32 = 100;
@@ -44,6 +45,7 @@ impl AudioMode {
44
45
pub struct AudioSetup {
45
46
factory: PeerConnectionFactory,
46
47
pub track: RtcAudioTrack,
48
pub track_with_ns: Option<RtcAudioTrack>,
47
49
pub listen_only: bool,
48
50
platform_acquired: bool,
49
51
pub adm_state: String,
@@ -90,9 +92,17 @@ impl AudioSetup {
90
92
}
91
93
}
92
94
if has_input {
95
// Windows Auto disables built-in WebRTC NS so DeepFilterNet runs alone on 48 kHz mics
96
// (with single-stage WebRTC NS fallback inside the capture hook for 16 kHz / warm-up).
97
// Linux and macOS keep WebRTC NS on that track, then DeepFilterNet, as before.
98
// Low mode switches to `track_with_ns` with built-in WebRTC NS enabled and hook off.
99
let track =
100
factory.create_device_audio_track_with_options("microphone", !cfg!(windows));
101
let track_with_ns = Some(factory.create_device_audio_track("microphone-ns"));
93
102
return AudioSetup {
94
103
factory: factory.clone(),
95
track: factory.create_device_audio_track("microphone"),
104
track,
105
track_with_ns,
96
106
listen_only: false,
97
107
platform_acquired,
98
108
adm_state,
@@ -124,6 +134,7 @@ impl AudioSetup {
124
134
AudioSetup {
125
135
factory: factory.clone(),
126
136
track,
137
track_with_ns: None,
127
138
listen_only: mode == AudioMode::Platform,
128
139
platform_acquired,
129
140
adm_state,
@@ -131,6 +142,22 @@ impl AudioSetup {
131
142
}
132
143
}
133
144
145
pub fn device_track(&self, settings: MicSettings) -> &RtcAudioTrack {
146
if classical_noise_track(settings)
147
&& let Some(track) = &self.track_with_ns
148
{
149
return track;
150
}
151
&self.track
152
}
153
154
pub fn set_device_tracks_enabled(&self, enabled: bool) {
155
self.track.set_enabled(enabled);
156
if let Some(track) = &self.track_with_ns {
157
track.set_enabled(enabled);
158
}
159
}
160
134
161
pub fn uses_devices(&self) -> bool {
135
162
self.platform_acquired && self.feeder.is_none()
136
163
}
@@ -153,6 +180,10 @@ enum FrameGenerator {
153
180
Clip(ClipGenerator),
154
181
}
155
182
183
pub(crate) fn classical_noise_track(settings: MicSettings) -> bool {
184
settings.noise_suppression == NoiseSuppression::Low && !settings.music_mode
185
}
186
156
187
impl FrameGenerator {
157
188
fn next_frame(&mut self) -> Vec<i16> {
158
189
match self {
@@ -194,4 +225,18 @@ mod tests {
194
225
assert_eq!(AudioMode::parse(Some("file")), AudioMode::File);
195
226
assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);
196
227
}
228
229
#[test]
230
fn only_low_uses_the_classical_noise_track() {
231
use crate::mic_processing::{MicSettings, NoiseSuppression};
232
let mut settings = MicSettings::default();
233
assert!(!classical_noise_track(settings));
234
settings.noise_suppression = NoiseSuppression::Low;
235
assert!(classical_noise_track(settings));
236
settings.noise_suppression = NoiseSuppression::Off;
237
assert!(!classical_noise_track(settings));
238
settings.noise_suppression = NoiseSuppression::Low;
239
settings.music_mode = true;
240
assert!(!classical_noise_track(settings));
241
}
197
242
}
@@ -10,6 +10,7 @@ use tokio::time::interval;10
10
11
use crate::audio::{ClipGenerator, FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};11
use crate::audio::{ClipGenerator, FRAME_SAMPLES, SAMPLE_RATE, SineGenerator};12
use crate::devices::{self, DeviceChoice};12
use crate::devices::{self, DeviceChoice};13
use crate::mic_processing::{MicSettings, NoiseSuppression};13
14
14
const TONE_AMPLITUDE: f32 = 0.3;15
const TONE_AMPLITUDE: f32 = 0.3;15
const SOURCE_QUEUE_MS: u32 = 100;16
const SOURCE_QUEUE_MS: u32 = 100;@@ -44,6 +45,7 @@ impl AudioMode {44
pub struct AudioSetup {45
pub struct AudioSetup {45
factory: PeerConnectionFactory,46
factory: PeerConnectionFactory,46
pub track: RtcAudioTrack,47
pub track: RtcAudioTrack,48
pub track_with_ns: Option<RtcAudioTrack>,47
pub listen_only: bool,49
pub listen_only: bool,48
platform_acquired: bool,50
platform_acquired: bool,49
pub adm_state: String,51
pub adm_state: String,@@ -90,9 +92,17 @@ impl AudioSetup {90
}92
}91
}93
}92
if has_input {94
if has_input {95
// Windows Auto disables built-in WebRTC NS so DeepFilterNet runs alone on 48 kHz mics96
// (with single-stage WebRTC NS fallback inside the capture hook for 16 kHz / warm-up).97
// Linux and macOS keep WebRTC NS on that track, then DeepFilterNet, as before.98
// Low mode switches to `track_with_ns` with built-in WebRTC NS enabled and hook off.99
let track =100
factory.create_device_audio_track_with_options("microphone", !cfg!(windows));101
let track_with_ns = Some(factory.create_device_audio_track("microphone-ns"));93
return AudioSetup {102
return AudioSetup {94
factory: factory.clone(),103
factory: factory.clone(),95
track: factory.create_device_audio_track("microphone"),104
track,105
track_with_ns,96
listen_only: false,106
listen_only: false,97
platform_acquired,107
platform_acquired,98
adm_state,108
adm_state,@@ -124,6 +134,7 @@ impl AudioSetup {124
AudioSetup {134
AudioSetup {125
factory: factory.clone(),135
factory: factory.clone(),126
track,136
track,137
track_with_ns: None,127
listen_only: mode == AudioMode::Platform,138
listen_only: mode == AudioMode::Platform,128
platform_acquired,139
platform_acquired,129
adm_state,140
adm_state,@@ -131,6 +142,22 @@ impl AudioSetup {131
}142
}132
}143
}133
144
145
pub fn device_track(&self, settings: MicSettings) -> &RtcAudioTrack {146
if classical_noise_track(settings)147
&& let Some(track) = &self.track_with_ns148
{149
return track;150
}151
&self.track152
}153
154
pub fn set_device_tracks_enabled(&self, enabled: bool) {155
self.track.set_enabled(enabled);156
if let Some(track) = &self.track_with_ns {157
track.set_enabled(enabled);158
}159
}160
134
pub fn uses_devices(&self) -> bool {161
pub fn uses_devices(&self) -> bool {135
self.platform_acquired && self.feeder.is_none()162
self.platform_acquired && self.feeder.is_none()136
}163
}@@ -153,6 +180,10 @@ enum FrameGenerator {153
Clip(ClipGenerator),180
Clip(ClipGenerator),154
}181
}155
182
183
pub(crate) fn classical_noise_track(settings: MicSettings) -> bool {184
settings.noise_suppression == NoiseSuppression::Low && !settings.music_mode185
}186
156
impl FrameGenerator {187
impl FrameGenerator {157
fn next_frame(&mut self) -> Vec<i16> {188
fn next_frame(&mut self) -> Vec<i16> {158
match self {189
match self {@@ -194,4 +225,18 @@ mod tests {194
assert_eq!(AudioMode::parse(Some("file")), AudioMode::File);225
assert_eq!(AudioMode::parse(Some("file")), AudioMode::File);195
assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);226
assert_eq!(AudioMode::parse(Some("whatever")), AudioMode::Platform);196
}227
}228
229
#[test]230
fn only_low_uses_the_classical_noise_track() {231
use crate::mic_processing::{MicSettings, NoiseSuppression};232
let mut settings = MicSettings::default();233
assert!(!classical_noise_track(settings));234
settings.noise_suppression = NoiseSuppression::Low;235
assert!(classical_noise_track(settings));236
settings.noise_suppression = NoiseSuppression::Off;237
assert!(!classical_noise_track(settings));238
settings.noise_suppression = NoiseSuppression::Low;239
settings.music_mode = true;240
assert!(!classical_noise_track(settings));241
}197
}242
}@@ -51,25 +51,51 @@ pub(super) fn record_audio_devices(
51
51
);
52
52
}
53
53
54
#[allow(clippy::too_many_arguments)]
54
55
pub(super) fn follow_device_change(
55
56
flow: Flow,
56
57
(previous, current): (&[AudioDevice], &[AudioDevice]),
57
58
choice: &DeviceChoice,
58
59
applied: &mut Option<AppliedDevice>,
60
touched_ids: &[String],
59
61
select: impl Fn(u16) -> bool,
60
62
timeline: &Timeline,
61
63
control: &CallControl,
62
64
) -> bool {
63
65
let system_default = devices::system_default_id(flow);
64
let (index, fell_back) =
66
let (index, fell_back, recovery) =
65
67
match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
66
Reselect::Keep => return false,
67
Reselect::Select(index) => (index, false),
68
Reselect::FallBack(index) => (index, true),
68
Reselect::Keep => {
69
// On Windows, a Bluetooth headset profile switch or brief disconnect+reconnect
70
// within the debounce window can leave the same endpoint index while the legacy
71
// WASAPI render/capture thread has already died on timeout/invalidation.
72
let Some(active) = applied.as_ref() else {
73
return false;
74
};
75
let active_touched = touched_ids
76
.iter()
77
.any(|id| id.eq_ignore_ascii_case(&active.key));
78
if !active_touched {
79
return false;
80
}
81
let Some(still_present) = current
82
.iter()
83
.find(|device| device.key().eq_ignore_ascii_case(&active.key))
84
else {
85
return false;
86
};
87
(still_present.index, false, true)
88
}
89
Reselect::Select(index) => (index, false, false),
90
Reselect::FallBack(index) => (index, true, false),
69
91
};
70
92
let selected = select(index);
71
93
timeline.record(
72
"device change",
94
if recovery {
95
"device recovery"
96
} else {
97
"device change"
98
},
73
99
format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
74
100
);
75
101
if selected {
@@ -99,7 +125,7 @@ pub(super) fn apply_mute(
99
125
control: &CallControl,
100
126
) -> bool {
101
127
let effect = MuteEffect::for_muted(command.target(currently_muted));
102
audio.track.set_enabled(effect.track_enabled);
128
audio.set_device_tracks_enabled(effect.track_enabled);
103
129
if let Some(software_audio) = software_audio {
104
130
software_audio.set_microphone_muted(effect.muted);
105
131
}
@@ -118,6 +144,19 @@ pub(super) fn apply_mute(
118
144
effect.muted
119
145
}
120
146
147
pub(super) fn silence_for_server_mute(
148
audio: &AudioSetup,
149
software_audio: Option<&SoftwareAudio>,
150
control: &CallControl,
151
) {
152
let effect = MuteEffect::for_muted(true);
153
audio.set_device_tracks_enabled(effect.track_enabled);
154
if let Some(software_audio) = software_audio {
155
software_audio.set_microphone_muted(true);
156
}
157
control.send(CallUpdate::Muted(true));
158
}
159
121
160
pub(super) fn silence_for_hold(
122
161
on_hold: bool,
123
162
muted: bool,
@@ -126,9 +165,7 @@ pub(super) fn silence_for_hold(
126
165
) {
127
166
let silent = on_hold || muted;
128
167
if let Some(audio) = audio {
129
audio
130
.track
131
.set_enabled(MuteEffect::for_muted(silent).track_enabled);
168
audio.set_device_tracks_enabled(MuteEffect::for_muted(silent).track_enabled);
132
169
}
133
170
if let Some(software_audio) = software_audio {
134
171
software_audio.set_microphone_muted(silent);
@@ -51,25 +51,51 @@ pub(super) fn record_audio_devices(51
);51
);52
}52
}53
53
54
#[allow(clippy::too_many_arguments)]54
pub(super) fn follow_device_change(55
pub(super) fn follow_device_change(55
flow: Flow,56
flow: Flow,56
(previous, current): (&[AudioDevice], &[AudioDevice]),57
(previous, current): (&[AudioDevice], &[AudioDevice]),57
choice: &DeviceChoice,58
choice: &DeviceChoice,58
applied: &mut Option<AppliedDevice>,59
applied: &mut Option<AppliedDevice>,60
touched_ids: &[String],59
select: impl Fn(u16) -> bool,61
select: impl Fn(u16) -> bool,60
timeline: &Timeline,62
timeline: &Timeline,61
control: &CallControl,63
control: &CallControl,62
) -> bool {64
) -> bool {63
let system_default = devices::system_default_id(flow);65
let system_default = devices::system_default_id(flow);64
let (index, fell_back) =66
let (index, fell_back, recovery) =65
match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {67
match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {66
Reselect::Keep => return false,68
Reselect::Keep => {67
Reselect::Select(index) => (index, false),69
// On Windows, a Bluetooth headset profile switch or brief disconnect+reconnect68
Reselect::FallBack(index) => (index, true),70
// within the debounce window can leave the same endpoint index while the legacy71
// WASAPI render/capture thread has already died on timeout/invalidation.72
let Some(active) = applied.as_ref() else {73
return false;74
};75
let active_touched = touched_ids76
.iter()77
.any(|id| id.eq_ignore_ascii_case(&active.key));78
if !active_touched {79
return false;80
}81
let Some(still_present) = current82
.iter()83
.find(|device| device.key().eq_ignore_ascii_case(&active.key))84
else {85
return false;86
};87
(still_present.index, false, true)88
}89
Reselect::Select(index) => (index, false, false),90
Reselect::FallBack(index) => (index, true, false),69
};91
};70
let selected = select(index);92
let selected = select(index);71
timeline.record(93
timeline.record(72
"device change",94
if recovery {95
"device recovery"96
} else {97
"device change"98
},73
format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),99
format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),74
);100
);75
if selected {101
if selected {@@ -99,7 +125,7 @@ pub(super) fn apply_mute(99
control: &CallControl,125
control: &CallControl,100
) -> bool {126
) -> bool {101
let effect = MuteEffect::for_muted(command.target(currently_muted));127
let effect = MuteEffect::for_muted(command.target(currently_muted));102
audio.track.set_enabled(effect.track_enabled);128
audio.set_device_tracks_enabled(effect.track_enabled);103
if let Some(software_audio) = software_audio {129
if let Some(software_audio) = software_audio {104
software_audio.set_microphone_muted(effect.muted);130
software_audio.set_microphone_muted(effect.muted);105
}131
}@@ -118,6 +144,19 @@ pub(super) fn apply_mute(118
effect.muted144
effect.muted119
}145
}120
146
147
pub(super) fn silence_for_server_mute(148
audio: &AudioSetup,149
software_audio: Option<&SoftwareAudio>,150
control: &CallControl,151
) {152
let effect = MuteEffect::for_muted(true);153
audio.set_device_tracks_enabled(effect.track_enabled);154
if let Some(software_audio) = software_audio {155
software_audio.set_microphone_muted(true);156
}157
control.send(CallUpdate::Muted(true));158
}159
121
pub(super) fn silence_for_hold(160
pub(super) fn silence_for_hold(122
on_hold: bool,161
on_hold: bool,123
muted: bool,162
muted: bool,@@ -126,9 +165,7 @@ pub(super) fn silence_for_hold(126
) {165
) {127
let silent = on_hold || muted;166
let silent = on_hold || muted;128
if let Some(audio) = audio {167
if let Some(audio) = audio {129
audio168
audio.set_device_tracks_enabled(MuteEffect::for_muted(silent).track_enabled);130
.track131
.set_enabled(MuteEffect::for_muted(silent).track_enabled);132
}169
}133
if let Some(software_audio) = software_audio {170
if let Some(software_audio) = software_audio {134
software_audio.set_microphone_muted(silent);171
software_audio.set_microphone_muted(silent);@@ -55,7 +55,7 @@ use crate::hold::{
55
55
};
56
56
use crate::meeting_options::{self, OptionWrite};
57
57
use crate::mic_processing::MicSettings;
58
use crate::mute::{MuteCommand, MuteEffect};
58
use crate::mute::{MuteCommand, MuteEffect, sync_server_mute};
59
59
use crate::notices::{
60
60
ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,
61
61
BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,
@@ -171,6 +171,7 @@ pub struct CallOptions {
171
171
pub data_channel: bool,
172
172
pub concurrent: bool,
173
173
pub start_camera: bool,
174
pub mic: MicSettings,
174
175
}
175
176
176
177
impl Default for CallOptions {
@@ -194,6 +195,7 @@ impl Default for CallOptions {
194
195
data_channel: data_channel_from_env(),
195
196
concurrent: false,
196
197
start_camera: false,
198
mic: MicSettings::default(),
197
199
}
198
200
}
199
201
}
@@ -599,7 +601,8 @@ async fn drive(
599
601
input: input.clone(),
600
602
output: output.clone(),
601
603
});
602
let track = audio.track.clone();
604
let mut mic_settings = options.mic;
605
let mut track = audio.device_track(mic_settings).clone();
603
606
live.audio = Some(audio);
604
607
let mut local_video = LocalVideo::new(
605
608
&factory,
@@ -871,6 +874,7 @@ async fn drive(
871
874
872
875
let initial = MuteEffect::initial(is_meeting);
873
876
let mut muted = initial.muted;
877
let mut server_mute_cleared = false;
874
878
live.audio
875
879
.as_ref()
876
880
.expect("audio set above")
@@ -929,7 +933,6 @@ async fn drive(
929
933
}
930
934
let mut software_audio: Option<SoftwareAudio> = None;
931
935
let mut share_sound_wanted = false;
932
let mut mic_settings = MicSettings::default();
933
936
let mut audio_disabled = false;
934
937
let mut remote_audio: Option<RtcAudioTrack> = None;
935
938
sync_software_audio(
@@ -1615,6 +1618,18 @@ async fn drive(
1615
1618
let entries = roster.entries();
1616
1619
timeline.record("roster", format!("{} participant(s)", entries.len()));
1617
1620
control.send(CallUpdate::Roster(entries));
1621
let own_server_muted = roster
1622
.members()
1623
.iter()
1624
.any(|member| member.mri == own_mri && member.server_muted);
1625
let decision = sync_server_mute(own_server_muted, muted, server_mute_cleared);
1626
server_mute_cleared = decision.cleared;
1627
if decision.silence_without_signal
1628
&& let Some(audio) = live.audio.as_ref()
1629
{
1630
silence_for_server_mute(audio, software_audio.as_ref(), control);
1631
muted = true;
1632
}
1618
1633
if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) {
1619
1634
timeline.record("echo bot left", "test call ends like in Teams");
1620
1635
advance(state, CallSignal::RemoteEnd(EndKind::Normal), control);
@@ -2041,6 +2056,13 @@ async fn drive(
2041
2056
},
2042
2057
command = control.recv() => match command {
2043
2058
Some(CallCommand::Mute(mute)) => {
2059
let own_server_muted = roster
2060
.members()
2061
.iter()
2062
.any(|member| member.mri == own_mri && member.server_muted);
2063
if !mute.target(muted) && own_server_muted {
2064
server_mute_cleared = true;
2065
}
2044
2066
if consent_pending && !mute.target(muted) {
2045
2067
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
2046
2068
} else {
@@ -2073,8 +2095,13 @@ async fn drive(
2073
2095
}
2074
2096
}
2075
2097
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
2098
let device_ns_changed =
2099
mic_settings.ml_noise_suppression() != settings.ml_noise_suppression();
2076
2100
mic_settings = settings;
2077
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2101
if let Some(audio) = live.audio.as_ref() {
2102
track = audio.device_track(mic_settings).clone();
2103
}
2104
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);
2078
2105
}
2079
2106
Some(CallCommand::SetMicSettings(settings)) => {
2080
2107
mic_settings = settings;
@@ -2871,18 +2898,37 @@ async fn drive(
2871
2898
local_video.camera_capture_summary().unwrap_or_default()
2872
2899
),
2873
2900
);
2901
#[cfg(not(windows))]
2902
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2903
let listed = devices::list_devices(&factory);
2904
let previous_ids: Vec<String> = device_lists
2905
.inputs
2906
.iter()
2907
.chain(device_lists.outputs.iter())
2908
.map(|device| device.key())
2909
.collect();
2910
let current_ids: Vec<String> = listed
2911
.inputs
2912
.iter()
2913
.chain(listed.outputs.iter())
2914
.map(|device| device.key())
2915
.collect();
2916
for id in device_watch::endpoint_delta(&previous_ids, ¤t_ids) {
2917
device_debounce.signal_device(Instant::now(), Some(id));
2918
}
2919
}
2874
2920
}
2875
2921
}
2876
Some(()) = device_changes.recv() => {
2877
device_debounce.signal(Instant::now());
2922
Some(device_id) = device_changes.recv() => {
2923
device_debounce.signal_device(Instant::now(), device_id);
2878
2924
}
2879
2925
_ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {
2880
if device_debounce.take_due(Instant::now()) {
2926
if let Some(touched_ids) = device_debounce.take_due_devices(Instant::now()) {
2881
2927
let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));
2882
2928
control.send(CallUpdate::Devices(device_lists.clone()));
2883
2929
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2884
let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, |index| devices::select_input_index(&factory, index), timeline, control);
2885
let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, |index| devices::select_output_index(&factory, index), timeline, control);
2930
let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, &touched_ids, |index| devices::select_input_index(&factory, index), timeline, control);
2931
let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, &touched_ids, |index| devices::select_output_index(&factory, index), timeline, control);
2886
2932
if input_changed || output_changed {
2887
2933
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2888
2934
}
@@ -55,7 +55,7 @@ use crate::hold::{55
};55
};56
use crate::meeting_options::{self, OptionWrite};56
use crate::meeting_options::{self, OptionWrite};57
use crate::mic_processing::MicSettings;57
use crate::mic_processing::MicSettings;58
use crate::mute::{MuteCommand, MuteEffect};58
use crate::mute::{MuteCommand, MuteEffect, sync_server_mute};59
use crate::notices::{59
use crate::notices::{60
ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,60
ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE,61
BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,61
BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE,@@ -171,6 +171,7 @@ pub struct CallOptions {171
pub data_channel: bool,171
pub data_channel: bool,172
pub concurrent: bool,172
pub concurrent: bool,173
pub start_camera: bool,173
pub start_camera: bool,174
pub mic: MicSettings,174
}175
}175
176
176
impl Default for CallOptions {177
impl Default for CallOptions {@@ -194,6 +195,7 @@ impl Default for CallOptions {194
data_channel: data_channel_from_env(),195
data_channel: data_channel_from_env(),195
concurrent: false,196
concurrent: false,196
start_camera: false,197
start_camera: false,198
mic: MicSettings::default(),197
}199
}198
}200
}199
}201
}@@ -599,7 +601,8 @@ async fn drive(599
input: input.clone(),601
input: input.clone(),600
output: output.clone(),602
output: output.clone(),601
});603
});602
let track = audio.track.clone();604
let mut mic_settings = options.mic;605
let mut track = audio.device_track(mic_settings).clone();603
live.audio = Some(audio);606
live.audio = Some(audio);604
let mut local_video = LocalVideo::new(607
let mut local_video = LocalVideo::new(605
&factory,608
&factory,@@ -871,6 +874,7 @@ async fn drive(871
874
872
let initial = MuteEffect::initial(is_meeting);875
let initial = MuteEffect::initial(is_meeting);873
let mut muted = initial.muted;876
let mut muted = initial.muted;877
let mut server_mute_cleared = false;874
live.audio878
live.audio875
.as_ref()879
.as_ref()876
.expect("audio set above")880
.expect("audio set above")@@ -929,7 +933,6 @@ async fn drive(929
}933
}930
let mut software_audio: Option<SoftwareAudio> = None;934
let mut software_audio: Option<SoftwareAudio> = None;931
let mut share_sound_wanted = false;935
let mut share_sound_wanted = false;932
let mut mic_settings = MicSettings::default();933
let mut audio_disabled = false;936
let mut audio_disabled = false;934
let mut remote_audio: Option<RtcAudioTrack> = None;937
let mut remote_audio: Option<RtcAudioTrack> = None;935
sync_software_audio(938
sync_software_audio(@@ -1615,6 +1618,18 @@ async fn drive(1615
let entries = roster.entries();1618
let entries = roster.entries();1616
timeline.record("roster", format!("{} participant(s)", entries.len()));1619
timeline.record("roster", format!("{} participant(s)", entries.len()));1617
control.send(CallUpdate::Roster(entries));1620
control.send(CallUpdate::Roster(entries));1621
let own_server_muted = roster1622
.members()1623
.iter()1624
.any(|member| member.mri == own_mri && member.server_muted);1625
let decision = sync_server_mute(own_server_muted, muted, server_mute_cleared);1626
server_mute_cleared = decision.cleared;1627
if decision.silence_without_signal1628
&& let Some(audio) = live.audio.as_ref()1629
{1630
silence_for_server_mute(audio, software_audio.as_ref(), control);1631
muted = true;1632
}1618
if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) {1633
if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) {1619
timeline.record("echo bot left", "test call ends like in Teams");1634
timeline.record("echo bot left", "test call ends like in Teams");1620
advance(state, CallSignal::RemoteEnd(EndKind::Normal), control);1635
advance(state, CallSignal::RemoteEnd(EndKind::Normal), control);@@ -2041,6 +2056,13 @@ async fn drive(2041
},2056
},2042
command = control.recv() => match command {2057
command = control.recv() => match command {2043
Some(CallCommand::Mute(mute)) => {2058
Some(CallCommand::Mute(mute)) => {2059
let own_server_muted = roster2060
.members()2061
.iter()2062
.any(|member| member.mri == own_mri && member.server_muted);2063
if !mute.target(muted) && own_server_muted {2064
server_mute_cleared = true;2065
}2044
if consent_pending && !mute.target(muted) {2066
if consent_pending && !mute.target(muted) {2045
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));2067
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));2046
} else {2068
} else {@@ -2073,8 +2095,13 @@ async fn drive(2073
}2095
}2074
}2096
}2075
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2097
Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {2098
let device_ns_changed =2099
mic_settings.ml_noise_suppression() != settings.ml_noise_suppression();2076
mic_settings = settings;2100
mic_settings = settings;2077
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);2101
if let Some(audio) = live.audio.as_ref() {2102
track = audio.device_track(mic_settings).clone();2103
}2104
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline);2078
}2105
}2079
Some(CallCommand::SetMicSettings(settings)) => {2106
Some(CallCommand::SetMicSettings(settings)) => {2080
mic_settings = settings;2107
mic_settings = settings;@@ -2871,18 +2898,37 @@ async fn drive(2871
local_video.camera_capture_summary().unwrap_or_default()2898
local_video.camera_capture_summary().unwrap_or_default()2872
),2899
),2873
);2900
);2901
#[cfg(not(windows))]2902
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {2903
let listed = devices::list_devices(&factory);2904
let previous_ids: Vec<String> = device_lists2905
.inputs2906
.iter()2907
.chain(device_lists.outputs.iter())2908
.map(|device| device.key())2909
.collect();2910
let current_ids: Vec<String> = listed2911
.inputs2912
.iter()2913
.chain(listed.outputs.iter())2914
.map(|device| device.key())2915
.collect();2916
for id in device_watch::endpoint_delta(&previous_ids, ¤t_ids) {2917
device_debounce.signal_device(Instant::now(), Some(id));2918
}2919
}2874
}2920
}2875
}2921
}2876
Some(()) = device_changes.recv() => {2922
Some(device_id) = device_changes.recv() => {2877
device_debounce.signal(Instant::now());2923
device_debounce.signal_device(Instant::now(), device_id);2878
}2924
}2879
_ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {2925
_ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {2880
if device_debounce.take_due(Instant::now()) {2926
if let Some(touched_ids) = device_debounce.take_due_devices(Instant::now()) {2881
let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));2927
let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));2882
control.send(CallUpdate::Devices(device_lists.clone()));2928
control.send(CallUpdate::Devices(device_lists.clone()));2883
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {2929
if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {2884
let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, |index| devices::select_input_index(&factory, index), timeline, control);2930
let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, &touched_ids, |index| devices::select_input_index(&factory, index), timeline, control);2885
let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, |index| devices::select_output_index(&factory, index), timeline, control);2931
let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, &touched_ids, |index| devices::select_output_index(&factory, index), timeline, control);2886
if input_changed || output_changed {2932
if input_changed || output_changed {2887
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());2933
record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());2888
}2934
}@@ -1,9 +1,10 @@
1
#[cfg(target_os = "linux")]
1
2
use std::process::Command;
2
3
use std::sync::Arc;
3
4
use std::sync::atomic::{AtomicU64, Ordering};
4
5
use std::time::{Duration, Instant};
5
6
6
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
7
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420, yuy2_to_i420};
7
8
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
8
9
use nokhwa::pixel_format::RgbAFormat;
9
10
use nokhwa::utils::{
@@ -107,22 +108,95 @@ pub fn list_cameras() -> Vec<CameraDevice> {
107
108
query(ApiBackend::Auto)
108
109
.unwrap_or_default()
109
110
.into_iter()
110
.map(|info| CameraDevice {
111
key: match info.index() {
111
.map(|info| {
112
let fallback_key = match info.index() {
112
113
CameraIndex::Index(number) => number.to_string(),
113
114
CameraIndex::String(text) => text.clone(),
114
},
115
name: info.human_name(),
115
};
116
#[cfg(windows)]
117
let key = {
118
let misc = info.misc();
119
if misc.trim().is_empty() {
120
fallback_key
121
} else {
122
misc
123
}
124
};
125
#[cfg(not(windows))]
126
let key = fallback_key;
127
CameraDevice {
128
key,
129
name: info.human_name(),
130
}
116
131
})
117
132
.collect()
118
133
}
119
134
120
fn camera_index(choice: &DeviceChoice) -> CameraIndex {
121
match choice {
122
DeviceChoice::SystemDefault => CameraIndex::Index(0),
123
DeviceChoice::Device(key) => key
124
.parse()
125
.map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
135
fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {
136
#[cfg(windows)]
137
{
138
let queried = query(ApiBackend::Auto).unwrap_or_default();
139
match choice {
140
DeviceChoice::SystemDefault => {
141
let tune_target = queried
142
.first()
143
.map(|info| {
144
let misc = info.misc();
145
if misc.trim().is_empty() {
146
info.human_name()
147
} else {
148
misc
149
}
150
})
151
.unwrap_or_default();
152
let index = queried
153
.first()
154
.map_or(CameraIndex::Index(0), |info| info.index().clone());
155
return (index, tune_target);
156
}
157
DeviceChoice::Device(key) => {
158
if let Some(found) = queried.iter().find(|info| {
159
let misc = info.misc();
160
(!misc.is_empty() && misc.eq_ignore_ascii_case(key))
161
|| info.human_name().eq_ignore_ascii_case(key)
162
}) {
163
let misc = found.misc();
164
let tune_target = if misc.trim().is_empty() {
165
found.human_name()
166
} else {
167
misc
168
};
169
return (found.index().clone(), tune_target);
170
}
171
// Backward compatibility for previously saved numeric indices ("0", "1").
172
if let Ok(number) = key.parse::<u32>() {
173
let tune_target = queried
174
.iter()
175
.find(|info| *info.index() == CameraIndex::Index(number))
176
.map(|info| {
177
let misc = info.misc();
178
if misc.trim().is_empty() {
179
info.human_name()
180
} else {
181
misc
182
}
183
})
184
.unwrap_or_default();
185
return (CameraIndex::Index(number), tune_target);
186
}
187
return (CameraIndex::String(key.clone()), key.clone());
188
}
189
}
190
}
191
#[cfg(not(windows))]
192
{
193
let index = match choice {
194
DeviceChoice::SystemDefault => CameraIndex::Index(0),
195
DeviceChoice::Device(key) => key
196
.parse()
197
.map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),
198
};
199
(index, String::new())
126
200
}
127
201
}
128
202
@@ -319,6 +393,7 @@ fn open_with_request(
319
393
Ok(camera)
320
394
}
321
395
396
#[cfg(target_os = "linux")]
322
397
fn device_path(index: &CameraIndex) -> Option<String> {
323
398
match index {
324
399
CameraIndex::Index(number) => Some(format!("/dev/video{number}")),
@@ -331,30 +406,48 @@ fn device_path(index: &CameraIndex) -> Option<String> {
331
406
}
332
407
}
333
408
334
fn tune_uvc_controls(index: &CameraIndex) {
335
let Some(device) = device_path(index) else {
336
return;
337
};
338
// Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).
339
let _ = Command::new("v4l2-ctl")
340
.args([
341
"-d",
342
&device,
343
"-c",
344
"exposure_dynamic_framerate=0,power_line_frequency=1",
345
])
346
.stdout(std::process::Stdio::null())
347
.stderr(std::process::Stdio::null())
348
.status();
349
}
350
351
fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {
409
fn tune_uvc_controls(index: &CameraIndex, windows_target: &str) {
410
#[cfg(target_os = "linux")]
411
{
412
let _ = windows_target;
413
let Some(device) = device_path(index) else {
414
return;
415
};
416
// Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH/EU).
417
let _ = Command::new("v4l2-ctl")
418
.args([
419
"-d",
420
&device,
421
"-c",
422
"exposure_dynamic_framerate=0,power_line_frequency=1",
423
])
424
.stdout(std::process::Stdio::null())
425
.stderr(std::process::Stdio::null())
426
.status();
427
}
428
#[cfg(windows)]
429
{
430
let _ = index;
431
// Best effort: 50 Hz anti-flicker & disable low-light FPS drop via DirectShow UVC KSPROPERTY.
432
webrtc_sys::webrtc::ffi::tune_windows_camera(windows_target);
433
}
434
#[cfg(not(any(target_os = "linux", windows)))]
435
{
436
let _ = (index, windows_target);
437
}
438
}
439
440
fn accept_opened(
441
index: &CameraIndex,
442
windows_target: &str,
443
mut camera: Camera,
444
) -> Option<(Camera, String)> {
352
445
let got = camera.camera_format();
353
446
if got.frame_rate() < CAPTURE_FPS {
354
447
let _ = camera.stop_stream();
355
448
return None;
356
449
}
357
tune_uvc_controls(index);
450
tune_uvc_controls(index, windows_target);
358
451
let label = format_label(&got);
359
452
Some((camera, label))
360
453
}
@@ -371,6 +464,7 @@ fn try_exact_or_closest(
371
464
372
465
fn open_from_list(
373
466
index: CameraIndex,
467
windows_target: &str,
374
468
quality: VideoQuality,
375
469
formats: &[CameraFormat],
376
470
) -> Option<(Camera, String)> {
@@ -378,15 +472,16 @@ fn open_from_list(
378
472
return None;
379
473
};
380
474
let camera = try_exact_or_closest(index.clone(), wanted).ok()?;
381
accept_opened(&index, camera)
475
accept_opened(&index, windows_target, camera)
382
476
}
383
477
384
478
fn open_picked_format(
385
479
index: CameraIndex,
480
windows_target: &str,
386
481
quality: VideoQuality,
387
482
) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
388
483
let mut camera = Camera::new(
389
index,
484
index.clone(),
390
485
RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),
391
486
)?;
392
487
let formats = camera.compatible_camera_formats()?;
@@ -397,15 +492,17 @@ fn open_picked_format(
397
492
RequestedFormatType::Exact(format),
398
493
))?;
399
494
camera.open_stream()?;
495
tune_uvc_controls(&index, windows_target);
400
496
Ok((camera, format_label(&format)))
401
497
}
402
498
403
499
fn open_camera(
404
500
index: CameraIndex,
501
windows_target: &str,
405
502
quality: VideoQuality,
406
503
) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {
407
504
if cfg!(windows)
408
&& let Ok(opened) = open_picked_format(index.clone(), quality)
505
&& let Ok(opened) = open_picked_format(index.clone(), windows_target, quality)
409
506
{
410
507
return Ok(opened);
411
508
}
@@ -417,10 +514,10 @@ fn open_camera(
417
514
if let Ok(formats) = camera.compatible_camera_formats() {
418
515
let _ = camera.stop_stream();
419
516
drop(camera);
420
if let Some(opened) = open_from_list(index.clone(), quality, &formats) {
517
if let Some(opened) = open_from_list(index.clone(), windows_target, quality, &formats) {
421
518
return Ok(opened);
422
519
}
423
} else if let Some(opened) = accept_opened(&index, camera) {
520
} else if let Some(opened) = accept_opened(&index, windows_target, camera) {
424
521
return Ok(opened);
425
522
}
426
523
}
@@ -429,7 +526,7 @@ fn open_camera(
429
526
for candidate in preferred_candidates(quality) {
430
527
match try_exact_or_closest(index.clone(), candidate) {
431
528
Ok(camera) => {
432
if let Some(opened) = accept_opened(&index, camera) {
529
if let Some(opened) = accept_opened(&index, windows_target, camera) {
433
530
return Ok(opened);
434
531
}
435
532
}
@@ -440,7 +537,7 @@ fn open_camera(
440
537
// Last resort: AbsoluteHighest may still yield a usable stream on odd backends.
441
538
match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {
442
539
Ok(camera) => {
443
tune_uvc_controls(&index);
540
tune_uvc_controls(&index, windows_target);
444
541
let label = format_label(&camera.camera_format());
445
542
Ok((camera, label))
446
543
}
@@ -475,33 +572,25 @@ pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I42
475
572
}
476
573
477
574
pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {
478
let (width_pixels, height_rows) = (width as usize, height as usize);
479
let row_bytes = width_pixels * 2;
480
if data.len() < row_bytes * height_rows {
575
let row_bytes = width as usize * 2;
576
if data.len() < row_bytes * height as usize {
481
577
return None;
482
578
}
483
579
let mut buffer = I420Buffer::new(width, height);
484
580
let (stride_y, stride_u, stride_v) = buffer.strides();
485
581
let (plane_y, plane_u, plane_v) = buffer.data_mut();
486
for row in 0..height_rows {
487
let source = &data[row * row_bytes..(row + 1) * row_bytes];
488
let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels];
489
for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) {
490
luma[0] = pair[0];
491
luma[1] = pair[2];
492
}
493
}
494
for row in 0..height_rows / 2 {
495
let upper = &data[row * 2 * row_bytes..][..row_bytes];
496
let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes];
497
let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2];
498
let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2];
499
for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() {
500
let offset = column * 4;
501
*blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8;
502
*red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8;
503
}
504
}
582
yuy2_to_i420(
583
data,
584
row_bytes as u32,
585
plane_y,
586
stride_y,
587
plane_u,
588
stride_u,
589
plane_v,
590
stride_v,
591
width as i32,
592
height as i32,
593
);
505
594
Some(buffer)
506
595
}
507
596
@@ -554,9 +643,9 @@ pub fn start_camera(
554
643
deliver: impl FnMut(I420Buffer) + Send + 'static,
555
644
failed: impl FnOnce(String) + Send + 'static,
556
645
) -> Result<Capture> {
557
let index = camera_index(choice);
646
let (index, windows_target) = resolve_camera(choice);
558
647
Capture::spawn_thread("camera", move |stop| {
559
let (mut camera, label) = match open_camera(index, quality) {
648
let (mut camera, label) = match open_camera(index, &windows_target, quality) {
560
649
Ok(opened) => opened,
561
650
Err(error) => return failed(error.to_string()),
562
651
};
@@ -830,15 +919,15 @@ mod tests {
830
919
#[test]
831
920
fn camera_choices_map_to_indices_or_names() {
832
921
assert!(matches!(
833
camera_index(&DeviceChoice::SystemDefault),
834
CameraIndex::Index(0)
922
resolve_camera(&DeviceChoice::SystemDefault).0,
923
CameraIndex::Index(_)
835
924
));
836
925
assert!(matches!(
837
camera_index(&DeviceChoice::Device("2".into())),
926
resolve_camera(&DeviceChoice::Device("2".into())).0,
838
927
CameraIndex::Index(2)
839
928
));
840
929
assert!(matches!(
841
camera_index(&DeviceChoice::Device("video0".into())),
930
resolve_camera(&DeviceChoice::Device("video0".into())).0,
842
931
CameraIndex::String(_)
843
932
));
844
933
}
@@ -895,7 +984,7 @@ mod tests {
895
984
return;
896
985
}
897
986
let (mut camera, label) =
898
open_camera(CameraIndex::Index(0), VideoQuality::Auto).expect("camera opens");
987
open_camera(CameraIndex::Index(0), "", VideoQuality::Auto).expect("camera opens");
899
988
assert!(
900
989
camera.camera_format().frame_rate() >= CAPTURE_FPS,
901
990
"opened {label} under 30 fps"
@@ -1,9 +1,10 @@1
#[cfg(target_os = "linux")]1
use std::process::Command;2
use std::process::Command;2
use std::sync::Arc;3
use std::sync::Arc;3
use std::sync::atomic::{AtomicU64, Ordering};4
use std::sync::atomic::{AtomicU64, Ordering};4
use std::time::{Duration, Instant};5
use std::time::{Duration, Instant};5
6
6
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};7
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420, yuy2_to_i420};7
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};8
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};8
use nokhwa::pixel_format::RgbAFormat;9
use nokhwa::pixel_format::RgbAFormat;9
use nokhwa::utils::{10
use nokhwa::utils::{@@ -107,22 +108,95 @@ pub fn list_cameras() -> Vec<CameraDevice> {107
query(ApiBackend::Auto)108
query(ApiBackend::Auto)108
.unwrap_or_default()109
.unwrap_or_default()109
.into_iter()110
.into_iter()110
.map(|info| CameraDevice {111
.map(|info| {111
key: match info.index() {112
let fallback_key = match info.index() {112
CameraIndex::Index(number) => number.to_string(),113
CameraIndex::Index(number) => number.to_string(),113
CameraIndex::String(text) => text.clone(),114
CameraIndex::String(text) => text.clone(),114
},115
};115
name: info.human_name(),116
#[cfg(windows)]117
let key = {118
let misc = info.misc();119
if misc.trim().is_empty() {120
fallback_key121
} else {122
misc123
}124
};125
#[cfg(not(windows))]126
let key = fallback_key;127
CameraDevice {128
key,129
name: info.human_name(),130
}116
})131
})117
.collect()132
.collect()118
}133
}119
134
120
fn camera_index(choice: &DeviceChoice) -> CameraIndex {135
fn resolve_camera(choice: &DeviceChoice) -> (CameraIndex, String) {121
match choice {136
#[cfg(windows)]122
DeviceChoice::SystemDefault => CameraIndex::Index(0),137
{123
DeviceChoice::Device(key) => key138
let queried = query(ApiBackend::Auto).unwrap_or_default();124
.parse()139
match choice {125
.map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),140
DeviceChoice::SystemDefault => {141
let tune_target = queried142
.first()143
.map(|info| {144
let misc = info.misc();145
if misc.trim().is_empty() {146
info.human_name()147
} else {148
misc149
}150
})151
.unwrap_or_default();152
let index = queried153
.first()154
.map_or(CameraIndex::Index(0), |info| info.index().clone());155
return (index, tune_target);156
}157
DeviceChoice::Device(key) => {158
if let Some(found) = queried.iter().find(|info| {159
let misc = info.misc();160
(!misc.is_empty() && misc.eq_ignore_ascii_case(key))161
|| info.human_name().eq_ignore_ascii_case(key)162
}) {163
let misc = found.misc();164
let tune_target = if misc.trim().is_empty() {165
found.human_name()166
} else {167
misc168
};169
return (found.index().clone(), tune_target);170
}171
// Backward compatibility for previously saved numeric indices ("0", "1").172
if let Ok(number) = key.parse::<u32>() {173
let tune_target = queried174
.iter()175
.find(|info| *info.index() == CameraIndex::Index(number))176
.map(|info| {177
let misc = info.misc();178
if misc.trim().is_empty() {179
info.human_name()180
} else {181
misc182
}183
})184
.unwrap_or_default();185
return (CameraIndex::Index(number), tune_target);186
}187
return (CameraIndex::String(key.clone()), key.clone());188
}189
}190
}191
#[cfg(not(windows))]192
{193
let index = match choice {194
DeviceChoice::SystemDefault => CameraIndex::Index(0),195
DeviceChoice::Device(key) => key196
.parse()197
.map_or_else(|_| CameraIndex::String(key.clone()), CameraIndex::Index),198
};199
(index, String::new())126
}200
}127
}201
}128
202
@@ -319,6 +393,7 @@ fn open_with_request(319
Ok(camera)393
Ok(camera)320
}394
}321
395
396
#[cfg(target_os = "linux")]322
fn device_path(index: &CameraIndex) -> Option<String> {397
fn device_path(index: &CameraIndex) -> Option<String> {323
match index {398
match index {324
CameraIndex::Index(number) => Some(format!("/dev/video{number}")),399
CameraIndex::Index(number) => Some(format!("/dev/video{number}")),@@ -331,30 +406,48 @@ fn device_path(index: &CameraIndex) -> Option<String> {331
}406
}332
}407
}333
408
334
fn tune_uvc_controls(index: &CameraIndex) {409
fn tune_uvc_controls(index: &CameraIndex, windows_target: &str) {335
let Some(device) = device_path(index) else {410
#[cfg(target_os = "linux")]336
return;411
{337
};412
let _ = windows_target;338
// Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH).413
let Some(device) = device_path(index) else {339
let _ = Command::new("v4l2-ctl")414
return;340
.args([415
};341
"-d",416
// Best effort: fixed frame rate (no auto-drop in low light) and 50 Hz mains (CH/EU).342
&device,417
let _ = Command::new("v4l2-ctl")343
"-c",418
.args([344
"exposure_dynamic_framerate=0,power_line_frequency=1",419
"-d",345
])420
&device,346
.stdout(std::process::Stdio::null())421
"-c",347
.stderr(std::process::Stdio::null())422
"exposure_dynamic_framerate=0,power_line_frequency=1",348
.status();423
])349
}424
.stdout(std::process::Stdio::null())350
425
.stderr(std::process::Stdio::null())351
fn accept_opened(index: &CameraIndex, mut camera: Camera) -> Option<(Camera, String)> {426
.status();427
}428
#[cfg(windows)]429
{430
let _ = index;431
// Best effort: 50 Hz anti-flicker & disable low-light FPS drop via DirectShow UVC KSPROPERTY.432
webrtc_sys::webrtc::ffi::tune_windows_camera(windows_target);433
}434
#[cfg(not(any(target_os = "linux", windows)))]435
{436
let _ = (index, windows_target);437
}438
}439
440
fn accept_opened(441
index: &CameraIndex,442
windows_target: &str,443
mut camera: Camera,444
) -> Option<(Camera, String)> {352
let got = camera.camera_format();445
let got = camera.camera_format();353
if got.frame_rate() < CAPTURE_FPS {446
if got.frame_rate() < CAPTURE_FPS {354
let _ = camera.stop_stream();447
let _ = camera.stop_stream();355
return None;448
return None;356
}449
}357
tune_uvc_controls(index);450
tune_uvc_controls(index, windows_target);358
let label = format_label(&got);451
let label = format_label(&got);359
Some((camera, label))452
Some((camera, label))360
}453
}@@ -371,6 +464,7 @@ fn try_exact_or_closest(371
464
372
fn open_from_list(465
fn open_from_list(373
index: CameraIndex,466
index: CameraIndex,467
windows_target: &str,374
quality: VideoQuality,468
quality: VideoQuality,375
formats: &[CameraFormat],469
formats: &[CameraFormat],376
) -> Option<(Camera, String)> {470
) -> Option<(Camera, String)> {@@ -378,15 +472,16 @@ fn open_from_list(378
return None;472
return None;379
};473
};380
let camera = try_exact_or_closest(index.clone(), wanted).ok()?;474
let camera = try_exact_or_closest(index.clone(), wanted).ok()?;381
accept_opened(&index, camera)475
accept_opened(&index, windows_target, camera)382
}476
}383
477
384
fn open_picked_format(478
fn open_picked_format(385
index: CameraIndex,479
index: CameraIndex,480
windows_target: &str,386
quality: VideoQuality,481
quality: VideoQuality,387
) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {482
) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {388
let mut camera = Camera::new(483
let mut camera = Camera::new(389
index,484
index.clone(),390
RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),485
RequestedFormat::new::<RgbAFormat>(RequestedFormatType::AbsoluteHighestFrameRate),391
)?;486
)?;392
let formats = camera.compatible_camera_formats()?;487
let formats = camera.compatible_camera_formats()?;@@ -397,15 +492,17 @@ fn open_picked_format(397
RequestedFormatType::Exact(format),492
RequestedFormatType::Exact(format),398
))?;493
))?;399
camera.open_stream()?;494
camera.open_stream()?;495
tune_uvc_controls(&index, windows_target);400
Ok((camera, format_label(&format)))496
Ok((camera, format_label(&format)))401
}497
}402
498
403
fn open_camera(499
fn open_camera(404
index: CameraIndex,500
index: CameraIndex,501
windows_target: &str,405
quality: VideoQuality,502
quality: VideoQuality,406
) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {503
) -> std::result::Result<(Camera, String), nokhwa::NokhwaError> {407
if cfg!(windows)504
if cfg!(windows)408
&& let Ok(opened) = open_picked_format(index.clone(), quality)505
&& let Ok(opened) = open_picked_format(index.clone(), windows_target, quality)409
{506
{410
return Ok(opened);507
return Ok(opened);411
}508
}@@ -417,10 +514,10 @@ fn open_camera(417
if let Ok(formats) = camera.compatible_camera_formats() {514
if let Ok(formats) = camera.compatible_camera_formats() {418
let _ = camera.stop_stream();515
let _ = camera.stop_stream();419
drop(camera);516
drop(camera);420
if let Some(opened) = open_from_list(index.clone(), quality, &formats) {517
if let Some(opened) = open_from_list(index.clone(), windows_target, quality, &formats) {421
return Ok(opened);518
return Ok(opened);422
}519
}423
} else if let Some(opened) = accept_opened(&index, camera) {520
} else if let Some(opened) = accept_opened(&index, windows_target, camera) {424
return Ok(opened);521
return Ok(opened);425
}522
}426
}523
}@@ -429,7 +526,7 @@ fn open_camera(429
for candidate in preferred_candidates(quality) {526
for candidate in preferred_candidates(quality) {430
match try_exact_or_closest(index.clone(), candidate) {527
match try_exact_or_closest(index.clone(), candidate) {431
Ok(camera) => {528
Ok(camera) => {432
if let Some(opened) = accept_opened(&index, camera) {529
if let Some(opened) = accept_opened(&index, windows_target, camera) {433
return Ok(opened);530
return Ok(opened);434
}531
}435
}532
}@@ -440,7 +537,7 @@ fn open_camera(440
// Last resort: AbsoluteHighest may still yield a usable stream on odd backends.537
// Last resort: AbsoluteHighest may still yield a usable stream on odd backends.441
match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {538
match open_with_request(index.clone(), RequestedFormatType::AbsoluteHighestFrameRate) {442
Ok(camera) => {539
Ok(camera) => {443
tune_uvc_controls(&index);540
tune_uvc_controls(&index, windows_target);444
let label = format_label(&camera.camera_format());541
let label = format_label(&camera.camera_format());445
Ok((camera, label))542
Ok((camera, label))446
}543
}@@ -475,33 +572,25 @@ pub(crate) fn i420_from_nv12(data: &[u8], width: u32, height: u32) -> Option<I42475
}572
}476
573
477
pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {574
pub(crate) fn i420_from_yuyv(data: &[u8], width: u32, height: u32) -> Option<I420Buffer> {478
let (width_pixels, height_rows) = (width as usize, height as usize);575
let row_bytes = width as usize * 2;479
let row_bytes = width_pixels * 2;576
if data.len() < row_bytes * height as usize {480
if data.len() < row_bytes * height_rows {481
return None;577
return None;482
}578
}483
let mut buffer = I420Buffer::new(width, height);579
let mut buffer = I420Buffer::new(width, height);484
let (stride_y, stride_u, stride_v) = buffer.strides();580
let (stride_y, stride_u, stride_v) = buffer.strides();485
let (plane_y, plane_u, plane_v) = buffer.data_mut();581
let (plane_y, plane_u, plane_v) = buffer.data_mut();486
for row in 0..height_rows {582
yuy2_to_i420(487
let source = &data[row * row_bytes..(row + 1) * row_bytes];583
data,488
let luma_row = &mut plane_y[row * stride_y as usize..][..width_pixels];584
row_bytes as u32,489
for (luma, pair) in luma_row.chunks_exact_mut(2).zip(source.chunks_exact(4)) {585
plane_y,490
luma[0] = pair[0];586
stride_y,491
luma[1] = pair[2];587
plane_u,492
}588
stride_u,493
}589
plane_v,494
for row in 0..height_rows / 2 {590
stride_v,495
let upper = &data[row * 2 * row_bytes..][..row_bytes];591
width as i32,496
let lower = &data[(row * 2 + 1) * row_bytes..][..row_bytes];592
height as i32,497
let blue_row = &mut plane_u[row * stride_u as usize..][..width_pixels / 2];593
);498
let red_row = &mut plane_v[row * stride_v as usize..][..width_pixels / 2];499
for (column, (blue, red)) in blue_row.iter_mut().zip(red_row.iter_mut()).enumerate() {500
let offset = column * 4;501
*blue = ((u16::from(upper[offset + 1]) + u16::from(lower[offset + 1]) + 1) / 2) as u8;502
*red = ((u16::from(upper[offset + 3]) + u16::from(lower[offset + 3]) + 1) / 2) as u8;503
}504
}505
Some(buffer)594
Some(buffer)506
}595
}507
596
@@ -554,9 +643,9 @@ pub fn start_camera(554
deliver: impl FnMut(I420Buffer) + Send + 'static,643
deliver: impl FnMut(I420Buffer) + Send + 'static,555
failed: impl FnOnce(String) + Send + 'static,644
failed: impl FnOnce(String) + Send + 'static,556
) -> Result<Capture> {645
) -> Result<Capture> {557
let index = camera_index(choice);646
let (index, windows_target) = resolve_camera(choice);558
Capture::spawn_thread("camera", move |stop| {647
Capture::spawn_thread("camera", move |stop| {559
let (mut camera, label) = match open_camera(index, quality) {648
let (mut camera, label) = match open_camera(index, &windows_target, quality) {560
Ok(opened) => opened,649
Ok(opened) => opened,561
Err(error) => return failed(error.to_string()),650
Err(error) => return failed(error.to_string()),562
};651
};@@ -830,15 +919,15 @@ mod tests {830
#[test]919
#[test]831
fn camera_choices_map_to_indices_or_names() {920
fn camera_choices_map_to_indices_or_names() {832
assert!(matches!(921
assert!(matches!(833
camera_index(&DeviceChoice::SystemDefault),922
resolve_camera(&DeviceChoice::SystemDefault).0,834
CameraIndex::Index(0)923
CameraIndex::Index(_)835
));924
));836
assert!(matches!(925
assert!(matches!(837
camera_index(&DeviceChoice::Device("2".into())),926
resolve_camera(&DeviceChoice::Device("2".into())).0,838
CameraIndex::Index(2)927
CameraIndex::Index(2)839
));928
));840
assert!(matches!(929
assert!(matches!(841
camera_index(&DeviceChoice::Device("video0".into())),930
resolve_camera(&DeviceChoice::Device("video0".into())).0,842
CameraIndex::String(_)931
CameraIndex::String(_)843
));932
));844
}933
}@@ -895,7 +984,7 @@ mod tests {895
return;984
return;896
}985
}897
let (mut camera, label) =986
let (mut camera, label) =898
open_camera(CameraIndex::Index(0), VideoQuality::Auto).expect("camera opens");987
open_camera(CameraIndex::Index(0), "", VideoQuality::Auto).expect("camera opens");899
assert!(988
assert!(900
camera.camera_format().frame_rate() >= CAPTURE_FPS,989
camera.camera_format().frame_rate() >= CAPTURE_FPS,901
"opened {label} under 30 fps"990
"opened {label} under 30 fps"@@ -8,11 +8,24 @@ pub const DEVICE_CHANGE_QUIET: Duration = Duration::from_millis(500);
8
8
#[derive(Debug, Default)]
9
9
pub struct Debounce {
10
10
deadline: Option<Instant>,
11
touched_ids: Vec<String>,
11
12
}
12
13
13
14
impl Debounce {
14
15
pub fn signal(&mut self, now: Instant) {
16
self.signal_device(now, None);
17
}
18
19
pub fn signal_device(&mut self, now: Instant, device_id: Option<String>) {
15
20
self.deadline = Some(now + DEVICE_CHANGE_QUIET);
21
if let Some(id) = device_id
22
&& !self
23
.touched_ids
24
.iter()
25
.any(|existing| existing.eq_ignore_ascii_case(&id))
26
{
27
self.touched_ids.push(id);
28
}
16
29
}
17
30
18
31
pub fn deadline(&self) -> Option<Instant> {
@@ -20,11 +33,17 @@ impl Debounce {
20
33
}
21
34
22
35
pub fn take_due(&mut self, now: Instant) -> bool {
36
self.take_due_devices(now).is_some()
37
}
38
39
pub fn take_due_devices(&mut self, now: Instant) -> Option<Vec<String>> {
23
40
let due = self.deadline.is_some_and(|deadline| now >= deadline);
24
41
if due {
25
42
self.deadline = None;
43
Some(std::mem::take(&mut self.touched_ids))
44
} else {
45
None
26
46
}
27
due
28
47
}
29
48
}
30
49
@@ -33,7 +52,20 @@ pub struct DeviceWatcher {
33
52
_stop: std::sync::mpsc::Sender<()>,
34
53
}
35
54
36
pub fn watch() -> (DeviceWatcher, UnboundedReceiver<()>) {
55
pub fn endpoint_delta(previous: &[String], current: &[String]) -> Vec<String> {
56
let mut changed = Vec::new();
57
for id in previous.iter().chain(current.iter()) {
58
let before = previous.iter().any(|key| key.eq_ignore_ascii_case(id));
59
let after = current.iter().any(|key| key.eq_ignore_ascii_case(id));
60
let seen = changed.iter().any(|key: &String| key.eq_ignore_ascii_case(id));
61
if before != after && !seen {
62
changed.push(id.clone());
63
}
64
}
65
changed
66
}
67
68
pub fn watch() -> (DeviceWatcher, UnboundedReceiver<Option<String>>) {
37
69
let (sender, receiver) = unbounded_channel();
38
70
(platform::start(sender), receiver)
39
71
}
@@ -44,7 +76,7 @@ mod platform {
44
76
use windows::Win32::Foundation::PROPERTYKEY;
45
77
use windows::Win32::Media::Audio::{
46
78
DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient,
47
IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications,
79
IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications, eConsole,
48
80
};
49
81
use windows::Win32::System::Com::{
50
82
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,
@@ -54,28 +86,35 @@ mod platform {
54
86
55
87
use super::DeviceWatcher;
56
88
89
fn id_string(device_id: &PCWSTR) -> Option<String> {
90
if device_id.is_null() {
91
return None;
92
}
93
unsafe { device_id.to_string().ok() }.filter(|id| !id.is_empty())
94
}
95
57
96
#[implement(IMMNotificationClient)]
58
97
struct Client {
59
sender: UnboundedSender<()>,
98
sender: UnboundedSender<Option<String>>,
60
99
}
61
100
62
101
impl IMMNotificationClient_Impl for Client_Impl {
63
102
fn OnDeviceStateChanged(
64
103
&self,
65
_device_id: &PCWSTR,
104
device_id: &PCWSTR,
66
105
_state: DEVICE_STATE,
67
106
) -> windows::core::Result<()> {
68
let _ = self.sender.send(());
107
let _ = self.sender.send(id_string(device_id));
69
108
Ok(())
70
109
}
71
110
72
fn OnDeviceAdded(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {
73
let _ = self.sender.send(());
111
fn OnDeviceAdded(&self, device_id: &PCWSTR) -> windows::core::Result<()> {
112
let _ = self.sender.send(id_string(device_id));
74
113
Ok(())
75
114
}
76
115
77
fn OnDeviceRemoved(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {
78
let _ = self.sender.send(());
116
fn OnDeviceRemoved(&self, device_id: &PCWSTR) -> windows::core::Result<()> {
117
let _ = self.sender.send(id_string(device_id));
79
118
Ok(())
80
119
}
81
120
@@ -85,8 +124,8 @@ mod platform {
85
124
role: ERole,
86
125
_device_id: &PCWSTR,
87
126
) -> windows::core::Result<()> {
88
if role == eCommunications {
89
let _ = self.sender.send(());
127
if role == eConsole || role == eCommunications {
128
let _ = self.sender.send(None);
90
129
}
91
130
Ok(())
92
131
}
@@ -100,7 +139,7 @@ mod platform {
100
139
}
101
140
}
102
141
103
pub fn start(sender: UnboundedSender<()>) -> DeviceWatcher {
142
pub fn start(sender: UnboundedSender<Option<String>>) -> DeviceWatcher {
104
143
let (stop, stopped) = std::sync::mpsc::channel::<()>();
105
144
std::thread::spawn(move || unsafe {
106
145
let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
@@ -130,7 +169,7 @@ mod platform {
130
169
131
170
use super::DeviceWatcher;
132
171
133
pub fn start(_sender: UnboundedSender<()>) -> DeviceWatcher {
172
pub fn start(_sender: UnboundedSender<Option<String>>) -> DeviceWatcher {
134
173
DeviceWatcher {}
135
174
}
136
175
}
@@ -151,4 +190,40 @@ mod tests {
151
190
assert!(!debounce.take_due(start + Duration::from_millis(900)));
152
191
assert_eq!(debounce.deadline(), None);
153
192
}
193
194
#[test]
195
fn debounce_collects_unique_touched_device_ids() {
196
let start = Instant::now();
197
let mut debounce = Debounce::default();
198
debounce.signal_device(start, Some("{dev-a}".into()));
199
debounce.signal_device(start + Duration::from_millis(100), Some("{DEV-A}".into()));
200
debounce.signal_device(start + Duration::from_millis(200), None);
201
debounce.signal_device(start + Duration::from_millis(250), Some("{dev-b}".into()));
202
let ids = debounce
203
.take_due_devices(start + Duration::from_millis(800))
204
.expect("due");
205
assert_eq!(ids, vec!["{dev-a}".to_owned(), "{dev-b}".to_owned()]);
206
assert_eq!(
207
debounce.take_due_devices(start + Duration::from_millis(900)),
208
None
209
);
210
}
211
212
#[test]
213
fn a_device_that_leaves_and_returns_inside_the_quiet_period_is_one_event() {
214
let start = Instant::now();
215
let present = vec!["{headset}".to_owned()];
216
let gone = Vec::new();
217
let mut debounce = Debounce::default();
218
for id in endpoint_delta(&present, &gone) {
219
debounce.signal_device(start, Some(id));
220
}
221
for id in endpoint_delta(&gone, &present) {
222
debounce.signal_device(start + Duration::from_millis(200), Some(id));
223
}
224
assert_eq!(
225
debounce.take_due_devices(start + DEVICE_CHANGE_QUIET + Duration::from_millis(200)),
226
Some(vec!["{headset}".to_owned()])
227
);
228
}
154
229
}
@@ -8,11 +8,24 @@ pub const DEVICE_CHANGE_QUIET: Duration = Duration::from_millis(500);8
#[derive(Debug, Default)]8
#[derive(Debug, Default)]9
pub struct Debounce {9
pub struct Debounce {10
deadline: Option<Instant>,10
deadline: Option<Instant>,11
touched_ids: Vec<String>,11
}12
}12
13
13
impl Debounce {14
impl Debounce {14
pub fn signal(&mut self, now: Instant) {15
pub fn signal(&mut self, now: Instant) {16
self.signal_device(now, None);17
}18
19
pub fn signal_device(&mut self, now: Instant, device_id: Option<String>) {15
self.deadline = Some(now + DEVICE_CHANGE_QUIET);20
self.deadline = Some(now + DEVICE_CHANGE_QUIET);21
if let Some(id) = device_id22
&& !self23
.touched_ids24
.iter()25
.any(|existing| existing.eq_ignore_ascii_case(&id))26
{27
self.touched_ids.push(id);28
}16
}29
}17
30
18
pub fn deadline(&self) -> Option<Instant> {31
pub fn deadline(&self) -> Option<Instant> {@@ -20,11 +33,17 @@ impl Debounce {20
}33
}21
34
22
pub fn take_due(&mut self, now: Instant) -> bool {35
pub fn take_due(&mut self, now: Instant) -> bool {36
self.take_due_devices(now).is_some()37
}38
39
pub fn take_due_devices(&mut self, now: Instant) -> Option<Vec<String>> {23
let due = self.deadline.is_some_and(|deadline| now >= deadline);40
let due = self.deadline.is_some_and(|deadline| now >= deadline);24
if due {41
if due {25
self.deadline = None;42
self.deadline = None;43
Some(std::mem::take(&mut self.touched_ids))44
} else {45
None26
}46
}27
due28
}47
}29
}48
}30
49
@@ -33,7 +52,20 @@ pub struct DeviceWatcher {33
_stop: std::sync::mpsc::Sender<()>,52
_stop: std::sync::mpsc::Sender<()>,34
}53
}35
54
36
pub fn watch() -> (DeviceWatcher, UnboundedReceiver<()>) {55
pub fn endpoint_delta(previous: &[String], current: &[String]) -> Vec<String> {56
let mut changed = Vec::new();57
for id in previous.iter().chain(current.iter()) {58
let before = previous.iter().any(|key| key.eq_ignore_ascii_case(id));59
let after = current.iter().any(|key| key.eq_ignore_ascii_case(id));60
let seen = changed.iter().any(|key: &String| key.eq_ignore_ascii_case(id));61
if before != after && !seen {62
changed.push(id.clone());63
}64
}65
changed66
}67
68
pub fn watch() -> (DeviceWatcher, UnboundedReceiver<Option<String>>) {37
let (sender, receiver) = unbounded_channel();69
let (sender, receiver) = unbounded_channel();38
(platform::start(sender), receiver)70
(platform::start(sender), receiver)39
}71
}@@ -44,7 +76,7 @@ mod platform {44
use windows::Win32::Foundation::PROPERTYKEY;76
use windows::Win32::Foundation::PROPERTYKEY;45
use windows::Win32::Media::Audio::{77
use windows::Win32::Media::Audio::{46
DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient,78
DEVICE_STATE, EDataFlow, ERole, IMMDeviceEnumerator, IMMNotificationClient,47
IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications,79
IMMNotificationClient_Impl, MMDeviceEnumerator, eCommunications, eConsole,48
};80
};49
use windows::Win32::System::Com::{81
use windows::Win32::System::Com::{50
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,82
CLSCTX_ALL, COINIT_MULTITHREADED, CoCreateInstance, CoInitializeEx, CoUninitialize,@@ -54,28 +86,35 @@ mod platform {54
86
55
use super::DeviceWatcher;87
use super::DeviceWatcher;56
88
89
fn id_string(device_id: &PCWSTR) -> Option<String> {90
if device_id.is_null() {91
return None;92
}93
unsafe { device_id.to_string().ok() }.filter(|id| !id.is_empty())94
}95
57
#[implement(IMMNotificationClient)]96
#[implement(IMMNotificationClient)]58
struct Client {97
struct Client {59
sender: UnboundedSender<()>,98
sender: UnboundedSender<Option<String>>,60
}99
}61
100
62
impl IMMNotificationClient_Impl for Client_Impl {101
impl IMMNotificationClient_Impl for Client_Impl {63
fn OnDeviceStateChanged(102
fn OnDeviceStateChanged(64
&self,103
&self,65
_device_id: &PCWSTR,104
device_id: &PCWSTR,66
_state: DEVICE_STATE,105
_state: DEVICE_STATE,67
) -> windows::core::Result<()> {106
) -> windows::core::Result<()> {68
let _ = self.sender.send(());107
let _ = self.sender.send(id_string(device_id));69
Ok(())108
Ok(())70
}109
}71
110
72
fn OnDeviceAdded(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {111
fn OnDeviceAdded(&self, device_id: &PCWSTR) -> windows::core::Result<()> {73
let _ = self.sender.send(());112
let _ = self.sender.send(id_string(device_id));74
Ok(())113
Ok(())75
}114
}76
115
77
fn OnDeviceRemoved(&self, _device_id: &PCWSTR) -> windows::core::Result<()> {116
fn OnDeviceRemoved(&self, device_id: &PCWSTR) -> windows::core::Result<()> {78
let _ = self.sender.send(());117
let _ = self.sender.send(id_string(device_id));79
Ok(())118
Ok(())80
}119
}81
120
@@ -85,8 +124,8 @@ mod platform {85
role: ERole,124
role: ERole,86
_device_id: &PCWSTR,125
_device_id: &PCWSTR,87
) -> windows::core::Result<()> {126
) -> windows::core::Result<()> {88
if role == eCommunications {127
if role == eConsole || role == eCommunications {89
let _ = self.sender.send(());128
let _ = self.sender.send(None);90
}129
}91
Ok(())130
Ok(())92
}131
}@@ -100,7 +139,7 @@ mod platform {100
}139
}101
}140
}102
141
103
pub fn start(sender: UnboundedSender<()>) -> DeviceWatcher {142
pub fn start(sender: UnboundedSender<Option<String>>) -> DeviceWatcher {104
let (stop, stopped) = std::sync::mpsc::channel::<()>();143
let (stop, stopped) = std::sync::mpsc::channel::<()>();105
std::thread::spawn(move || unsafe {144
std::thread::spawn(move || unsafe {106
let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();145
let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();@@ -130,7 +169,7 @@ mod platform {130
169
131
use super::DeviceWatcher;170
use super::DeviceWatcher;132
171
133
pub fn start(_sender: UnboundedSender<()>) -> DeviceWatcher {172
pub fn start(_sender: UnboundedSender<Option<String>>) -> DeviceWatcher {134
DeviceWatcher {}173
DeviceWatcher {}135
}174
}136
}175
}@@ -151,4 +190,40 @@ mod tests {151
assert!(!debounce.take_due(start + Duration::from_millis(900)));190
assert!(!debounce.take_due(start + Duration::from_millis(900)));152
assert_eq!(debounce.deadline(), None);191
assert_eq!(debounce.deadline(), None);153
}192
}193
194
#[test]195
fn debounce_collects_unique_touched_device_ids() {196
let start = Instant::now();197
let mut debounce = Debounce::default();198
debounce.signal_device(start, Some("{dev-a}".into()));199
debounce.signal_device(start + Duration::from_millis(100), Some("{DEV-A}".into()));200
debounce.signal_device(start + Duration::from_millis(200), None);201
debounce.signal_device(start + Duration::from_millis(250), Some("{dev-b}".into()));202
let ids = debounce203
.take_due_devices(start + Duration::from_millis(800))204
.expect("due");205
assert_eq!(ids, vec!["{dev-a}".to_owned(), "{dev-b}".to_owned()]);206
assert_eq!(207
debounce.take_due_devices(start + Duration::from_millis(900)),208
None209
);210
}211
212
#[test]213
fn a_device_that_leaves_and_returns_inside_the_quiet_period_is_one_event() {214
let start = Instant::now();215
let present = vec!["{headset}".to_owned()];216
let gone = Vec::new();217
let mut debounce = Debounce::default();218
for id in endpoint_delta(&present, &gone) {219
debounce.signal_device(start, Some(id));220
}221
for id in endpoint_delta(&gone, &present) {222
debounce.signal_device(start + Duration::from_millis(200), Some(id));223
}224
assert_eq!(225
debounce.take_due_devices(start + DEVICE_CHANGE_QUIET + Duration::from_millis(200)),226
Some(vec!["{headset}".to_owned()])227
);228
}154
}229
}@@ -86,7 +86,8 @@ pub enum Flow {
86
86
Render,
87
87
}
88
88
89
/// Endpoint id of the Windows default communications device, which the ADM reports as the device guid.
89
/// Endpoint id of the Windows default audio device (preferring eConsole to match the Windows
90
/// taskbar switcher and AdmProxy::SystemDefaultFor, with fallback to eCommunications).
90
91
#[cfg(windows)]
91
92
pub fn system_default_id(flow: Flow) -> Option<String> {
92
93
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
@@ -101,7 +102,7 @@ pub fn system_default_id(flow: Flow) -> Option<String> {
101
102
#[cfg(windows)]
102
103
fn default_endpoint_id(flow: Flow) -> Option<String> {
103
104
use windows::Win32::Media::Audio::{
104
IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eRender,
105
IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eConsole, eRender,
105
106
};
106
107
use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
107
108
let data_flow = match flow {
@@ -112,7 +113,8 @@ fn default_endpoint_id(flow: Flow) -> Option<String> {
112
113
let enumerator: IMMDeviceEnumerator =
113
114
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
114
115
let device = enumerator
115
.GetDefaultAudioEndpoint(data_flow, eCommunications)
116
.GetDefaultAudioEndpoint(data_flow, eConsole)
117
.or_else(|_| enumerator.GetDefaultAudioEndpoint(data_flow, eCommunications))
116
118
.ok()?;
117
119
let id = device.GetId().ok()?;
118
120
let text = id.to_string().ok();
@@ -143,7 +145,7 @@ pub fn resolve_index(
143
145
.map(|device| device.index),
144
146
DeviceChoice::Device(key) => devices
145
147
.iter()
146
.find(|device| device.key() == *key)
148
.find(|device| device.key().eq_ignore_ascii_case(key))
147
149
.map(|device| device.index),
148
150
}
149
151
}
@@ -247,6 +249,21 @@ fn default_for(choice: &DeviceChoice, flow: Flow) -> Option<String> {
247
249
.flatten()
248
250
}
249
251
252
pub fn device_switch_applied(selected: bool, started: bool) -> bool {
253
selected && started
254
}
255
256
pub fn input_label(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> Option<String> {
257
let DeviceChoice::Device(key) = choice else {
258
return None;
259
};
260
enumerate(factory)
261
.inputs
262
.into_iter()
263
.find(|device| device.key().eq_ignore_ascii_case(key))
264
.map(|device| device.name)
265
}
266
250
267
pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
251
268
let Some(index) = resolve_index(
252
269
&enumerate(factory).inputs,
@@ -258,12 +275,37 @@ pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> b
258
275
select_input_index(factory, index)
259
276
}
260
277
278
#[cfg(windows)]
279
fn pause_for_endpoint_retry() {
280
let pause = || std::thread::sleep(std::time::Duration::from_millis(150));
281
if tokio::runtime::Handle::try_current().is_ok() {
282
tokio::task::block_in_place(pause);
283
} else {
284
pause();
285
}
286
}
287
261
288
pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {
262
289
factory.stop_recording();
263
290
let selected = factory.set_recording_device(index);
264
factory.init_recording();
265
factory.start_recording();
266
selected
291
let started = factory.init_recording() && factory.start_recording();
292
#[cfg(windows)]
293
let started = if selected && !started {
294
// Bluetooth headsets (HFP/A2DP profile switch) can momentarily reject Init/StartRecording.
295
pause_for_endpoint_retry();
296
factory.stop_recording();
297
let reselected = factory.set_recording_device(index);
298
reselected && factory.init_recording() && factory.start_recording()
299
} else {
300
started
301
};
302
#[cfg(windows)]
303
return device_switch_applied(selected, started);
304
#[cfg(not(windows))]
305
{
306
let _ = started;
307
selected
308
}
267
309
}
268
310
269
311
pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
@@ -280,9 +322,24 @@ pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) ->
280
322
pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {
281
323
factory.stop_playout();
282
324
let selected = factory.set_playout_device(index);
283
factory.init_playout();
284
factory.start_playout();
285
selected
325
let started = factory.init_playout() && factory.start_playout();
326
#[cfg(windows)]
327
let started = if selected && !started {
328
// Retry once after Bluetooth A2DP/HFP endpoint renegotiation settles.
329
pause_for_endpoint_retry();
330
factory.stop_playout();
331
let reselected = factory.set_playout_device(index);
332
reselected && factory.init_playout() && factory.start_playout()
333
} else {
334
started
335
};
336
#[cfg(windows)]
337
return device_switch_applied(selected, started);
338
#[cfg(not(windows))]
339
{
340
let _ = started;
341
selected
342
}
286
343
}
287
344
288
345
#[cfg(test)]
@@ -397,6 +454,21 @@ mod tests {
397
454
),
398
455
Some(0)
399
456
);
457
assert_eq!(
458
resolve_index(
459
&devices,
460
&DeviceChoice::Device("{0.0.0.00000000}.{BBBB}".into()),
461
None
462
),
463
Some(1)
464
);
465
}
466
467
#[test]
468
fn a_device_switch_counts_only_when_audio_starts() {
469
assert!(!device_switch_applied(true, false));
470
assert!(device_switch_applied(true, true));
471
assert!(!device_switch_applied(false, true));
400
472
}
401
473
402
474
fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {
@@ -86,7 +86,8 @@ pub enum Flow {86
Render,86
Render,87
}87
}88
88
89
/// Endpoint id of the Windows default communications device, which the ADM reports as the device guid.89
/// Endpoint id of the Windows default audio device (preferring eConsole to match the Windows90
/// taskbar switcher and AdmProxy::SystemDefaultFor, with fallback to eCommunications).90
#[cfg(windows)]91
#[cfg(windows)]91
pub fn system_default_id(flow: Flow) -> Option<String> {92
pub fn system_default_id(flow: Flow) -> Option<String> {92
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};93
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};@@ -101,7 +102,7 @@ pub fn system_default_id(flow: Flow) -> Option<String> {101
#[cfg(windows)]102
#[cfg(windows)]102
fn default_endpoint_id(flow: Flow) -> Option<String> {103
fn default_endpoint_id(flow: Flow) -> Option<String> {103
use windows::Win32::Media::Audio::{104
use windows::Win32::Media::Audio::{104
IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eRender,105
IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eCommunications, eConsole, eRender,105
};106
};106
use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};107
use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};107
let data_flow = match flow {108
let data_flow = match flow {@@ -112,7 +113,8 @@ fn default_endpoint_id(flow: Flow) -> Option<String> {112
let enumerator: IMMDeviceEnumerator =113
let enumerator: IMMDeviceEnumerator =113
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;114
CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;114
let device = enumerator115
let device = enumerator115
.GetDefaultAudioEndpoint(data_flow, eCommunications)116
.GetDefaultAudioEndpoint(data_flow, eConsole)117
.or_else(|_| enumerator.GetDefaultAudioEndpoint(data_flow, eCommunications))116
.ok()?;118
.ok()?;117
let id = device.GetId().ok()?;119
let id = device.GetId().ok()?;118
let text = id.to_string().ok();120
let text = id.to_string().ok();@@ -143,7 +145,7 @@ pub fn resolve_index(143
.map(|device| device.index),145
.map(|device| device.index),144
DeviceChoice::Device(key) => devices146
DeviceChoice::Device(key) => devices145
.iter()147
.iter()146
.find(|device| device.key() == *key)148
.find(|device| device.key().eq_ignore_ascii_case(key))147
.map(|device| device.index),149
.map(|device| device.index),148
}150
}149
}151
}@@ -247,6 +249,21 @@ fn default_for(choice: &DeviceChoice, flow: Flow) -> Option<String> {247
.flatten()249
.flatten()248
}250
}249
251
252
pub fn device_switch_applied(selected: bool, started: bool) -> bool {253
selected && started254
}255
256
pub fn input_label(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> Option<String> {257
let DeviceChoice::Device(key) = choice else {258
return None;259
};260
enumerate(factory)261
.inputs262
.into_iter()263
.find(|device| device.key().eq_ignore_ascii_case(key))264
.map(|device| device.name)265
}266
250
pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {267
pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {251
let Some(index) = resolve_index(268
let Some(index) = resolve_index(252
&enumerate(factory).inputs,269
&enumerate(factory).inputs,@@ -258,12 +275,37 @@ pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> b258
select_input_index(factory, index)275
select_input_index(factory, index)259
}276
}260
277
278
#[cfg(windows)]279
fn pause_for_endpoint_retry() {280
let pause = || std::thread::sleep(std::time::Duration::from_millis(150));281
if tokio::runtime::Handle::try_current().is_ok() {282
tokio::task::block_in_place(pause);283
} else {284
pause();285
}286
}287
261
pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {288
pub fn select_input_index(factory: &PeerConnectionFactory, index: u16) -> bool {262
factory.stop_recording();289
factory.stop_recording();263
let selected = factory.set_recording_device(index);290
let selected = factory.set_recording_device(index);264
factory.init_recording();291
let started = factory.init_recording() && factory.start_recording();265
factory.start_recording();292
#[cfg(windows)]266
selected293
let started = if selected && !started {294
// Bluetooth headsets (HFP/A2DP profile switch) can momentarily reject Init/StartRecording.295
pause_for_endpoint_retry();296
factory.stop_recording();297
let reselected = factory.set_recording_device(index);298
reselected && factory.init_recording() && factory.start_recording()299
} else {300
started301
};302
#[cfg(windows)]303
return device_switch_applied(selected, started);304
#[cfg(not(windows))]305
{306
let _ = started;307
selected308
}267
}309
}268
310
269
pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {311
pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {@@ -280,9 +322,24 @@ pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) ->280
pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {322
pub fn select_output_index(factory: &PeerConnectionFactory, index: u16) -> bool {281
factory.stop_playout();323
factory.stop_playout();282
let selected = factory.set_playout_device(index);324
let selected = factory.set_playout_device(index);283
factory.init_playout();325
let started = factory.init_playout() && factory.start_playout();284
factory.start_playout();326
#[cfg(windows)]285
selected327
let started = if selected && !started {328
// Retry once after Bluetooth A2DP/HFP endpoint renegotiation settles.329
pause_for_endpoint_retry();330
factory.stop_playout();331
let reselected = factory.set_playout_device(index);332
reselected && factory.init_playout() && factory.start_playout()333
} else {334
started335
};336
#[cfg(windows)]337
return device_switch_applied(selected, started);338
#[cfg(not(windows))]339
{340
let _ = started;341
selected342
}286
}343
}287
344
288
#[cfg(test)]345
#[cfg(test)]@@ -397,6 +454,21 @@ mod tests {397
),454
),398
Some(0)455
Some(0)399
);456
);457
assert_eq!(458
resolve_index(459
&devices,460
&DeviceChoice::Device("{0.0.0.00000000}.{BBBB}".into()),461
None462
),463
Some(1)464
);465
}466
467
#[test]468
fn a_device_switch_counts_only_when_audio_starts() {469
assert!(!device_switch_applied(true, false));470
assert!(device_switch_applied(true, true));471
assert!(!device_switch_applied(false, true));400
}472
}401
473
402
fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {474
fn headset_lists() -> (Vec<AudioDevice>, Vec<AudioDevice>) {@@ -17,6 +17,7 @@ use crate::control::{CallControl, CallHandle, call_channel};
17
17
use crate::devices::DeviceChoice;
18
18
use crate::end::EndKind;
19
19
use crate::error::{Error, Result};
20
use crate::mic_processing::MicSettings;
20
21
use crate::push::{CallNotification, Caller, PushEvent, decode_push};
21
22
use crate::relay::{DEFAULT_RELAY_HOST, RelayCache};
22
23
use crate::signaling::{
@@ -152,6 +153,7 @@ pub(crate) struct Inner {
152
153
seen: Mutex<HashMap<(String, String), Instant>>,
153
154
next_ring_id: AtomicU64,
154
155
default_camera: Mutex<DeviceChoice>,
156
default_mic: Mutex<MicSettings>,
155
157
runtime: tokio::runtime::Handle,
156
158
events: mpsc::UnboundedSender<EngineEvent>,
157
159
stop: Mutex<Option<oneshot::Sender<()>>>,
@@ -220,6 +222,7 @@ impl Inner {
220
222
.lock()
221
223
.expect("default camera lock")
222
224
.clone(),
225
mic: *self.default_mic.lock().expect("default mic lock"),
223
226
..CallOptions::default()
224
227
}
225
228
}
@@ -332,6 +335,7 @@ impl CallEngine {
332
335
next_ring_id: AtomicU64::new(RING_ID_START),
333
336
relay: RelayCache::default(),
334
337
default_camera: Mutex::new(DeviceChoice::SystemDefault),
338
default_mic: Mutex::new(MicSettings::default()),
335
339
runtime: tokio::runtime::Handle::current(),
336
340
events,
337
341
stop: Mutex::new(Some(stop)),
@@ -413,6 +417,10 @@ impl CallEngine {
413
417
.expect("default camera lock") = camera;
414
418
}
415
419
420
pub fn set_default_mic(&self, mic: MicSettings) {
421
*self.inner.default_mic.lock().expect("default mic lock") = mic;
422
}
423
416
424
pub fn decline_ring(&self, ring_id: u64) {
417
425
self.send_ring_command(ring_id, RingCommand::Decline);
418
426
}
@@ -17,6 +17,7 @@ use crate::control::{CallControl, CallHandle, call_channel};17
use crate::devices::DeviceChoice;17
use crate::devices::DeviceChoice;18
use crate::end::EndKind;18
use crate::end::EndKind;19
use crate::error::{Error, Result};19
use crate::error::{Error, Result};20
use crate::mic_processing::MicSettings;20
use crate::push::{CallNotification, Caller, PushEvent, decode_push};21
use crate::push::{CallNotification, Caller, PushEvent, decode_push};21
use crate::relay::{DEFAULT_RELAY_HOST, RelayCache};22
use crate::relay::{DEFAULT_RELAY_HOST, RelayCache};22
use crate::signaling::{23
use crate::signaling::{@@ -152,6 +153,7 @@ pub(crate) struct Inner {152
seen: Mutex<HashMap<(String, String), Instant>>,153
seen: Mutex<HashMap<(String, String), Instant>>,153
next_ring_id: AtomicU64,154
next_ring_id: AtomicU64,154
default_camera: Mutex<DeviceChoice>,155
default_camera: Mutex<DeviceChoice>,156
default_mic: Mutex<MicSettings>,155
runtime: tokio::runtime::Handle,157
runtime: tokio::runtime::Handle,156
events: mpsc::UnboundedSender<EngineEvent>,158
events: mpsc::UnboundedSender<EngineEvent>,157
stop: Mutex<Option<oneshot::Sender<()>>>,159
stop: Mutex<Option<oneshot::Sender<()>>>,@@ -220,6 +222,7 @@ impl Inner {220
.lock()222
.lock()221
.expect("default camera lock")223
.expect("default camera lock")222
.clone(),224
.clone(),225
mic: *self.default_mic.lock().expect("default mic lock"),223
..CallOptions::default()226
..CallOptions::default()224
}227
}225
}228
}@@ -332,6 +335,7 @@ impl CallEngine {332
next_ring_id: AtomicU64::new(RING_ID_START),335
next_ring_id: AtomicU64::new(RING_ID_START),333
relay: RelayCache::default(),336
relay: RelayCache::default(),334
default_camera: Mutex::new(DeviceChoice::SystemDefault),337
default_camera: Mutex::new(DeviceChoice::SystemDefault),338
default_mic: Mutex::new(MicSettings::default()),335
runtime: tokio::runtime::Handle::current(),339
runtime: tokio::runtime::Handle::current(),336
events,340
events,337
stop: Mutex::new(Some(stop)),341
stop: Mutex::new(Some(stop)),@@ -413,6 +417,10 @@ impl CallEngine {413
.expect("default camera lock") = camera;417
.expect("default camera lock") = camera;414
}418
}415
419
420
pub fn set_default_mic(&self, mic: MicSettings) {421
*self.inner.default_mic.lock().expect("default mic lock") = mic;422
}423
416
pub fn decline_ring(&self, ring_id: u64) {424
pub fn decline_ring(&self, ring_id: u64) {417
self.send_ring_command(ring_id, RingCommand::Decline);425
self.send_ring_command(ring_id, RingCommand::Decline);418
}426
}@@ -4,12 +4,14 @@ use webrtc_sys::apm::GainProcessor;
4
4
5
5
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
6
6
7
/// Start flat; quiet mics climb through adaptive AGC2 instead of blasting a hot PipeWire input.
7
/// Start flat; quiet mics climb through adaptive AGC2 instead of blasting a hot input.
8
8
const LIFT_DEFAULT_GAIN_DB: f32 = 0.0;
9
9
const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;
10
const OUTPUT_FIXED_GAIN_DB: f32 = 8.0;
11
/// Only restore DeepFilterNet's level drop when the post-filter frame is still quiet.
12
const OUTPUT_APPLY_BELOW_DBFS: f32 = -25.0;
10
const OUTPUT_MAX_GAIN_DB: f32 = 6.0;
11
/// Smooth knee for post-filter level recovery: full boost below -32 dBFS, 0 dB above -18 dBFS.
12
const OUTPUT_FULL_BOOST_DBFS: f32 = -32.0;
13
const OUTPUT_UNITY_DBFS: f32 = -18.0;
14
const OUTPUT_SMOOTH_ALPHA: f32 = 0.15;
13
15
const SPEECH_FLOOR_DBFS: f32 = -55.0;
14
16
const MIN_SPEECH_FRAMES: u32 = 100;
15
17
@@ -24,12 +26,24 @@ fn frame_dbfs(frame: &[i16]) -> f32 {
24
26
10.0 * (mean_square / 32768.0_f32.powi(2) + 1e-12).log10()
25
27
}
26
28
27
/// One AGC2 (optional adaptive digital gain, then fixed gain, then its limiter) on 10 ms mono frames.
29
fn target_output_gain_db(input_dbfs: f32) -> f32 {
30
if input_dbfs >= OUTPUT_UNITY_DBFS {
31
0.0
32
} else if input_dbfs <= OUTPUT_FULL_BOOST_DBFS {
33
OUTPUT_MAX_GAIN_DB
34
} else {
35
let ratio = (OUTPUT_UNITY_DBFS - input_dbfs) / (OUTPUT_UNITY_DBFS - OUTPUT_FULL_BOOST_DBFS);
36
OUTPUT_MAX_GAIN_DB * ratio
37
}
38
}
39
40
/// One AGC2 (optional adaptive digital gain, or smooth output makeup with limiter) on 10 ms mono frames.
28
41
pub struct GainStage {
29
42
module: GainProcessor,
30
43
measured_gain_db_sum: f32,
31
44
measured_frames: u32,
32
45
learns: bool,
46
smoothed_gain_db: f32,
33
47
}
34
48
35
49
impl GainStage {
@@ -45,9 +59,9 @@ impl GainStage {
45
59
)
46
60
}
47
61
48
/// Last stage, fixed: makes up the level DeepFilterNet takes off and limits peaks; a second adaptive stage pumps against the first.
62
/// Last stage: smoothly recovers level lost to DeepFilterNet and limits peaks without hard-threshold step jumps.
49
63
pub fn output() -> GainStage {
50
GainStage::new(false, 0.0, OUTPUT_FIXED_GAIN_DB, 1.0, false)
64
GainStage::new(false, 0.0, 0.0, 1.0, false)
51
65
}
52
66
53
67
fn new(
@@ -67,6 +81,7 @@ impl GainStage {
67
81
measured_gain_db_sum: 0.0,
68
82
measured_frames: 0,
69
83
learns,
84
smoothed_gain_db: 0.0,
70
85
}
71
86
}
72
87
@@ -75,11 +90,27 @@ impl GainStage {
75
90
return;
76
91
}
77
92
let input_dbfs = frame_dbfs(frame);
78
if !self.learns && input_dbfs > OUTPUT_APPLY_BELOW_DBFS {
93
if !self.learns {
94
let target_db = target_output_gain_db(input_dbfs);
95
let prev_gain = 10.0_f32.powf(self.smoothed_gain_db / 20.0);
96
self.smoothed_gain_db += (target_db - self.smoothed_gain_db) * OUTPUT_SMOOTH_ALPHA;
97
let next_gain = 10.0_f32.powf(self.smoothed_gain_db / 20.0);
98
if self.smoothed_gain_db > 0.05 || (next_gain - prev_gain).abs() > 1e-4 {
99
let len = frame.len() as f32;
100
for (index, sample) in frame.iter_mut().enumerate() {
101
let t = (index as f32 + 1.0) / len;
102
let gain = prev_gain + (next_gain - prev_gain) * t;
103
*sample = (f32::from(*sample) * gain)
104
.round()
105
.clamp(f32::from(i16::MIN), f32::from(i16::MAX))
106
as i16;
107
}
108
let _ = self.module.process(frame, SAMPLE_RATE as i32);
109
}
79
110
return;
80
111
}
81
112
let processed = self.module.process(frame, SAMPLE_RATE as i32);
82
if processed && self.learns && input_dbfs > SPEECH_FLOOR_DBFS {
113
if processed && input_dbfs > SPEECH_FLOOR_DBFS {
83
114
self.measured_gain_db_sum += frame_dbfs(frame) - input_dbfs;
84
115
self.measured_frames += 1;
85
116
}
@@ -114,21 +145,26 @@ mod tests {
114
145
#[test]
115
146
fn the_fixed_output_stage_adds_its_gain_only_to_quiet_frames() {
116
147
let mut stage = GainStage::output();
117
let mut quiet: Vec<i16> = (0..FRAME_SAMPLES)
148
let quiet_template: Vec<i16> = (0..FRAME_SAMPLES)
118
149
.map(|sample| ((sample as f32 * 0.04).sin() * 200.0) as i16)
119
150
.collect();
120
let before = frame_dbfs(&quiet);
121
stage.process(&mut quiet);
151
let before = frame_dbfs(&quiet_template);
152
let mut quiet = quiet_template.clone();
153
for _ in 0..30 {
154
quiet = quiet_template.clone();
155
stage.process(&mut quiet);
156
}
122
157
assert!(
123
frame_dbfs(&quiet) - before > 6.0,
124
"quiet speech should be lifted"
158
frame_dbfs(&quiet) - before > 4.5,
159
"quiet speech should be lifted smoothly"
125
160
);
126
161
162
let mut fresh_stage = GainStage::output();
127
163
let mut loud: Vec<i16> = (0..FRAME_SAMPLES)
128
164
.map(|sample| ((sample as f32 * 0.04).sin() * 8000.0) as i16)
129
165
.collect();
130
166
let loud_before = loud.clone();
131
stage.process(&mut loud);
167
fresh_stage.process(&mut loud);
132
168
assert_eq!(loud, loud_before, "already-loud frames stay untouched");
133
169
}
134
170
@@ -4,12 +4,14 @@ use webrtc_sys::apm::GainProcessor;4
4
5
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};5
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};6
6
7
/// Start flat; quiet mics climb through adaptive AGC2 instead of blasting a hot PipeWire input.7
/// Start flat; quiet mics climb through adaptive AGC2 instead of blasting a hot input.8
const LIFT_DEFAULT_GAIN_DB: f32 = 0.0;8
const LIFT_DEFAULT_GAIN_DB: f32 = 0.0;9
const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;9
const LIFT_GAIN_CHANGE_DB_PER_SECOND: f32 = 6.0;10
const OUTPUT_FIXED_GAIN_DB: f32 = 8.0;10
const OUTPUT_MAX_GAIN_DB: f32 = 6.0;11
/// Only restore DeepFilterNet's level drop when the post-filter frame is still quiet.11
/// Smooth knee for post-filter level recovery: full boost below -32 dBFS, 0 dB above -18 dBFS.12
const OUTPUT_APPLY_BELOW_DBFS: f32 = -25.0;12
const OUTPUT_FULL_BOOST_DBFS: f32 = -32.0;13
const OUTPUT_UNITY_DBFS: f32 = -18.0;14
const OUTPUT_SMOOTH_ALPHA: f32 = 0.15;13
const SPEECH_FLOOR_DBFS: f32 = -55.0;15
const SPEECH_FLOOR_DBFS: f32 = -55.0;14
const MIN_SPEECH_FRAMES: u32 = 100;16
const MIN_SPEECH_FRAMES: u32 = 100;15
17
@@ -24,12 +26,24 @@ fn frame_dbfs(frame: &[i16]) -> f32 {24
10.0 * (mean_square / 32768.0_f32.powi(2) + 1e-12).log10()26
10.0 * (mean_square / 32768.0_f32.powi(2) + 1e-12).log10()25
}27
}26
28
27
/// One AGC2 (optional adaptive digital gain, then fixed gain, then its limiter) on 10 ms mono frames.29
fn target_output_gain_db(input_dbfs: f32) -> f32 {30
if input_dbfs >= OUTPUT_UNITY_DBFS {31
0.032
} else if input_dbfs <= OUTPUT_FULL_BOOST_DBFS {33
OUTPUT_MAX_GAIN_DB34
} else {35
let ratio = (OUTPUT_UNITY_DBFS - input_dbfs) / (OUTPUT_UNITY_DBFS - OUTPUT_FULL_BOOST_DBFS);36
OUTPUT_MAX_GAIN_DB * ratio37
}38
}39
40
/// One AGC2 (optional adaptive digital gain, or smooth output makeup with limiter) on 10 ms mono frames.28
pub struct GainStage {41
pub struct GainStage {29
module: GainProcessor,42
module: GainProcessor,30
measured_gain_db_sum: f32,43
measured_gain_db_sum: f32,31
measured_frames: u32,44
measured_frames: u32,32
learns: bool,45
learns: bool,46
smoothed_gain_db: f32,33
}47
}34
48
35
impl GainStage {49
impl GainStage {@@ -45,9 +59,9 @@ impl GainStage {45
)59
)46
}60
}47
61
48
/// Last stage, fixed: makes up the level DeepFilterNet takes off and limits peaks; a second adaptive stage pumps against the first.62
/// Last stage: smoothly recovers level lost to DeepFilterNet and limits peaks without hard-threshold step jumps.49
pub fn output() -> GainStage {63
pub fn output() -> GainStage {50
GainStage::new(false, 0.0, OUTPUT_FIXED_GAIN_DB, 1.0, false)64
GainStage::new(false, 0.0, 0.0, 1.0, false)51
}65
}52
66
53
fn new(67
fn new(@@ -67,6 +81,7 @@ impl GainStage {67
measured_gain_db_sum: 0.0,81
measured_gain_db_sum: 0.0,68
measured_frames: 0,82
measured_frames: 0,69
learns,83
learns,84
smoothed_gain_db: 0.0,70
}85
}71
}86
}72
87
@@ -75,11 +90,27 @@ impl GainStage {75
return;90
return;76
}91
}77
let input_dbfs = frame_dbfs(frame);92
let input_dbfs = frame_dbfs(frame);78
if !self.learns && input_dbfs > OUTPUT_APPLY_BELOW_DBFS {93
if !self.learns {94
let target_db = target_output_gain_db(input_dbfs);95
let prev_gain = 10.0_f32.powf(self.smoothed_gain_db / 20.0);96
self.smoothed_gain_db += (target_db - self.smoothed_gain_db) * OUTPUT_SMOOTH_ALPHA;97
let next_gain = 10.0_f32.powf(self.smoothed_gain_db / 20.0);98
if self.smoothed_gain_db > 0.05 || (next_gain - prev_gain).abs() > 1e-4 {99
let len = frame.len() as f32;100
for (index, sample) in frame.iter_mut().enumerate() {101
let t = (index as f32 + 1.0) / len;102
let gain = prev_gain + (next_gain - prev_gain) * t;103
*sample = (f32::from(*sample) * gain)104
.round()105
.clamp(f32::from(i16::MIN), f32::from(i16::MAX))106
as i16;107
}108
let _ = self.module.process(frame, SAMPLE_RATE as i32);109
}79
return;110
return;80
}111
}81
let processed = self.module.process(frame, SAMPLE_RATE as i32);112
let processed = self.module.process(frame, SAMPLE_RATE as i32);82
if processed && self.learns && input_dbfs > SPEECH_FLOOR_DBFS {113
if processed && input_dbfs > SPEECH_FLOOR_DBFS {83
self.measured_gain_db_sum += frame_dbfs(frame) - input_dbfs;114
self.measured_gain_db_sum += frame_dbfs(frame) - input_dbfs;84
self.measured_frames += 1;115
self.measured_frames += 1;85
}116
}@@ -114,21 +145,26 @@ mod tests {114
#[test]145
#[test]115
fn the_fixed_output_stage_adds_its_gain_only_to_quiet_frames() {146
fn the_fixed_output_stage_adds_its_gain_only_to_quiet_frames() {116
let mut stage = GainStage::output();147
let mut stage = GainStage::output();117
let mut quiet: Vec<i16> = (0..FRAME_SAMPLES)148
let quiet_template: Vec<i16> = (0..FRAME_SAMPLES)118
.map(|sample| ((sample as f32 * 0.04).sin() * 200.0) as i16)149
.map(|sample| ((sample as f32 * 0.04).sin() * 200.0) as i16)119
.collect();150
.collect();120
let before = frame_dbfs(&quiet);151
let before = frame_dbfs(&quiet_template);121
stage.process(&mut quiet);152
let mut quiet = quiet_template.clone();153
for _ in 0..30 {154
quiet = quiet_template.clone();155
stage.process(&mut quiet);156
}122
assert!(157
assert!(123
frame_dbfs(&quiet) - before > 6.0,158
frame_dbfs(&quiet) - before > 4.5,124
"quiet speech should be lifted"159
"quiet speech should be lifted smoothly"125
);160
);126
161
162
let mut fresh_stage = GainStage::output();127
let mut loud: Vec<i16> = (0..FRAME_SAMPLES)163
let mut loud: Vec<i16> = (0..FRAME_SAMPLES)128
.map(|sample| ((sample as f32 * 0.04).sin() * 8000.0) as i16)164
.map(|sample| ((sample as f32 * 0.04).sin() * 8000.0) as i16)129
.collect();165
.collect();130
let loud_before = loud.clone();166
let loud_before = loud.clone();131
stage.process(&mut loud);167
fresh_stage.process(&mut loud);132
assert_eq!(loud, loud_before, "already-loud frames stay untouched");168
assert_eq!(loud, loud_before, "already-loud frames stay untouched");133
}169
}134
170
@@ -81,6 +81,7 @@ pub mod video_send;
81
81
pub mod voice_high_pass;
82
82
pub mod wav_dump;
83
83
pub mod whiteboard;
84
pub(crate) mod win_timer;
84
85
85
86
pub use audio_io::AudioMode;
86
87
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};
@@ -81,6 +81,7 @@ pub mod video_send;81
pub mod voice_high_pass;81
pub mod voice_high_pass;82
pub mod wav_dump;82
pub mod wav_dump;83
pub mod whiteboard;83
pub mod whiteboard;84
pub(crate) mod win_timer;84
85
85
pub use audio_io::AudioMode;86
pub use audio_io::AudioMode;86
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};87
pub use background::{BackgroundCache, BackgroundChoice, BackgroundPicture, DefaultBackground};@@ -5,8 +5,7 @@ use std::time::Duration;
5
5
use windows::Win32::Foundation::{CloseHandle, E_FAIL, HANDLE, WAIT_OBJECT_0};
6
6
use windows::Win32::Media::Audio::{
7
7
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
8
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK,
9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,
8
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK, AUDIOCLIENT_ACTIVATION_PARAMS,
10
9
AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,
11
10
AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, ActivateAudioInterfaceAsync,
12
11
IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,
@@ -120,8 +119,7 @@ fn initialise(client: &IAudioClient) -> Result<(IAudioCaptureClient, HANDLE)> {
120
119
};
121
120
let flags = AUDCLNT_STREAMFLAGS_LOOPBACK
122
121
| AUDCLNT_STREAMFLAGS_EVENTCALLBACK
123
| AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
124
| AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
122
| AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;
125
123
unsafe {
126
124
client
127
125
.Initialize(
@@ -5,8 +5,7 @@ use std::time::Duration;5
use windows::Win32::Foundation::{CloseHandle, E_FAIL, HANDLE, WAIT_OBJECT_0};5
use windows::Win32::Foundation::{CloseHandle, E_FAIL, HANDLE, WAIT_OBJECT_0};6
use windows::Win32::Media::Audio::{6
use windows::Win32::Media::Audio::{7
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,7
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,8
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK,8
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_LOOPBACK, AUDIOCLIENT_ACTIVATION_PARAMS,9
AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY, AUDIOCLIENT_ACTIVATION_PARAMS,10
AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,9
AUDIOCLIENT_ACTIVATION_PARAMS_0, AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK,11
AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, ActivateAudioInterfaceAsync,10
AUDIOCLIENT_PROCESS_LOOPBACK_PARAMS, ActivateAudioInterfaceAsync,12
IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,11
IActivateAudioInterfaceAsyncOperation, IActivateAudioInterfaceCompletionHandler,@@ -120,8 +119,7 @@ fn initialise(client: &IAudioClient) -> Result<(IAudioCaptureClient, HANDLE)> {120
};119
};121
let flags = AUDCLNT_STREAMFLAGS_LOOPBACK120
let flags = AUDCLNT_STREAMFLAGS_LOOPBACK122
| AUDCLNT_STREAMFLAGS_EVENTCALLBACK121
| AUDCLNT_STREAMFLAGS_EVENTCALLBACK123
| AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM122
| AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;124
| AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;125
unsafe {123
unsafe {126
client124
client127
.Initialize(125
.Initialize(@@ -56,6 +56,7 @@ impl MicChain {
56
56
high_pass.process(frame);
57
57
}
58
58
if let Some(front) = self.front.as_mut() {
59
let _ = front.set_stream_delay_ms(40);
59
60
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);
60
61
}
61
62
self.dump(2, frame);
@@ -56,6 +56,7 @@ impl MicChain {56
high_pass.process(frame);56
high_pass.process(frame);57
}57
}58
if let Some(front) = self.front.as_mut() {58
if let Some(front) = self.front.as_mut() {59
let _ = front.set_stream_delay_ms(40);59
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);60
let _ = front.process_stream(frame, SAMPLE_RATE as i32, 1);60
}61
}61
self.dump(2, frame);62
self.dump(2, frame);@@ -89,16 +89,12 @@ impl MicSettings {
89
89
}
90
90
}
91
91
92
/// Auto and Low use the native WebRTC platform ADM device track on every desktop OS
93
/// (WASAPI2/CoreAudio on Windows, Pulse/PipeWire on Linux, CoreAudio on macOS), matching
94
/// Web Teams and avoiding software-feeder jitter and unsynchronized AEC.
95
/// Music mode and Off run the software chain.
92
96
pub fn uses_device_track(self) -> bool {
93
self.uses_device_track_on(cfg!(windows))
94
}
95
96
/// On Linux and macOS, Auto and Low keep the platform ADM device track
97
/// (Pulse / CoreAudio — same path Web Teams uses). Music mode and Off still
98
/// run the software chain; Windows always does.
99
pub fn uses_device_track_on(self, windows: bool) -> bool {
100
!windows
101
&& !self.music_mode
97
!self.music_mode
102
98
&& matches!(
103
99
self.noise_suppression,
104
100
NoiseSuppression::Auto | NoiseSuppression::Low
@@ -115,11 +111,9 @@ mod tests {
115
111
use super::*;
116
112
117
113
#[test]
118
fn auto_uses_the_device_track_on_linux_and_macos_and_keeps_ml_for_the_windows_chain() {
114
fn auto_uses_the_device_track_on_all_platforms() {
119
115
let settings = MicSettings::default();
120
// Non-Windows (Pulse on Linux, CoreAudio on macOS) keeps the ADM track.
121
assert!(settings.uses_device_track_on(false));
122
assert!(!settings.uses_device_track_on(true));
116
assert!(settings.uses_device_track());
123
117
assert!(settings.ml_noise_suppression());
124
118
assert_eq!(
125
119
settings.apm_config(),
@@ -133,12 +127,12 @@ mod tests {
133
127
}
134
128
135
129
#[test]
136
fn low_keeps_the_coreaudio_or_pulse_device_track_with_the_apm_noise_suppression() {
130
fn low_keeps_the_platform_device_track_with_apm_noise_suppression() {
137
131
let settings = MicSettings {
138
132
noise_suppression: NoiseSuppression::Low,
139
133
music_mode: false,
140
134
};
141
assert!(settings.uses_device_track_on(false));
135
assert!(settings.uses_device_track());
142
136
assert!(!settings.ml_noise_suppression());
143
137
assert_eq!(
144
138
settings.apm_config(),
@@ -170,25 +164,6 @@ mod tests {
170
164
);
171
165
}
172
166
173
#[test]
174
fn windows_never_uses_the_device_track() {
175
for noise_suppression in NoiseSuppression::ALL {
176
for music_mode in [false, true] {
177
let settings = MicSettings {
178
noise_suppression,
179
music_mode,
180
};
181
assert!(!settings.uses_device_track_on(true));
182
let non_windows_device = !music_mode
183
&& matches!(
184
noise_suppression,
185
NoiseSuppression::Auto | NoiseSuppression::Low
186
);
187
assert_eq!(settings.uses_device_track_on(false), non_windows_device);
188
}
189
}
190
}
191
192
167
#[test]
193
168
fn off_leaves_the_device_track_and_processes_nothing() {
194
169
let settings = MicSettings {
@@ -89,16 +89,12 @@ impl MicSettings {89
}89
}90
}90
}91
91
92
/// Auto and Low use the native WebRTC platform ADM device track on every desktop OS93
/// (WASAPI2/CoreAudio on Windows, Pulse/PipeWire on Linux, CoreAudio on macOS), matching94
/// Web Teams and avoiding software-feeder jitter and unsynchronized AEC.95
/// Music mode and Off run the software chain.92
pub fn uses_device_track(self) -> bool {96
pub fn uses_device_track(self) -> bool {93
self.uses_device_track_on(cfg!(windows))97
!self.music_mode94
}95
96
/// On Linux and macOS, Auto and Low keep the platform ADM device track97
/// (Pulse / CoreAudio — same path Web Teams uses). Music mode and Off still98
/// run the software chain; Windows always does.99
pub fn uses_device_track_on(self, windows: bool) -> bool {100
!windows101
&& !self.music_mode102
&& matches!(98
&& matches!(103
self.noise_suppression,99
self.noise_suppression,104
NoiseSuppression::Auto | NoiseSuppression::Low100
NoiseSuppression::Auto | NoiseSuppression::Low@@ -115,11 +111,9 @@ mod tests {115
use super::*;111
use super::*;116
112
117
#[test]113
#[test]118
fn auto_uses_the_device_track_on_linux_and_macos_and_keeps_ml_for_the_windows_chain() {114
fn auto_uses_the_device_track_on_all_platforms() {119
let settings = MicSettings::default();115
let settings = MicSettings::default();120
// Non-Windows (Pulse on Linux, CoreAudio on macOS) keeps the ADM track.116
assert!(settings.uses_device_track());121
assert!(settings.uses_device_track_on(false));122
assert!(!settings.uses_device_track_on(true));123
assert!(settings.ml_noise_suppression());117
assert!(settings.ml_noise_suppression());124
assert_eq!(118
assert_eq!(125
settings.apm_config(),119
settings.apm_config(),@@ -133,12 +127,12 @@ mod tests {133
}127
}134
128
135
#[test]129
#[test]136
fn low_keeps_the_coreaudio_or_pulse_device_track_with_the_apm_noise_suppression() {130
fn low_keeps_the_platform_device_track_with_apm_noise_suppression() {137
let settings = MicSettings {131
let settings = MicSettings {138
noise_suppression: NoiseSuppression::Low,132
noise_suppression: NoiseSuppression::Low,139
music_mode: false,133
music_mode: false,140
};134
};141
assert!(settings.uses_device_track_on(false));135
assert!(settings.uses_device_track());142
assert!(!settings.ml_noise_suppression());136
assert!(!settings.ml_noise_suppression());143
assert_eq!(137
assert_eq!(144
settings.apm_config(),138
settings.apm_config(),@@ -170,25 +164,6 @@ mod tests {170
);164
);171
}165
}172
166
173
#[test]174
fn windows_never_uses_the_device_track() {175
for noise_suppression in NoiseSuppression::ALL {176
for music_mode in [false, true] {177
let settings = MicSettings {178
noise_suppression,179
music_mode,180
};181
assert!(!settings.uses_device_track_on(true));182
let non_windows_device = !music_mode183
&& matches!(184
noise_suppression,185
NoiseSuppression::Auto | NoiseSuppression::Low186
);187
assert_eq!(settings.uses_device_track_on(false), non_windows_device);188
}189
}190
}191
192
#[test]167
#[test]193
fn off_leaves_the_device_track_and_processes_nothing() {168
fn off_leaves_the_device_track_and_processes_nothing() {194
let settings = MicSettings {169
let settings = MicSettings {@@ -6,11 +6,11 @@ use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;
6
6
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};
7
7
use windows::Win32::Media::Audio::{
8
8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,
9
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,
10
AUDCLNT_STREAMOPTIONS_NONE, AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON,
11
AudioCategory_Communications, AudioClientProperties, DEVICE_STATE_ACTIVE, IAudioCaptureClient,
12
IAudioClient, IAudioClient2, IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator,
13
MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,
9
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMOPTIONS_NONE, AUDIO_EFFECT,
10
AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, AudioCategory_Communications,
11
AudioClientProperties, DEVICE_STATE_ACTIVE, IAudioCaptureClient, IAudioClient, IAudioClient2,
12
IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX,
13
eCapture, eCommunications, eConsole,
14
14
};
15
15
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};
16
16
use windows::Win32::System::Com::{
@@ -53,13 +53,36 @@ fn open_device(choice: &DeviceChoice) -> Result<IMMDevice> {
53
53
};
54
54
match chosen {
55
55
Some(device) => Ok(device),
56
None => enumerator
57
.GetDefaultAudioEndpoint(eCapture, eCommunications)
58
.map_err(|error| audio_error("default communications microphone", error)),
56
None => match choice {
57
DeviceChoice::Device(key) => Err(audio_error(
58
"microphone",
59
format!("`{key}` is not an active capture device"),
60
)),
61
DeviceChoice::SystemDefault => enumerator
62
.GetDefaultAudioEndpoint(eCapture, eConsole)
63
.or_else(|_| enumerator.GetDefaultAudioEndpoint(eCapture, eCommunications))
64
.map_err(|error| audio_error("default microphone", error)),
65
},
59
66
}
60
67
}
61
68
}
62
69
70
pub fn friendly_name_for_id(id: &str) -> Option<String> {
71
unsafe {
72
let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();
73
let name =
74
CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL)
75
.ok()
76
.and_then(|enumerator| enumerator.GetDevice(&HSTRING::from(id)).ok())
77
.map(|device| friendly_name(&device))
78
.filter(|name| !name.is_empty());
79
if initialized {
80
CoUninitialize();
81
}
82
name
83
}
84
}
85
63
86
fn friendly_name(device: &IMMDevice) -> String {
64
87
unsafe {
65
88
let Ok(store) = device.OpenPropertyStore(STGM_READ) else {
@@ -93,9 +116,8 @@ fn initialise(
93
116
wBitsPerSample: BITS,
94
117
cbSize: 0,
95
118
};
96
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK
97
| AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM
98
| AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;
119
// Omit AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY so WASAPI uses Windows' higher-quality resampler.
120
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;
99
121
unsafe {
100
122
let client: IAudioClient = device
101
123
.Activate(CLSCTX_ALL, None)
@@ -6,11 +6,11 @@ use windows::Win32::Devices::FunctionDiscovery::PKEY_Device_FriendlyName;6
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};6
use windows::Win32::Foundation::{CloseHandle, HANDLE, WAIT_OBJECT_0};7
use windows::Win32::Media::Audio::{7
use windows::Win32::Media::Audio::{8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,8
AUDCLNT_BUFFERFLAGS_SILENT, AUDCLNT_SHAREMODE_SHARED, AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM,9
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY,9
AUDCLNT_STREAMFLAGS_EVENTCALLBACK, AUDCLNT_STREAMOPTIONS_NONE, AUDIO_EFFECT,10
AUDCLNT_STREAMOPTIONS_NONE, AUDIO_EFFECT, AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON,10
AUDIO_EFFECT_STATE_OFF, AUDIO_EFFECT_STATE_ON, AudioCategory_Communications,11
AudioCategory_Communications, AudioClientProperties, DEVICE_STATE_ACTIVE, IAudioCaptureClient,11
AudioClientProperties, DEVICE_STATE_ACTIVE, IAudioCaptureClient, IAudioClient, IAudioClient2,12
IAudioClient, IAudioClient2, IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator,12
IAudioEffectsManager, IMMDevice, IMMDeviceEnumerator, MMDeviceEnumerator, WAVEFORMATEX,13
MMDeviceEnumerator, WAVEFORMATEX, eCapture, eCommunications,13
eCapture, eCommunications, eConsole,14
};14
};15
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};15
use windows::Win32::System::Com::StructuredStorage::{PROPVARIANT, PropVariantClear};16
use windows::Win32::System::Com::{16
use windows::Win32::System::Com::{@@ -53,13 +53,36 @@ fn open_device(choice: &DeviceChoice) -> Result<IMMDevice> {53
};53
};54
match chosen {54
match chosen {55
Some(device) => Ok(device),55
Some(device) => Ok(device),56
None => enumerator56
None => match choice {57
.GetDefaultAudioEndpoint(eCapture, eCommunications)57
DeviceChoice::Device(key) => Err(audio_error(58
.map_err(|error| audio_error("default communications microphone", error)),58
"microphone",59
format!("`{key}` is not an active capture device"),60
)),61
DeviceChoice::SystemDefault => enumerator62
.GetDefaultAudioEndpoint(eCapture, eConsole)63
.or_else(|_| enumerator.GetDefaultAudioEndpoint(eCapture, eCommunications))64
.map_err(|error| audio_error("default microphone", error)),65
},59
}66
}60
}67
}61
}68
}62
69
70
pub fn friendly_name_for_id(id: &str) -> Option<String> {71
unsafe {72
let initialized = CoInitializeEx(None, COINIT_MULTITHREADED).is_ok();73
let name =74
CoCreateInstance::<_, IMMDeviceEnumerator>(&MMDeviceEnumerator, None, CLSCTX_ALL)75
.ok()76
.and_then(|enumerator| enumerator.GetDevice(&HSTRING::from(id)).ok())77
.map(|device| friendly_name(&device))78
.filter(|name| !name.is_empty());79
if initialized {80
CoUninitialize();81
}82
name83
}84
}85
63
fn friendly_name(device: &IMMDevice) -> String {86
fn friendly_name(device: &IMMDevice) -> String {64
unsafe {87
unsafe {65
let Ok(store) = device.OpenPropertyStore(STGM_READ) else {88
let Ok(store) = device.OpenPropertyStore(STGM_READ) else {@@ -93,9 +116,8 @@ fn initialise(93
wBitsPerSample: BITS,116
wBitsPerSample: BITS,94
cbSize: 0,117
cbSize: 0,95
};118
};96
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK119
// Omit AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY so WASAPI uses Windows' higher-quality resampler.97
| AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM120
let flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK | AUDCLNT_STREAMFLAGS_AUTOCONVERTPCM;98
| AUDCLNT_STREAMFLAGS_SRC_DEFAULT_QUALITY;99
unsafe {121
unsafe {100
let client: IAudioClient = device122
let client: IAudioClient = device101
.Activate(CLSCTX_ALL, None)123
.Activate(CLSCTX_ALL, None)@@ -22,6 +22,37 @@ impl MuteCommand {
22
22
}
23
23
}
24
24
25
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
26
pub struct ServerMuteSync {
27
pub muted: bool,
28
pub cleared: bool,
29
pub silence_without_signal: bool,
30
}
31
32
/// Applies an organizer mute locally. A local unmute while the flag is still set
33
/// stays cleared until `server_muted` drops, so the same roster update cannot mute again.
34
pub fn sync_server_mute(server_muted: bool, muted: bool, cleared: bool) -> ServerMuteSync {
35
if !server_muted {
36
return ServerMuteSync {
37
muted,
38
cleared: false,
39
silence_without_signal: false,
40
};
41
}
42
if cleared || muted {
43
return ServerMuteSync {
44
muted,
45
cleared,
46
silence_without_signal: false,
47
};
48
}
49
ServerMuteSync {
50
muted: true,
51
cleared: false,
52
silence_without_signal: true,
53
}
54
}
55
25
56
impl MuteEffect {
26
57
pub fn for_muted(muted: bool) -> Self {
27
58
MuteEffect {
@@ -59,6 +90,22 @@ mod tests {
59
90
assert!(!open.endpoint_is_muted);
60
91
}
61
92
93
#[test]
94
fn an_organizer_mute_closes_the_mic_until_the_user_clears_it() {
95
let applied = sync_server_mute(true, false, false);
96
assert!(applied.silence_without_signal);
97
assert!(applied.muted);
98
assert!(!applied.cleared);
99
let held = sync_server_mute(true, false, true);
100
assert!(!held.silence_without_signal);
101
assert!(!held.muted);
102
assert!(held.cleared);
103
let again = sync_server_mute(false, false, true);
104
assert!(!again.cleared);
105
let fresh = sync_server_mute(true, false, again.cleared);
106
assert!(fresh.silence_without_signal);
107
}
108
62
109
#[test]
63
110
fn meetings_start_muted_and_other_calls_do_not() {
64
111
let meeting = MuteEffect::initial(true);
@@ -22,6 +22,37 @@ impl MuteCommand {22
}22
}23
}23
}24
24
25
#[derive(Debug, Clone, Copy, PartialEq, Eq)]26
pub struct ServerMuteSync {27
pub muted: bool,28
pub cleared: bool,29
pub silence_without_signal: bool,30
}31
32
/// Applies an organizer mute locally. A local unmute while the flag is still set33
/// stays cleared until `server_muted` drops, so the same roster update cannot mute again.34
pub fn sync_server_mute(server_muted: bool, muted: bool, cleared: bool) -> ServerMuteSync {35
if !server_muted {36
return ServerMuteSync {37
muted,38
cleared: false,39
silence_without_signal: false,40
};41
}42
if cleared || muted {43
return ServerMuteSync {44
muted,45
cleared,46
silence_without_signal: false,47
};48
}49
ServerMuteSync {50
muted: true,51
cleared: false,52
silence_without_signal: true,53
}54
}55
25
impl MuteEffect {56
impl MuteEffect {26
pub fn for_muted(muted: bool) -> Self {57
pub fn for_muted(muted: bool) -> Self {27
MuteEffect {58
MuteEffect {@@ -59,6 +90,22 @@ mod tests {59
assert!(!open.endpoint_is_muted);90
assert!(!open.endpoint_is_muted);60
}91
}61
92
93
#[test]94
fn an_organizer_mute_closes_the_mic_until_the_user_clears_it() {95
let applied = sync_server_mute(true, false, false);96
assert!(applied.silence_without_signal);97
assert!(applied.muted);98
assert!(!applied.cleared);99
let held = sync_server_mute(true, false, true);100
assert!(!held.silence_without_signal);101
assert!(!held.muted);102
assert!(held.cleared);103
let again = sync_server_mute(false, false, true);104
assert!(!again.cleared);105
let fresh = sync_server_mute(true, false, again.cleared);106
assert!(fresh.silence_without_signal);107
}108
62
#[test]109
#[test]63
fn meetings_start_muted_and_other_calls_do_not() {110
fn meetings_start_muted_and_other_calls_do_not() {64
let meeting = MuteEffect::initial(true);111
let meeting = MuteEffect::initial(true);@@ -3,6 +3,7 @@ use std::sync::{Mutex, Once};
3
3
use std::time::{Duration, Instant};
4
4
5
5
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};
6
use libwebrtc::native::apm::AudioProcessingModule;
6
7
use ndarray::{ArrayView2, ArrayViewMut2};
7
8
8
9
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};
@@ -115,10 +116,15 @@ fn capture_hook(channel_index: usize, samples: &mut [f32]) {
115
116
let Ok(mut stage) = HOOK_STAGE.try_lock() else {
116
117
return;
117
118
};
119
let overloaded = OVERLOADED.load(Ordering::Relaxed);
118
120
let started = Instant::now();
119
stage.process(channel_index, samples);
120
if stage.over_budget(started.elapsed()) {
121
HOOK_ARMED.store(false, Ordering::Relaxed);
121
let used_ml = !overloaded && stage.process_ml_only(channel_index, samples);
122
if used_ml {
123
let _ = stage.over_budget(started.elapsed());
124
} else {
125
// 16/32 kHz headset, DeepFilterNet still loading, or CPU budget exceeded:
126
// run single-stage WebRTC NS instead of leaving the track unfiltered or double-stacking.
127
stage.process_fallback_ns(channel_index, samples);
122
128
}
123
129
}
124
130
@@ -127,14 +133,15 @@ fn install_hook(armed: bool) {
127
133
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));
128
134
}
129
135
130
/// Arms DeepFilterNet on the capture hook only while the Pulse / CoreAudio device track is the
131
/// outgoing microphone. WebRTC's own noise suppression keeps running before it either way.
136
/// Arms the capture hook while the platform ADM device track is outgoing in Auto mode.
137
/// WebRTC's built-in NS is disabled on the Auto device track so DeepFilterNet runs alone on
138
/// 48 kHz microphones, while 16 kHz headsets, warm-up frames and overloaded CPUs fall back
139
/// cleanly to single-stage WebRTC NS inside the hook.
132
140
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {
133
141
if settings.ml_noise_suppression() {
134
142
prepare();
135
143
}
136
let armed =
137
should_arm_hook(settings, device_track_outgoing) && !OVERLOADED.load(Ordering::Relaxed);
144
let armed = should_arm_hook(settings, device_track_outgoing);
138
145
install_hook(armed);
139
146
}
140
147
@@ -173,6 +180,8 @@ impl FrameBudget {
173
180
174
181
pub struct NoiseStage {
175
182
channels: Vec<Option<DfTract>>,
183
fallback_ns: Vec<Option<AudioProcessingModule>>,
184
fallback_pcm: Vec<i16>,
176
185
input: Vec<f32>,
177
186
output: Vec<f32>,
178
187
pcm: Vec<f32>,
@@ -183,6 +192,8 @@ impl NoiseStage {
183
192
pub const fn new() -> Self {
184
193
NoiseStage {
185
194
channels: Vec::new(),
195
fallback_ns: Vec::new(),
196
fallback_pcm: Vec::new(),
186
197
input: Vec::new(),
187
198
output: Vec::new(),
188
199
pcm: Vec::new(),
@@ -190,9 +201,11 @@ impl NoiseStage {
190
201
}
191
202
}
192
203
193
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
204
/// Runs DeepFilterNet if the frame is 48 kHz (480 samples) and the model is loaded.
205
/// Returns true if DeepFilterNet processed the frame.
206
fn process_ml_only(&mut self, channel_index: usize, samples: &mut [f32]) -> bool {
194
207
if samples.len() != FRAME_SAMPLES {
195
return;
208
return false;
196
209
}
197
210
while self.channels.len() <= channel_index {
198
211
self.channels.push(None);
@@ -202,7 +215,7 @@ impl NoiseStage {
202
215
*channel = ready_model();
203
216
}
204
217
let Some(model) = channel.as_mut() else {
205
return;
218
return false;
206
219
};
207
220
self.input.clear();
208
221
self.input
@@ -212,14 +225,50 @@ impl NoiseStage {
212
225
ArrayView2::from_shape((1, FRAME_SAMPLES), &self.input),
213
226
ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut self.output),
214
227
) else {
215
return;
228
return false;
216
229
};
217
230
if model.process(noisy, enhanced).is_err() {
218
return;
231
return false;
219
232
}
220
233
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {
221
234
*sample = enhanced * PCM_SCALE;
222
235
}
236
true
237
}
238
239
/// Single-stage WebRTC NS fallback for non-48 kHz headsets (e.g. 16 kHz Bluetooth/wireless HFP),
240
/// while DeepFilterNet is warming up, or after CPU budget overload.
241
fn process_fallback_ns(&mut self, channel_index: usize, samples: &mut [f32]) {
242
let sample_rate = match samples.len() {
243
80 => 8_000,
244
160 => 16_000,
245
320 => 32_000,
246
480 => 48_000,
247
_ => return,
248
};
249
while self.fallback_ns.len() <= channel_index {
250
self.fallback_ns.push(None);
251
}
252
let apm = self.fallback_ns[channel_index]
253
.get_or_insert_with(|| AudioProcessingModule::new(false, false, false, true));
254
self.fallback_pcm.clear();
255
self.fallback_pcm.extend(samples.iter().map(|sample| {
256
sample
257
.round()
258
.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16
259
}));
260
if apm
261
.process_stream(&mut self.fallback_pcm, sample_rate, 1)
262
.is_ok()
263
{
264
for (sample, cleaned) in samples.iter_mut().zip(&self.fallback_pcm) {
265
*sample = f32::from(*cleaned);
266
}
267
}
268
}
269
270
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {
271
let _ = self.process_ml_only(channel_index, samples);
223
272
}
224
273
225
274
/// Reports and remembers for this call when frames keep running over their budget.
@@ -364,7 +413,7 @@ mod tests {
364
413
}
365
414
366
415
#[test]
367
fn only_linux_and_macos_auto_arm_the_hook_and_an_overload_keeps_it_off_until_hangup() {
416
fn auto_arms_the_hook_on_all_platforms_and_overload_falls_back_until_hangup() {
368
417
let auto = MicSettings::default();
369
418
let low = MicSettings {
370
419
noise_suppression: NoiseSuppression::Low,
@@ -377,21 +426,22 @@ mod tests {
377
426
assert!(!should_arm_hook(auto, false));
378
427
assert!(!should_arm_hook(low, true));
379
428
assert!(!should_arm_hook(music, true));
380
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));
429
assert!(should_arm_hook(auto, auto.uses_device_track()));
381
430
382
431
clear();
383
432
apply_for_outgoing(auto, true);
384
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());
433
assert!(HOOK_ARMED.load(Ordering::Relaxed));
385
434
386
435
OVERLOADED.store(true, Ordering::Relaxed);
387
436
apply_for_outgoing(auto, true);
388
assert!(!HOOK_ARMED.load(Ordering::Relaxed));
437
// Hook stays armed so fallback WebRTC NS keeps protecting the Windows Auto track (built-in NS off).
438
assert!(HOOK_ARMED.load(Ordering::Relaxed));
389
439
assert!(overloaded());
390
440
391
441
clear();
392
442
assert!(!overloaded());
393
apply_for_outgoing(auto, true);
394
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());
443
apply_for_outgoing(low, true);
444
assert!(!HOOK_ARMED.load(Ordering::Relaxed));
395
445
clear();
396
446
}
397
447
}
@@ -3,6 +3,7 @@ use std::sync::{Mutex, Once};3
use std::time::{Duration, Instant};3
use std::time::{Duration, Instant};4
4
5
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};5
use df::tract::{DfParams, DfTract, ReduceMask, RuntimeParams};6
use libwebrtc::native::apm::AudioProcessingModule;6
use ndarray::{ArrayView2, ArrayViewMut2};7
use ndarray::{ArrayView2, ArrayViewMut2};7
8
8
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};9
use crate::audio::{FRAME_SAMPLES, SAMPLE_RATE};@@ -115,10 +116,15 @@ fn capture_hook(channel_index: usize, samples: &mut [f32]) {115
let Ok(mut stage) = HOOK_STAGE.try_lock() else {116
let Ok(mut stage) = HOOK_STAGE.try_lock() else {116
return;117
return;117
};118
};119
let overloaded = OVERLOADED.load(Ordering::Relaxed);118
let started = Instant::now();120
let started = Instant::now();119
stage.process(channel_index, samples);121
let used_ml = !overloaded && stage.process_ml_only(channel_index, samples);120
if stage.over_budget(started.elapsed()) {122
if used_ml {121
HOOK_ARMED.store(false, Ordering::Relaxed);123
let _ = stage.over_budget(started.elapsed());124
} else {125
// 16/32 kHz headset, DeepFilterNet still loading, or CPU budget exceeded:126
// run single-stage WebRTC NS instead of leaving the track unfiltered or double-stacking.127
stage.process_fallback_ns(channel_index, samples);122
}128
}123
}129
}124
130
@@ -127,14 +133,15 @@ fn install_hook(armed: bool) {127
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));133
webrtc_sys::noise_hook::set_capture_hook(armed.then_some(capture_hook));128
}134
}129
135
130
/// Arms DeepFilterNet on the capture hook only while the Pulse / CoreAudio device track is the136
/// Arms the capture hook while the platform ADM device track is outgoing in Auto mode.131
/// outgoing microphone. WebRTC's own noise suppression keeps running before it either way.137
/// WebRTC's built-in NS is disabled on the Auto device track so DeepFilterNet runs alone on138
/// 48 kHz microphones, while 16 kHz headsets, warm-up frames and overloaded CPUs fall back139
/// cleanly to single-stage WebRTC NS inside the hook.132
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {140
pub fn apply_for_outgoing(settings: MicSettings, device_track_outgoing: bool) {133
if settings.ml_noise_suppression() {141
if settings.ml_noise_suppression() {134
prepare();142
prepare();135
}143
}136
let armed =144
let armed = should_arm_hook(settings, device_track_outgoing);137
should_arm_hook(settings, device_track_outgoing) && !OVERLOADED.load(Ordering::Relaxed);138
install_hook(armed);145
install_hook(armed);139
}146
}140
147
@@ -173,6 +180,8 @@ impl FrameBudget {173
180
174
pub struct NoiseStage {181
pub struct NoiseStage {175
channels: Vec<Option<DfTract>>,182
channels: Vec<Option<DfTract>>,183
fallback_ns: Vec<Option<AudioProcessingModule>>,184
fallback_pcm: Vec<i16>,176
input: Vec<f32>,185
input: Vec<f32>,177
output: Vec<f32>,186
output: Vec<f32>,178
pcm: Vec<f32>,187
pcm: Vec<f32>,@@ -183,6 +192,8 @@ impl NoiseStage {183
pub const fn new() -> Self {192
pub const fn new() -> Self {184
NoiseStage {193
NoiseStage {185
channels: Vec::new(),194
channels: Vec::new(),195
fallback_ns: Vec::new(),196
fallback_pcm: Vec::new(),186
input: Vec::new(),197
input: Vec::new(),187
output: Vec::new(),198
output: Vec::new(),188
pcm: Vec::new(),199
pcm: Vec::new(),@@ -190,9 +201,11 @@ impl NoiseStage {190
}201
}191
}202
}192
203
193
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {204
/// Runs DeepFilterNet if the frame is 48 kHz (480 samples) and the model is loaded.205
/// Returns true if DeepFilterNet processed the frame.206
fn process_ml_only(&mut self, channel_index: usize, samples: &mut [f32]) -> bool {194
if samples.len() != FRAME_SAMPLES {207
if samples.len() != FRAME_SAMPLES {195
return;208
return false;196
}209
}197
while self.channels.len() <= channel_index {210
while self.channels.len() <= channel_index {198
self.channels.push(None);211
self.channels.push(None);@@ -202,7 +215,7 @@ impl NoiseStage {202
*channel = ready_model();215
*channel = ready_model();203
}216
}204
let Some(model) = channel.as_mut() else {217
let Some(model) = channel.as_mut() else {205
return;218
return false;206
};219
};207
self.input.clear();220
self.input.clear();208
self.input221
self.input@@ -212,14 +225,50 @@ impl NoiseStage {212
ArrayView2::from_shape((1, FRAME_SAMPLES), &self.input),225
ArrayView2::from_shape((1, FRAME_SAMPLES), &self.input),213
ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut self.output),226
ArrayViewMut2::from_shape((1, FRAME_SAMPLES), &mut self.output),214
) else {227
) else {215
return;228
return false;216
};229
};217
if model.process(noisy, enhanced).is_err() {230
if model.process(noisy, enhanced).is_err() {218
return;231
return false;219
}232
}220
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {233
for (sample, enhanced) in samples.iter_mut().zip(&self.output) {221
*sample = enhanced * PCM_SCALE;234
*sample = enhanced * PCM_SCALE;222
}235
}236
true237
}238
239
/// Single-stage WebRTC NS fallback for non-48 kHz headsets (e.g. 16 kHz Bluetooth/wireless HFP),240
/// while DeepFilterNet is warming up, or after CPU budget overload.241
fn process_fallback_ns(&mut self, channel_index: usize, samples: &mut [f32]) {242
let sample_rate = match samples.len() {243
80 => 8_000,244
160 => 16_000,245
320 => 32_000,246
480 => 48_000,247
_ => return,248
};249
while self.fallback_ns.len() <= channel_index {250
self.fallback_ns.push(None);251
}252
let apm = self.fallback_ns[channel_index]253
.get_or_insert_with(|| AudioProcessingModule::new(false, false, false, true));254
self.fallback_pcm.clear();255
self.fallback_pcm.extend(samples.iter().map(|sample| {256
sample257
.round()258
.clamp(f32::from(i16::MIN), f32::from(i16::MAX)) as i16259
}));260
if apm261
.process_stream(&mut self.fallback_pcm, sample_rate, 1)262
.is_ok()263
{264
for (sample, cleaned) in samples.iter_mut().zip(&self.fallback_pcm) {265
*sample = f32::from(*cleaned);266
}267
}268
}269
270
pub fn process(&mut self, channel_index: usize, samples: &mut [f32]) {271
let _ = self.process_ml_only(channel_index, samples);223
}272
}224
273
225
/// Reports and remembers for this call when frames keep running over their budget.274
/// Reports and remembers for this call when frames keep running over their budget.@@ -364,7 +413,7 @@ mod tests {364
}413
}365
414
366
#[test]415
#[test]367
fn only_linux_and_macos_auto_arm_the_hook_and_an_overload_keeps_it_off_until_hangup() {416
fn auto_arms_the_hook_on_all_platforms_and_overload_falls_back_until_hangup() {368
let auto = MicSettings::default();417
let auto = MicSettings::default();369
let low = MicSettings {418
let low = MicSettings {370
noise_suppression: NoiseSuppression::Low,419
noise_suppression: NoiseSuppression::Low,@@ -377,21 +426,22 @@ mod tests {377
assert!(!should_arm_hook(auto, false));426
assert!(!should_arm_hook(auto, false));378
assert!(!should_arm_hook(low, true));427
assert!(!should_arm_hook(low, true));379
assert!(!should_arm_hook(music, true));428
assert!(!should_arm_hook(music, true));380
assert!(!should_arm_hook(auto, auto.uses_device_track_on(true)));429
assert!(should_arm_hook(auto, auto.uses_device_track()));381
430
382
clear();431
clear();383
apply_for_outgoing(auto, true);432
apply_for_outgoing(auto, true);384
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());433
assert!(HOOK_ARMED.load(Ordering::Relaxed));385
434
386
OVERLOADED.store(true, Ordering::Relaxed);435
OVERLOADED.store(true, Ordering::Relaxed);387
apply_for_outgoing(auto, true);436
apply_for_outgoing(auto, true);388
assert!(!HOOK_ARMED.load(Ordering::Relaxed));437
// Hook stays armed so fallback WebRTC NS keeps protecting the Windows Auto track (built-in NS off).438
assert!(HOOK_ARMED.load(Ordering::Relaxed));389
assert!(overloaded());439
assert!(overloaded());390
440
391
clear();441
clear();392
assert!(!overloaded());442
assert!(!overloaded());393
apply_for_outgoing(auto, true);443
apply_for_outgoing(low, true);394
assert_eq!(HOOK_ARMED.load(Ordering::Relaxed), auto.uses_device_track());444
assert!(!HOOK_ARMED.load(Ordering::Relaxed));395
clear();445
clear();396
}446
}397
}447
}@@ -73,6 +73,7 @@ pub struct Member {
73
73
pub mri: String,
74
74
pub display_name: String,
75
75
pub muted: bool,
76
pub server_muted: bool,
76
77
pub in_lobby: bool,
77
78
pub audio_sources: Vec<u32>,
78
79
pub video_source: Option<u32>,
@@ -324,6 +325,9 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
324
325
.iter()
325
326
.any(|endpoint| endpoint.get("lobby").is_some());
326
327
let muted = !in_call.is_empty() && in_call.iter().all(|endpoint| endpoint_muted(endpoint));
328
let server_muted = in_call
329
.iter()
330
.any(|endpoint| endpoint_server_muted(endpoint));
327
331
let audio_sources = in_call
328
332
.iter()
329
333
.flat_map(|endpoint| audio_streams(endpoint))
@@ -337,6 +341,7 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M
337
341
mri: mri.to_owned(),
338
342
display_name,
339
343
muted,
344
server_muted,
340
345
in_lobby,
341
346
audio_sources,
342
347
video_source: sending_source(&in_call, VIDEO),
@@ -479,7 +484,11 @@ fn audio_streams(endpoint: &Value) -> impl Iterator<Item = &Value> {
479
484
480
485
fn endpoint_muted(endpoint: &Value) -> bool {
481
486
endpoint["endpointState"]["state"]["isMuted"].as_bool() == Some(true)
482
|| audio_streams(endpoint).any(|stream| stream["serverMuted"].as_bool() == Some(true))
487
|| endpoint_server_muted(endpoint)
488
}
489
490
fn endpoint_server_muted(endpoint: &Value) -> bool {
491
audio_streams(endpoint).any(|stream| stream["serverMuted"].as_bool() == Some(true))
483
492
}
484
493
485
494
fn source_id(value: &Value) -> Option<u32> {
@@ -576,6 +585,12 @@ mod tests {
576
585
forced["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(true);
577
586
roster.apply(&delta(json!({"8:orgid:a": forced})));
578
587
assert!(roster.members()[0].muted);
588
assert!(roster.members()[0].server_muted);
589
let mut local = participant("Ana", 2, "active", true, 201);
590
local["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(false);
591
roster.apply(&delta(json!({"8:orgid:a": local})));
592
assert!(roster.members()[0].muted);
593
assert!(!roster.members()[0].server_muted);
579
594
}
580
595
581
596
#[test]
@@ -73,6 +73,7 @@ pub struct Member {73
pub mri: String,73
pub mri: String,74
pub display_name: String,74
pub display_name: String,75
pub muted: bool,75
pub muted: bool,76
pub server_muted: bool,76
pub in_lobby: bool,77
pub in_lobby: bool,77
pub audio_sources: Vec<u32>,78
pub audio_sources: Vec<u32>,78
pub video_source: Option<u32>,79
pub video_source: Option<u32>,@@ -324,6 +325,9 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M324
.iter()325
.iter()325
.any(|endpoint| endpoint.get("lobby").is_some());326
.any(|endpoint| endpoint.get("lobby").is_some());326
let muted = !in_call.is_empty() && in_call.iter().all(|endpoint| endpoint_muted(endpoint));327
let muted = !in_call.is_empty() && in_call.iter().all(|endpoint| endpoint_muted(endpoint));328
let server_muted = in_call329
.iter()330
.any(|endpoint| endpoint_server_muted(endpoint));327
let audio_sources = in_call331
let audio_sources = in_call328
.iter()332
.iter()329
.flat_map(|endpoint| audio_streams(endpoint))333
.flat_map(|endpoint| audio_streams(endpoint))@@ -337,6 +341,7 @@ fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&M337
mri: mri.to_owned(),341
mri: mri.to_owned(),338
display_name,342
display_name,339
muted,343
muted,344
server_muted,340
in_lobby,345
in_lobby,341
audio_sources,346
audio_sources,342
video_source: sending_source(&in_call, VIDEO),347
video_source: sending_source(&in_call, VIDEO),@@ -479,7 +484,11 @@ fn audio_streams(endpoint: &Value) -> impl Iterator<Item = &Value> {479
484
480
fn endpoint_muted(endpoint: &Value) -> bool {485
fn endpoint_muted(endpoint: &Value) -> bool {481
endpoint["endpointState"]["state"]["isMuted"].as_bool() == Some(true)486
endpoint["endpointState"]["state"]["isMuted"].as_bool() == Some(true)482
|| audio_streams(endpoint).any(|stream| stream["serverMuted"].as_bool() == Some(true))487
|| endpoint_server_muted(endpoint)488
}489
490
fn endpoint_server_muted(endpoint: &Value) -> bool {491
audio_streams(endpoint).any(|stream| stream["serverMuted"].as_bool() == Some(true))483
}492
}484
493
485
fn source_id(value: &Value) -> Option<u32> {494
fn source_id(value: &Value) -> Option<u32> {@@ -576,6 +585,12 @@ mod tests {576
forced["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(true);585
forced["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(true);577
roster.apply(&delta(json!({"8:orgid:a": forced})));586
roster.apply(&delta(json!({"8:orgid:a": forced})));578
assert!(roster.members()[0].muted);587
assert!(roster.members()[0].muted);588
assert!(roster.members()[0].server_muted);589
let mut local = participant("Ana", 2, "active", true, 201);590
local["endpoints"]["ep"]["call"]["mediaStreams"][0]["serverMuted"] = json!(false);591
roster.apply(&delta(json!({"8:orgid:a": local})));592
assert!(roster.members()[0].muted);593
assert!(!roster.members()[0].server_muted);579
}594
}580
595
581
#[test]596
#[test]@@ -6,12 +6,13 @@ use libwebrtc::desktop_capturer::{
6
6
CaptureError, CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,
7
7
PortalPickerEvent,
8
8
};
9
use libwebrtc::native::yuv_helper::argb_to_i420;
9
use libwebrtc::native::yuv_helper::{argb_scale, argb_to_i420};
10
10
use libwebrtc::video_frame::I420Buffer;
11
11
12
12
use crate::capture::Capture;
13
13
use crate::error::{Error, Result};
14
14
use crate::video_frame::VideoPicture;
15
use crate::win_timer::HighResSleep;
15
16
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17
18
pub enum ShareKind {
@@ -176,6 +177,81 @@ fn scaled_bgra(
176
177
})
177
178
}
178
179
180
const SHARE_SEND_MAX_FS: u32 = 8160;
181
const MACROBLOCK: u32 = 16;
182
183
fn macroblocks(width: u32, height: u32) -> u32 {
184
width.div_ceil(MACROBLOCK) * height.div_ceil(MACROBLOCK)
185
}
186
187
fn even(value: u32) -> u32 {
188
value & !1
189
}
190
191
fn buffer_covers(bytes: &[u8], width: u32, height: u32, stride: u32) -> bool {
192
width >= 2
193
&& height >= 2
194
&& stride as usize >= width as usize * 4
195
&& bytes.len() >= stride as usize * height as usize
196
}
197
198
pub(crate) fn fit_share_size(width: u32, height: u32, max_fs: u32) -> (u32, u32) {
199
let (width, height) = (even(width), even(height));
200
if width < 2 || height < 2 || max_fs == 0 || macroblocks(width, height) <= max_fs {
201
return (width, height);
202
}
203
let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt();
204
let mut target_width = even((f64::from(width) / scale) as u32).max(2);
205
let mut target_height = even((f64::from(height) / scale) as u32).max(2);
206
while macroblocks(target_width, target_height) > max_fs && target_width > 2 && target_height > 2
207
{
208
scale *= 1.05;
209
target_width = even((f64::from(width) / scale) as u32).max(2);
210
target_height = even((f64::from(height) / scale) as u32).max(2);
211
}
212
(target_width, target_height)
213
}
214
215
fn scale_bgra_to(
216
bytes: &[u8],
217
width: u32,
218
height: u32,
219
stride: u32,
220
target_width: u32,
221
target_height: u32,
222
) -> Vec<u8> {
223
let mut scaled = vec![0u8; target_width as usize * target_height as usize * 4];
224
argb_scale(
225
bytes,
226
stride,
227
width as i32,
228
height as i32,
229
&mut scaled,
230
target_width * 4,
231
target_width as i32,
232
target_height as i32,
233
);
234
scaled
235
}
236
237
fn share_frame(bytes: &[u8], width: u32, height: u32, stride: u32) -> Option<I420Buffer> {
238
let (width, height) = (even(width), even(height));
239
if !buffer_covers(bytes, width, height, stride) {
240
return None;
241
}
242
let (target_width, target_height) = fit_share_size(width, height, SHARE_SEND_MAX_FS);
243
if target_width == width && target_height == height {
244
return Some(i420_from_bgra(bytes, width, height, stride));
245
}
246
let scaled = scale_bgra_to(bytes, width, height, stride, target_width, target_height);
247
Some(i420_from_bgra(
248
&scaled,
249
target_width,
250
target_height,
251
target_width * 4,
252
))
253
}
254
179
255
fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {
180
256
let mut buffer = I420Buffer::new(width, height);
181
257
let (stride_y, stride_u, stride_v) = buffer.strides();
@@ -237,11 +313,13 @@ pub fn start_screen_capture(
237
313
*since = None;
238
314
}
239
315
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
240
if width >= 2 && height >= 2 {
241
deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
316
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {
317
deliver(picture);
242
318
}
243
319
});
320
let sleeper = HighResSleep::new();
244
321
while !stop.load(Ordering::SeqCst) {
322
let started = Instant::now();
245
323
let gone = gone_since
246
324
.lock()
247
325
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));
@@ -250,7 +328,8 @@ pub fn start_screen_capture(
250
328
}
251
329
pump_messages();
252
330
capturer.capture_frame();
253
std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));
331
let period = Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1);
332
sleeper.sleep_until(started + period);
254
333
}
255
334
})
256
335
.map_err(|error| Error::Webrtc(format!("screen thread: {error}")))
@@ -360,8 +439,8 @@ pub(crate) fn start_portal_capture(
360
439
}
361
440
let Ok(frame) = result else { return };
362
441
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);
363
if width >= 2 && height >= 2 {
364
deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));
442
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {
443
deliver(picture);
365
444
}
366
445
});
367
446
if delegated {
@@ -421,6 +500,17 @@ pub(crate) fn start_portal_capture(
421
500
mod tests {
422
501
use super::*;
423
502
503
#[test]
504
fn a_wide_share_fits_the_send_budget_and_a_short_buffer_does_not() {
505
use libwebrtc::video_frame::VideoBuffer;
506
let (width, height) = fit_share_size(2560, 1440, SHARE_SEND_MAX_FS);
507
assert!(macroblocks(width, height) <= SHARE_SEND_MAX_FS);
508
let bytes = vec![0u8; 2560 * 1440 * 4];
509
let frame = share_frame(&bytes, 2560, 1440, 2560 * 4).expect("scaled");
510
assert!(macroblocks(frame.width(), frame.height()) <= SHARE_SEND_MAX_FS);
511
assert!(share_frame(&[0u8; 8], 4, 2, 16).is_none());
512
}
513
424
514
#[test]
425
515
fn sources_get_readable_labels() {
426
516
let screen = ShareSource {
@@ -6,12 +6,13 @@ use libwebrtc::desktop_capturer::{6
CaptureError, CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,6
CaptureError, CaptureSource, DesktopCaptureSourceType, DesktopCapturer, DesktopCapturerOptions,7
PortalPickerEvent,7
PortalPickerEvent,8
};8
};9
use libwebrtc::native::yuv_helper::argb_to_i420;9
use libwebrtc::native::yuv_helper::{argb_scale, argb_to_i420};10
use libwebrtc::video_frame::I420Buffer;10
use libwebrtc::video_frame::I420Buffer;11
11
12
use crate::capture::Capture;12
use crate::capture::Capture;13
use crate::error::{Error, Result};13
use crate::error::{Error, Result};14
use crate::video_frame::VideoPicture;14
use crate::video_frame::VideoPicture;15
use crate::win_timer::HighResSleep;15
16
16
#[derive(Debug, Clone, Copy, PartialEq, Eq)]17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]17
pub enum ShareKind {18
pub enum ShareKind {@@ -176,6 +177,81 @@ fn scaled_bgra(176
})177
})177
}178
}178
179
180
const SHARE_SEND_MAX_FS: u32 = 8160;181
const MACROBLOCK: u32 = 16;182
183
fn macroblocks(width: u32, height: u32) -> u32 {184
width.div_ceil(MACROBLOCK) * height.div_ceil(MACROBLOCK)185
}186
187
fn even(value: u32) -> u32 {188
value & !1189
}190
191
fn buffer_covers(bytes: &[u8], width: u32, height: u32, stride: u32) -> bool {192
width >= 2193
&& height >= 2194
&& stride as usize >= width as usize * 4195
&& bytes.len() >= stride as usize * height as usize196
}197
198
pub(crate) fn fit_share_size(width: u32, height: u32, max_fs: u32) -> (u32, u32) {199
let (width, height) = (even(width), even(height));200
if width < 2 || height < 2 || max_fs == 0 || macroblocks(width, height) <= max_fs {201
return (width, height);202
}203
let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt();204
let mut target_width = even((f64::from(width) / scale) as u32).max(2);205
let mut target_height = even((f64::from(height) / scale) as u32).max(2);206
while macroblocks(target_width, target_height) > max_fs && target_width > 2 && target_height > 2207
{208
scale *= 1.05;209
target_width = even((f64::from(width) / scale) as u32).max(2);210
target_height = even((f64::from(height) / scale) as u32).max(2);211
}212
(target_width, target_height)213
}214
215
fn scale_bgra_to(216
bytes: &[u8],217
width: u32,218
height: u32,219
stride: u32,220
target_width: u32,221
target_height: u32,222
) -> Vec<u8> {223
let mut scaled = vec![0u8; target_width as usize * target_height as usize * 4];224
argb_scale(225
bytes,226
stride,227
width as i32,228
height as i32,229
&mut scaled,230
target_width * 4,231
target_width as i32,232
target_height as i32,233
);234
scaled235
}236
237
fn share_frame(bytes: &[u8], width: u32, height: u32, stride: u32) -> Option<I420Buffer> {238
let (width, height) = (even(width), even(height));239
if !buffer_covers(bytes, width, height, stride) {240
return None;241
}242
let (target_width, target_height) = fit_share_size(width, height, SHARE_SEND_MAX_FS);243
if target_width == width && target_height == height {244
return Some(i420_from_bgra(bytes, width, height, stride));245
}246
let scaled = scale_bgra_to(bytes, width, height, stride, target_width, target_height);247
Some(i420_from_bgra(248
&scaled,249
target_width,250
target_height,251
target_width * 4,252
))253
}254
179
fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {255
fn i420_from_bgra(bytes: &[u8], width: u32, height: u32, stride: u32) -> I420Buffer {180
let mut buffer = I420Buffer::new(width, height);256
let mut buffer = I420Buffer::new(width, height);181
let (stride_y, stride_u, stride_v) = buffer.strides();257
let (stride_y, stride_u, stride_v) = buffer.strides();@@ -237,11 +313,13 @@ pub fn start_screen_capture(237
*since = None;313
*since = None;238
}314
}239
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);315
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);240
if width >= 2 && height >= 2 {316
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {241
deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));317
deliver(picture);242
}318
}243
});319
});320
let sleeper = HighResSleep::new();244
while !stop.load(Ordering::SeqCst) {321
while !stop.load(Ordering::SeqCst) {322
let started = Instant::now();245
let gone = gone_since323
let gone = gone_since246
.lock()324
.lock()247
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));325
.is_ok_and(|since| since.is_some_and(|since| since.elapsed() >= SOURCE_GONE_AFTER));@@ -250,7 +328,8 @@ pub fn start_screen_capture(250
}328
}251
pump_messages();329
pump_messages();252
capturer.capture_frame();330
capturer.capture_frame();253
std::thread::sleep(Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1));331
let period = Duration::from_secs(1) / fps.load(Ordering::Relaxed).max(1);332
sleeper.sleep_until(started + period);254
}333
}255
})334
})256
.map_err(|error| Error::Webrtc(format!("screen thread: {error}")))335
.map_err(|error| Error::Webrtc(format!("screen thread: {error}")))@@ -360,8 +439,8 @@ pub(crate) fn start_portal_capture(360
}439
}361
let Ok(frame) = result else { return };440
let Ok(frame) = result else { return };362
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);441
let (width, height) = (frame.width() as u32 & !1, frame.height() as u32 & !1);363
if width >= 2 && height >= 2 {442
if let Some(picture) = share_frame(frame.data(), width, height, frame.stride()) {364
deliver(i420_from_bgra(frame.data(), width, height, frame.stride()));443
deliver(picture);365
}444
}366
});445
});367
if delegated {446
if delegated {@@ -421,6 +500,17 @@ pub(crate) fn start_portal_capture(421
mod tests {500
mod tests {422
use super::*;501
use super::*;423
502
503
#[test]504
fn a_wide_share_fits_the_send_budget_and_a_short_buffer_does_not() {505
use libwebrtc::video_frame::VideoBuffer;506
let (width, height) = fit_share_size(2560, 1440, SHARE_SEND_MAX_FS);507
assert!(macroblocks(width, height) <= SHARE_SEND_MAX_FS);508
let bytes = vec![0u8; 2560 * 1440 * 4];509
let frame = share_frame(&bytes, 2560, 1440, 2560 * 4).expect("scaled");510
assert!(macroblocks(frame.width(), frame.height()) <= SHARE_SEND_MAX_FS);511
assert!(share_frame(&[0u8; 8], 4, 2, 16).is_none());512
}513
424
#[test]514
#[test]425
fn sources_get_readable_labels() {515
fn sources_get_readable_labels() {426
let screen = ShareSource {516
let screen = ShareSource {@@ -811,9 +811,6 @@ fn with_opus_send_quality(fmtp: &str) -> String {
811
811
/// libwebrtc starts its bandwidth estimate at 300 kbit/s, which opens a 720p camera at 320x180.
812
812
const H264_SEND_START: [(&str, &str); 1] = [("x-google-start-bitrate", "1500")];
813
813
const H264_PROFILE_LEVEL_ID: &str = "profile-level-id=";
814
const H264_LEVEL_4_0: u8 = 0x28;
815
const FULL_HD_MAX_FS: u32 = 8160;
816
const FULL_HD_MAX_MBPS: u32 = 244_800;
817
814
818
815
/// Only touches H264 lines, the sole codec here that carries a `profile-level-id`.
819
816
fn with_h264_send_quality(fmtp: &str) -> String {
@@ -823,32 +820,66 @@ fn with_h264_send_quality(fmtp: &str) -> String {
823
820
with_fmtp_parameters(&with_full_hd_level(fmtp), &H264_SEND_START)
824
821
}
825
822
826
/// Teams answers level 3.1 even when its `max-fs` and `max-mbps` allow 1080p, and the encoder
827
/// stalls at 1080p on that level. The explicit limits are what the peer can really receive.
823
/// Teams answers a level below the frame size its own `max-fs` and `max-mbps` allow, and the
824
/// encoder stalls on every layer larger than that level. The explicit limits are what the peer
825
/// can really receive. The level is never lowered, and an answer without both limits stays as it is.
828
826
fn with_full_hd_level(fmtp: &str) -> String {
829
827
let limit = |name: &str| {
830
828
fmtp.split([' ', ';'])
831
829
.find_map(|parameter| parameter.strip_prefix(name)?.strip_prefix('='))
832
830
.and_then(|value| value.parse::<u32>().ok())
833
831
};
834
let allows_full_hd = limit("max-fs").is_some_and(|max_fs| max_fs >= FULL_HD_MAX_FS)
835
&& limit("max-mbps").is_some_and(|max_mbps| max_mbps >= FULL_HD_MAX_MBPS);
836
let level = fmtp
832
let (Some(max_fs), Some(max_mbps)) = (limit("max-fs"), limit("max-mbps")) else {
833
return fmtp.to_owned();
834
};
835
let Some(needed) = h264_level_for(max_fs, max_mbps) else {
836
return fmtp.to_owned();
837
};
838
let range = fmtp
837
839
.find(H264_PROFILE_LEVEL_ID)
838
840
.map(|start| start + H264_PROFILE_LEVEL_ID.len() + 4)
839
841
.map(|start| start..start + 2)
840
.filter(|range| {
841
fmtp.get(range.clone())
842
.and_then(|level| u8::from_str_radix(level, 16).ok())
843
.is_some_and(|level| level < H264_LEVEL_4_0)
844
});
845
let mut raised = fmtp.to_owned();
846
if let Some(range) = level.filter(|_| allows_full_hd) {
847
raised.replace_range(range, &format!("{H264_LEVEL_4_0:02x}"));
842
.filter(|range| range.end <= fmtp.len());
843
let Some(range) = range else {
844
return fmtp.to_owned();
845
};
846
let current = fmtp
847
.get(range.clone())
848
.and_then(|level| u8::from_str_radix(level, 16).ok());
849
if current.is_some_and(|level| level >= needed) {
850
return fmtp.to_owned();
848
851
}
852
let mut raised = fmtp.to_owned();
853
raised.replace_range(range, &format!("{needed:02x}"));
849
854
raised
850
855
}
851
856
857
/// H.264 Table A-1, lowest level whose MaxFS and MaxMBPS cover the peer limits.
858
fn h264_level_for(max_fs: u32, max_mbps: u32) -> Option<u8> {
859
const LEVELS: [(u8, u32, u32); 16] = [
860
(0x0a, 99, 1_485),
861
(0x0b, 396, 3_000),
862
(0x0c, 396, 6_000),
863
(0x0d, 396, 11_880),
864
(0x14, 396, 11_880),
865
(0x15, 792, 19_800),
866
(0x16, 1_620, 20_250),
867
(0x1e, 1_620, 40_500),
868
(0x1f, 3_600, 108_000),
869
(0x20, 5_120, 216_000),
870
(0x28, 8_192, 245_760),
871
(0x29, 8_192, 245_760),
872
(0x2a, 8_704, 522_240),
873
(0x32, 22_080, 589_824),
874
(0x33, 36_864, 983_040),
875
(0x34, 36_864, 2_073_600),
876
];
877
LEVELS
878
.into_iter()
879
.find(|(_, fs, mbps)| *fs >= max_fs && *mbps >= max_mbps)
880
.map(|(level, _, _)| level)
881
}
882
852
883
fn without_fmtp_parameter(fmtp: &str, name: &str) -> String {
853
884
let Some((payload, parameters)) = fmtp.split_once(' ') else {
854
885
return fmtp.to_owned();
@@ -1483,6 +1514,15 @@ mod tests {
1483
1514
with_h264_send_quality(hd),
1484
1515
"98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"
1485
1516
);
1517
let level_30 = "98 profile-level-id=42C01E;max-fs=3600;max-mbps=108000";
1518
assert_eq!(
1519
with_h264_send_quality(level_30),
1520
"98 profile-level-id=42C01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"
1521
);
1522
assert_eq!(
1523
with_h264_send_quality("98 profile-level-id=42C01E"),
1524
"98 profile-level-id=42C01E;x-google-start-bitrate=1500"
1525
);
1486
1526
assert_eq!(with_h264_send_quality("99 apt=98"), "99 apt=98");
1487
1527
assert_eq!(
1488
1528
without_fmtp_parameter(
@@ -811,9 +811,6 @@ fn with_opus_send_quality(fmtp: &str) -> String {811
/// libwebrtc starts its bandwidth estimate at 300 kbit/s, which opens a 720p camera at 320x180.811
/// libwebrtc starts its bandwidth estimate at 300 kbit/s, which opens a 720p camera at 320x180.812
const H264_SEND_START: [(&str, &str); 1] = [("x-google-start-bitrate", "1500")];812
const H264_SEND_START: [(&str, &str); 1] = [("x-google-start-bitrate", "1500")];813
const H264_PROFILE_LEVEL_ID: &str = "profile-level-id=";813
const H264_PROFILE_LEVEL_ID: &str = "profile-level-id=";814
const H264_LEVEL_4_0: u8 = 0x28;815
const FULL_HD_MAX_FS: u32 = 8160;816
const FULL_HD_MAX_MBPS: u32 = 244_800;817
814
818
/// Only touches H264 lines, the sole codec here that carries a `profile-level-id`.815
/// Only touches H264 lines, the sole codec here that carries a `profile-level-id`.819
fn with_h264_send_quality(fmtp: &str) -> String {816
fn with_h264_send_quality(fmtp: &str) -> String {@@ -823,32 +820,66 @@ fn with_h264_send_quality(fmtp: &str) -> String {823
with_fmtp_parameters(&with_full_hd_level(fmtp), &H264_SEND_START)820
with_fmtp_parameters(&with_full_hd_level(fmtp), &H264_SEND_START)824
}821
}825
822
826
/// Teams answers level 3.1 even when its `max-fs` and `max-mbps` allow 1080p, and the encoder823
/// Teams answers a level below the frame size its own `max-fs` and `max-mbps` allow, and the827
/// stalls at 1080p on that level. The explicit limits are what the peer can really receive.824
/// encoder stalls on every layer larger than that level. The explicit limits are what the peer825
/// can really receive. The level is never lowered, and an answer without both limits stays as it is.828
fn with_full_hd_level(fmtp: &str) -> String {826
fn with_full_hd_level(fmtp: &str) -> String {829
let limit = |name: &str| {827
let limit = |name: &str| {830
fmtp.split([' ', ';'])828
fmtp.split([' ', ';'])831
.find_map(|parameter| parameter.strip_prefix(name)?.strip_prefix('='))829
.find_map(|parameter| parameter.strip_prefix(name)?.strip_prefix('='))832
.and_then(|value| value.parse::<u32>().ok())830
.and_then(|value| value.parse::<u32>().ok())833
};831
};834
let allows_full_hd = limit("max-fs").is_some_and(|max_fs| max_fs >= FULL_HD_MAX_FS)832
let (Some(max_fs), Some(max_mbps)) = (limit("max-fs"), limit("max-mbps")) else {835
&& limit("max-mbps").is_some_and(|max_mbps| max_mbps >= FULL_HD_MAX_MBPS);833
return fmtp.to_owned();836
let level = fmtp834
};835
let Some(needed) = h264_level_for(max_fs, max_mbps) else {836
return fmtp.to_owned();837
};838
let range = fmtp837
.find(H264_PROFILE_LEVEL_ID)839
.find(H264_PROFILE_LEVEL_ID)838
.map(|start| start + H264_PROFILE_LEVEL_ID.len() + 4)840
.map(|start| start + H264_PROFILE_LEVEL_ID.len() + 4)839
.map(|start| start..start + 2)841
.map(|start| start..start + 2)840
.filter(|range| {842
.filter(|range| range.end <= fmtp.len());841
fmtp.get(range.clone())843
let Some(range) = range else {842
.and_then(|level| u8::from_str_radix(level, 16).ok())844
return fmtp.to_owned();843
.is_some_and(|level| level < H264_LEVEL_4_0)845
};844
});846
let current = fmtp845
let mut raised = fmtp.to_owned();847
.get(range.clone())846
if let Some(range) = level.filter(|_| allows_full_hd) {848
.and_then(|level| u8::from_str_radix(level, 16).ok());847
raised.replace_range(range, &format!("{H264_LEVEL_4_0:02x}"));849
if current.is_some_and(|level| level >= needed) {850
return fmtp.to_owned();848
}851
}852
let mut raised = fmtp.to_owned();853
raised.replace_range(range, &format!("{needed:02x}"));849
raised854
raised850
}855
}851
856
857
/// H.264 Table A-1, lowest level whose MaxFS and MaxMBPS cover the peer limits.858
fn h264_level_for(max_fs: u32, max_mbps: u32) -> Option<u8> {859
const LEVELS: [(u8, u32, u32); 16] = [860
(0x0a, 99, 1_485),861
(0x0b, 396, 3_000),862
(0x0c, 396, 6_000),863
(0x0d, 396, 11_880),864
(0x14, 396, 11_880),865
(0x15, 792, 19_800),866
(0x16, 1_620, 20_250),867
(0x1e, 1_620, 40_500),868
(0x1f, 3_600, 108_000),869
(0x20, 5_120, 216_000),870
(0x28, 8_192, 245_760),871
(0x29, 8_192, 245_760),872
(0x2a, 8_704, 522_240),873
(0x32, 22_080, 589_824),874
(0x33, 36_864, 983_040),875
(0x34, 36_864, 2_073_600),876
];877
LEVELS878
.into_iter()879
.find(|(_, fs, mbps)| *fs >= max_fs && *mbps >= max_mbps)880
.map(|(level, _, _)| level)881
}882
852
fn without_fmtp_parameter(fmtp: &str, name: &str) -> String {883
fn without_fmtp_parameter(fmtp: &str, name: &str) -> String {853
let Some((payload, parameters)) = fmtp.split_once(' ') else {884
let Some((payload, parameters)) = fmtp.split_once(' ') else {854
return fmtp.to_owned();885
return fmtp.to_owned();@@ -1483,6 +1514,15 @@ mod tests {1483
with_h264_send_quality(hd),1514
with_h264_send_quality(hd),1484
"98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"1515
"98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"1485
);1516
);1517
let level_30 = "98 profile-level-id=42C01E;max-fs=3600;max-mbps=108000";1518
assert_eq!(1519
with_h264_send_quality(level_30),1520
"98 profile-level-id=42C01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"1521
);1522
assert_eq!(1523
with_h264_send_quality("98 profile-level-id=42C01E"),1524
"98 profile-level-id=42C01E;x-google-start-bitrate=1500"1525
);1486
assert_eq!(with_h264_send_quality("99 apt=98"), "99 apt=98");1526
assert_eq!(with_h264_send_quality("99 apt=98"), "99 apt=98");1487
assert_eq!(1527
assert_eq!(1488
without_fmtp_parameter(1528
without_fmtp_parameter(@@ -34,19 +34,22 @@ pub fn rungs(onnx_runtime: bool, gpu: bool, on_battery: bool) -> Vec<Rung> {
34
34
spec: MEDIAPIPE,
35
35
device: Device::Cpu { threads: 1 },
36
36
}];
37
if on_battery || !onnx_runtime {
37
if !onnx_runtime {
38
38
return rungs;
39
39
}
40
40
if gpu {
41
// DirectML iGPU runs MODNET_SMALL efficiently even on battery; only skip MODNET_LARGE on battery.
41
42
rungs.push(Rung {
42
43
spec: MODNET_SMALL,
43
44
device: Device::Gpu,
44
45
});
45
rungs.push(Rung {
46
spec: MODNET_LARGE,
47
device: Device::Gpu,
48
});
49
} else {
46
if !on_battery {
47
rungs.push(Rung {
48
spec: MODNET_LARGE,
49
device: Device::Gpu,
50
});
51
}
52
} else if !on_battery {
50
53
rungs.push(Rung {
51
54
spec: MODNET_SMALL,
52
55
device: Device::Cpu {
@@ -344,7 +347,20 @@ mod tests {
344
347
345
348
#[test]
346
349
fn battery_missing_gpu_and_missing_onnx_runtime_shorten_the_ladder() {
347
assert_eq!(rungs(true, true, true).len(), 1);
350
assert_eq!(
351
rungs(true, true, true),
352
vec![
353
Rung {
354
spec: MEDIAPIPE,
355
device: Device::Cpu { threads: 1 },
356
},
357
Rung {
358
spec: MODNET_SMALL,
359
device: Device::Gpu,
360
},
361
]
362
);
363
assert_eq!(rungs(true, false, true).len(), 1);
348
364
assert_eq!(
349
365
rungs(false, false, false).len(),
350
366
1,
@@ -34,19 +34,22 @@ pub fn rungs(onnx_runtime: bool, gpu: bool, on_battery: bool) -> Vec<Rung> {34
spec: MEDIAPIPE,34
spec: MEDIAPIPE,35
device: Device::Cpu { threads: 1 },35
device: Device::Cpu { threads: 1 },36
}];36
}];37
if on_battery || !onnx_runtime {37
if !onnx_runtime {38
return rungs;38
return rungs;39
}39
}40
if gpu {40
if gpu {41
// DirectML iGPU runs MODNET_SMALL efficiently even on battery; only skip MODNET_LARGE on battery.41
rungs.push(Rung {42
rungs.push(Rung {42
spec: MODNET_SMALL,43
spec: MODNET_SMALL,43
device: Device::Gpu,44
device: Device::Gpu,44
});45
});45
rungs.push(Rung {46
if !on_battery {46
spec: MODNET_LARGE,47
rungs.push(Rung {47
device: Device::Gpu,48
spec: MODNET_LARGE,48
});49
device: Device::Gpu,49
} else {50
});51
}52
} else if !on_battery {50
rungs.push(Rung {53
rungs.push(Rung {51
spec: MODNET_SMALL,54
spec: MODNET_SMALL,52
device: Device::Cpu {55
device: Device::Cpu {@@ -344,7 +347,20 @@ mod tests {344
347
345
#[test]348
#[test]346
fn battery_missing_gpu_and_missing_onnx_runtime_shorten_the_ladder() {349
fn battery_missing_gpu_and_missing_onnx_runtime_shorten_the_ladder() {347
assert_eq!(rungs(true, true, true).len(), 1);350
assert_eq!(351
rungs(true, true, true),352
vec![353
Rung {354
spec: MEDIAPIPE,355
device: Device::Cpu { threads: 1 },356
},357
Rung {358
spec: MODNET_SMALL,359
device: Device::Gpu,360
},361
]362
);363
assert_eq!(rungs(true, false, true).len(), 1);348
assert_eq!(364
assert_eq!(349
rungs(false, false, false).len(),365
rungs(false, false, false).len(),350
1,366
1,@@ -20,6 +20,7 @@ use crate::mixer::mix_frames;
20
20
use crate::pcm::SampleQueue;
21
21
use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};
22
22
use crate::wav_dump::StageDumps;
23
use crate::win_timer::HighResSleep;
23
24
24
25
/// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime.
25
26
const SOURCE_QUEUE_MS: u32 = 0;
@@ -65,12 +66,13 @@ struct Feeder {
65
66
impl Feeder {
66
67
fn run(mut self) {
67
68
let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());
69
let sleeper = HighResSleep::new();
68
70
let mut due = Instant::now();
69
71
while self.running.load(Ordering::SeqCst) {
70
72
due += FRAME_PERIOD;
71
73
let now = Instant::now();
72
74
if due > now {
73
std::thread::sleep(due - now);
75
sleeper.sleep(due - now);
74
76
} else if now - due > MAX_LAG {
75
77
due = now;
76
78
}
@@ -78,7 +80,12 @@ impl Feeder {
78
80
chain.process_far_end(&mut far_end);
79
81
}
80
82
let muted = self.microphone_muted.load(Ordering::SeqCst);
81
let microphone = match self.microphone.next_frame() {
83
let captured = self.microphone.next_frame().or_else(|| {
84
// Small 2 ms cushion for WASAPI/CPAL callback cadence jitter before emitting silence.
85
sleeper.sleep(Duration::from_millis(2));
86
self.microphone.next_frame()
87
});
88
let microphone = match captured {
82
89
Some(mut frame) if !muted => {
83
90
chain.process(&mut frame);
84
91
frame
@@ -127,21 +134,14 @@ pub struct SoftwareAudio {
127
134
128
135
impl SoftwareAudioPlan {
129
136
pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
130
Self::wanted_on(cfg!(windows), mic, sharing_sound, uses_devices)
137
Self::wanted_on(mic, sharing_sound, uses_devices)
131
138
}
132
139
133
pub fn wanted_on(
134
windows: bool,
135
mic: MicSettings,
136
sharing_sound: bool,
137
uses_devices: bool,
138
) -> Option<Self> {
139
(sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| {
140
SoftwareAudioPlan {
141
processing: mic.apm_config(),
142
ml_noise: mic.ml_noise_suppression(),
143
computer_sound: sharing_sound,
144
}
140
pub fn wanted_on(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {
141
(sharing_sound || (uses_devices && !mic.uses_device_track())).then(|| SoftwareAudioPlan {
142
processing: mic.apm_config(),
143
ml_noise: mic.ml_noise_suppression(),
144
computer_sound: sharing_sound,
145
145
})
146
146
}
147
147
}
@@ -171,41 +171,47 @@ impl SoftwareAudio {
171
171
(FrameSource::Silence, None)
172
172
};
173
173
let microphone_queue = SampleQueue::default();
174
let microphone = match start_microphone(input, microphone_queue.clone()) {
175
Ok(started) => {
176
microphone_source = Some(started.source);
177
captures.push(started.capture);
178
FrameSource::Captured(microphone_queue)
179
}
180
Err(error) => {
181
if !plan.computer_sound {
182
return Err(error);
174
let label = crate::devices::input_label(factory, input);
175
let microphone =
176
match start_microphone(input, label.as_deref(), microphone_queue.clone()) {
177
Ok(started) => {
178
microphone_source = Some(started.source);
179
captures.push(started.capture);
180
FrameSource::Captured(microphone_queue)
183
181
}
184
let fallback_queue = SampleQueue::default();
185
let fallback = Some(input)
186
.filter(|input| **input != DeviceChoice::SystemDefault)
187
.and_then(|_| {
188
start_microphone(&DeviceChoice::SystemDefault, fallback_queue.clone())
189
.ok()
190
});
191
match fallback {
192
Some(started) => {
193
microphone_notice = Some(DEFAULT_MICROPHONE_NOTICE);
194
microphone_source =
195
Some(format!("{}, picked one failed: {error}", started.source));
196
captures.push(started.capture);
197
FrameSource::Captured(fallback_queue)
182
Err(error) => {
183
if !plan.computer_sound {
184
return Err(error);
198
185
}
199
None => {
200
microphone_notice = Some(NO_MICROPHONE_NOTICE);
201
warning.get_or_insert(format!(
202
"microphone not captured while sharing sound: {error}"
203
));
204
FrameSource::Silence
186
let fallback_queue = SampleQueue::default();
187
let fallback = (input != &DeviceChoice::SystemDefault)
188
.then(|| {
189
start_microphone(
190
&DeviceChoice::SystemDefault,
191
None,
192
fallback_queue.clone(),
193
)
194
.ok()
195
})
196
.flatten();
197
match fallback {
198
Some(started) => {
199
microphone_notice = Some(DEFAULT_MICROPHONE_NOTICE);
200
microphone_source =
201
Some(format!("{}, picked one failed: {error}", started.source));
202
captures.push(started.capture);
203
FrameSource::Captured(fallback_queue)
204
}
205
None => {
206
microphone_notice = Some(NO_MICROPHONE_NOTICE);
207
warning.get_or_insert(format!(
208
"microphone not captured while sharing sound: {error}"
209
));
210
FrameSource::Silence
211
}
205
212
}
206
213
}
207
}
208
};
214
};
209
215
(microphone, computer, loopback)
210
216
} else {
211
217
let microphone = if mode == AudioMode::Tone {
@@ -333,15 +339,14 @@ mod tests {
333
339
}
334
340
335
341
#[test]
336
fn default_settings_use_the_device_track_on_linux() {
342
fn default_settings_use_the_device_track_on_all_platforms() {
337
343
let default = MicSettings::default();
338
assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());
339
assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());
344
assert!(SoftwareAudioPlan::wanted_on(default, false, true).is_none());
340
345
let low = MicSettings {
341
346
noise_suppression: NoiseSuppression::Low,
342
347
music_mode: false,
343
348
};
344
assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());
349
assert!(SoftwareAudioPlan::wanted_on(low, false, true).is_none());
345
350
}
346
351
347
352
#[test]
@@ -355,28 +360,27 @@ mod tests {
355
360
noise_suppression: NoiseSuppression::Low,
356
361
music_mode: false,
357
362
};
358
assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);
359
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);
360
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();
363
assert_eq!(SoftwareAudioPlan::wanted_on(low, false, true), None);
364
assert_eq!(SoftwareAudioPlan::wanted_on(off, false, false), None);
365
let mic_only = SoftwareAudioPlan::wanted_on(off, false, true).unwrap();
361
366
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());
362
let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();
367
let sharing = SoftwareAudioPlan::wanted_on(auto, true, false).unwrap();
363
368
assert!(sharing.computer_sound && sharing.processing.echo_canceller);
364
369
}
365
370
366
371
#[test]
367
fn windows_runs_the_software_path_for_every_mic_setting() {
372
fn windows_uses_software_path_only_when_not_on_device_track() {
368
373
for noise_suppression in NoiseSuppression::ALL {
369
374
for music_mode in [false, true] {
370
375
let mic = MicSettings {
371
376
noise_suppression,
372
377
music_mode,
373
378
};
374
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());
375
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());
376
379
assert_eq!(
377
SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(),
378
!mic.uses_device_track_on(false)
380
SoftwareAudioPlan::wanted_on(mic, false, true).is_some(),
381
!mic.uses_device_track()
379
382
);
383
assert!(SoftwareAudioPlan::wanted_on(mic, false, false).is_none());
380
384
}
381
385
}
382
386
}
@@ -385,12 +389,11 @@ mod tests {
385
389
fn rnnoise_runs_in_the_software_path_only_for_auto() {
386
390
let ml_noise = |noise_suppression, music_mode| {
387
391
SoftwareAudioPlan::wanted_on(
388
true,
389
392
MicSettings {
390
393
noise_suppression,
391
394
music_mode,
392
395
},
393
false,
396
true,
394
397
true,
395
398
)
396
399
.unwrap()
@@ -20,6 +20,7 @@ use crate::mixer::mix_frames;20
use crate::pcm::SampleQueue;20
use crate::pcm::SampleQueue;21
use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};21
use crate::sound_capture::{LoopbackKind, start_loopback, start_microphone};22
use crate::wav_dump::StageDumps;22
use crate::wav_dump::StageDumps;23
use crate::win_timer::HighResSleep;23
24
24
/// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime.25
/// Direct capture: 10 ms frames complete synchronously, so the feeder never parks on the Tokio runtime.25
const SOURCE_QUEUE_MS: u32 = 0;26
const SOURCE_QUEUE_MS: u32 = 0;@@ -65,12 +66,13 @@ struct Feeder {65
impl Feeder {66
impl Feeder {66
fn run(mut self) {67
fn run(mut self) {67
let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());68
let mut chain = MicChain::new(self.processing, self.ml_noise, StageDumps::from_env());69
let sleeper = HighResSleep::new();68
let mut due = Instant::now();70
let mut due = Instant::now();69
while self.running.load(Ordering::SeqCst) {71
while self.running.load(Ordering::SeqCst) {70
due += FRAME_PERIOD;72
due += FRAME_PERIOD;71
let now = Instant::now();73
let now = Instant::now();72
if due > now {74
if due > now {73
std::thread::sleep(due - now);75
sleeper.sleep(due - now);74
} else if now - due > MAX_LAG {76
} else if now - due > MAX_LAG {75
due = now;77
due = now;76
}78
}@@ -78,7 +80,12 @@ impl Feeder {78
chain.process_far_end(&mut far_end);80
chain.process_far_end(&mut far_end);79
}81
}80
let muted = self.microphone_muted.load(Ordering::SeqCst);82
let muted = self.microphone_muted.load(Ordering::SeqCst);81
let microphone = match self.microphone.next_frame() {83
let captured = self.microphone.next_frame().or_else(|| {84
// Small 2 ms cushion for WASAPI/CPAL callback cadence jitter before emitting silence.85
sleeper.sleep(Duration::from_millis(2));86
self.microphone.next_frame()87
});88
let microphone = match captured {82
Some(mut frame) if !muted => {89
Some(mut frame) if !muted => {83
chain.process(&mut frame);90
chain.process(&mut frame);84
frame91
frame@@ -127,21 +134,14 @@ pub struct SoftwareAudio {127
134
128
impl SoftwareAudioPlan {135
impl SoftwareAudioPlan {129
pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {136
pub fn wanted(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {130
Self::wanted_on(cfg!(windows), mic, sharing_sound, uses_devices)137
Self::wanted_on(mic, sharing_sound, uses_devices)131
}138
}132
139
133
pub fn wanted_on(140
pub fn wanted_on(mic: MicSettings, sharing_sound: bool, uses_devices: bool) -> Option<Self> {134
windows: bool,141
(sharing_sound || (uses_devices && !mic.uses_device_track())).then(|| SoftwareAudioPlan {135
mic: MicSettings,142
processing: mic.apm_config(),136
sharing_sound: bool,143
ml_noise: mic.ml_noise_suppression(),137
uses_devices: bool,144
computer_sound: sharing_sound,138
) -> Option<Self> {139
(sharing_sound || (uses_devices && !mic.uses_device_track_on(windows))).then(|| {140
SoftwareAudioPlan {141
processing: mic.apm_config(),142
ml_noise: mic.ml_noise_suppression(),143
computer_sound: sharing_sound,144
}145
})145
})146
}146
}147
}147
}@@ -171,41 +171,47 @@ impl SoftwareAudio {171
(FrameSource::Silence, None)171
(FrameSource::Silence, None)172
};172
};173
let microphone_queue = SampleQueue::default();173
let microphone_queue = SampleQueue::default();174
let microphone = match start_microphone(input, microphone_queue.clone()) {174
let label = crate::devices::input_label(factory, input);175
Ok(started) => {175
let microphone =176
microphone_source = Some(started.source);176
match start_microphone(input, label.as_deref(), microphone_queue.clone()) {177
captures.push(started.capture);177
Ok(started) => {178
FrameSource::Captured(microphone_queue)178
microphone_source = Some(started.source);179
}179
captures.push(started.capture);180
Err(error) => {180
FrameSource::Captured(microphone_queue)181
if !plan.computer_sound {182
return Err(error);183
}181
}184
let fallback_queue = SampleQueue::default();182
Err(error) => {185
let fallback = Some(input)183
if !plan.computer_sound {186
.filter(|input| **input != DeviceChoice::SystemDefault)184
return Err(error);187
.and_then(|_| {188
start_microphone(&DeviceChoice::SystemDefault, fallback_queue.clone())189
.ok()190
});191
match fallback {192
Some(started) => {193
microphone_notice = Some(DEFAULT_MICROPHONE_NOTICE);194
microphone_source =195
Some(format!("{}, picked one failed: {error}", started.source));196
captures.push(started.capture);197
FrameSource::Captured(fallback_queue)198
}185
}199
None => {186
let fallback_queue = SampleQueue::default();200
microphone_notice = Some(NO_MICROPHONE_NOTICE);187
let fallback = (input != &DeviceChoice::SystemDefault)201
warning.get_or_insert(format!(188
.then(|| {202
"microphone not captured while sharing sound: {error}"189
start_microphone(203
));190
&DeviceChoice::SystemDefault,204
FrameSource::Silence191
None,192
fallback_queue.clone(),193
)194
.ok()195
})196
.flatten();197
match fallback {198
Some(started) => {199
microphone_notice = Some(DEFAULT_MICROPHONE_NOTICE);200
microphone_source =201
Some(format!("{}, picked one failed: {error}", started.source));202
captures.push(started.capture);203
FrameSource::Captured(fallback_queue)204
}205
None => {206
microphone_notice = Some(NO_MICROPHONE_NOTICE);207
warning.get_or_insert(format!(208
"microphone not captured while sharing sound: {error}"209
));210
FrameSource::Silence211
}205
}212
}206
}213
}207
}214
};208
};209
(microphone, computer, loopback)215
(microphone, computer, loopback)210
} else {216
} else {211
let microphone = if mode == AudioMode::Tone {217
let microphone = if mode == AudioMode::Tone {@@ -333,15 +339,14 @@ mod tests {333
}339
}334
340
335
#[test]341
#[test]336
fn default_settings_use_the_device_track_on_linux() {342
fn default_settings_use_the_device_track_on_all_platforms() {337
let default = MicSettings::default();343
let default = MicSettings::default();338
assert!(SoftwareAudioPlan::wanted_on(true, default, false, true).is_some());344
assert!(SoftwareAudioPlan::wanted_on(default, false, true).is_none());339
assert!(SoftwareAudioPlan::wanted_on(false, default, false, true).is_none());340
let low = MicSettings {345
let low = MicSettings {341
noise_suppression: NoiseSuppression::Low,346
noise_suppression: NoiseSuppression::Low,342
music_mode: false,347
music_mode: false,343
};348
};344
assert!(SoftwareAudioPlan::wanted_on(false, low, false, true).is_none());349
assert!(SoftwareAudioPlan::wanted_on(low, false, true).is_none());345
}350
}346
351
347
#[test]352
#[test]@@ -355,28 +360,27 @@ mod tests {355
noise_suppression: NoiseSuppression::Low,360
noise_suppression: NoiseSuppression::Low,356
music_mode: false,361
music_mode: false,357
};362
};358
assert_eq!(SoftwareAudioPlan::wanted_on(false, low, false, true), None);363
assert_eq!(SoftwareAudioPlan::wanted_on(low, false, true), None);359
assert_eq!(SoftwareAudioPlan::wanted_on(false, off, false, false), None);364
assert_eq!(SoftwareAudioPlan::wanted_on(off, false, false), None);360
let mic_only = SoftwareAudioPlan::wanted_on(false, off, false, true).unwrap();365
let mic_only = SoftwareAudioPlan::wanted_on(off, false, true).unwrap();361
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());366
assert!(!mic_only.computer_sound && mic_only.processing.is_passthrough());362
let sharing = SoftwareAudioPlan::wanted_on(false, auto, true, false).unwrap();367
let sharing = SoftwareAudioPlan::wanted_on(auto, true, false).unwrap();363
assert!(sharing.computer_sound && sharing.processing.echo_canceller);368
assert!(sharing.computer_sound && sharing.processing.echo_canceller);364
}369
}365
370
366
#[test]371
#[test]367
fn windows_runs_the_software_path_for_every_mic_setting() {372
fn windows_uses_software_path_only_when_not_on_device_track() {368
for noise_suppression in NoiseSuppression::ALL {373
for noise_suppression in NoiseSuppression::ALL {369
for music_mode in [false, true] {374
for music_mode in [false, true] {370
let mic = MicSettings {375
let mic = MicSettings {371
noise_suppression,376
noise_suppression,372
music_mode,377
music_mode,373
};378
};374
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, true).is_some());375
assert!(SoftwareAudioPlan::wanted_on(true, mic, false, false).is_none());376
assert_eq!(379
assert_eq!(377
SoftwareAudioPlan::wanted_on(false, mic, false, true).is_some(),380
SoftwareAudioPlan::wanted_on(mic, false, true).is_some(),378
!mic.uses_device_track_on(false)381
!mic.uses_device_track()379
);382
);383
assert!(SoftwareAudioPlan::wanted_on(mic, false, false).is_none());380
}384
}381
}385
}382
}386
}@@ -385,12 +389,11 @@ mod tests {385
fn rnnoise_runs_in_the_software_path_only_for_auto() {389
fn rnnoise_runs_in_the_software_path_only_for_auto() {386
let ml_noise = |noise_suppression, music_mode| {390
let ml_noise = |noise_suppression, music_mode| {387
SoftwareAudioPlan::wanted_on(391
SoftwareAudioPlan::wanted_on(388
true,389
MicSettings {392
MicSettings {390
noise_suppression,393
noise_suppression,391
music_mode,394
music_mode,392
},395
},393
false,396
true,394
true,397
true,395
)398
)396
.unwrap()399
.unwrap()@@ -32,17 +32,37 @@ fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
32
32
Error::Audio(format!("{what}: {error}"))
33
33
}
34
34
35
fn named_input(choice: &DeviceChoice) -> Option<Device> {
36
let DeviceChoice::Device(wanted) = choice else {
37
return None;
38
};
35
pub fn capture_name_matches(device_name: &str, target: &str) -> bool {
36
if target.is_empty() {
37
return false;
38
}
39
if device_name.eq_ignore_ascii_case(target) {
40
return true;
41
}
42
// cpal on Linux and macOS uses ALSA or CoreAudio names, which differ from
43
// the Pulse or CoreAudio descriptions in the device list.
44
#[cfg(not(windows))]
45
{
46
let device = device_name.to_ascii_lowercase();
47
let wanted = target.to_ascii_lowercase();
48
return device.contains(&wanted) || wanted.contains(&device);
49
}
50
#[cfg(windows)]
51
false
52
}
53
54
fn named_input(wanted: &str, label: Option<&str>) -> Option<Device> {
55
#[cfg(windows)]
56
let resolved = crate::mic_windows::friendly_name_for_id(wanted);
57
#[cfg(not(windows))]
58
let resolved: Option<String> = None;
59
let target = resolved.as_deref().or(label).unwrap_or(wanted);
39
60
let host = cpal::default_host();
40
61
let mut devices = host.input_devices().ok()?;
41
62
devices.find(|device| {
42
device.description().is_ok_and(|description| {
43
let name = description.name();
44
name == *wanted || name.contains(wanted) || wanted.contains(&name)
45
})
63
device
64
.description()
65
.is_ok_and(|description| capture_name_matches(&description.name(), target))
46
66
})
47
67
}
48
68
@@ -52,7 +72,11 @@ pub struct MicrophoneStart {
52
72
}
53
73
54
74
#[cfg(windows)]
55
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
75
pub fn start_microphone(
76
choice: &DeviceChoice,
77
label: Option<&str>,
78
queue: SampleQueue,
79
) -> Result<MicrophoneStart> {
56
80
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {
57
81
Ok((capture, name, effects)) => {
58
82
let active: Vec<String> = effects
@@ -69,7 +93,7 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
69
93
})
70
94
}
71
95
Err(error) => {
72
let (capture, name) = start_cpal_microphone(choice, queue)?;
96
let (capture, name) = start_cpal_microphone(choice, label, queue)?;
73
97
Ok(MicrophoneStart {
74
98
capture,
75
99
source: format!("cpal ({name}), wasapi communications failed: {error}"),
@@ -79,20 +103,28 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic
79
103
}
80
104
81
105
#[cfg(not(windows))]
82
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
83
let (capture, name) = start_cpal_microphone(choice, queue)?;
106
pub fn start_microphone(
107
choice: &DeviceChoice,
108
label: Option<&str>,
109
queue: SampleQueue,
110
) -> Result<MicrophoneStart> {
111
let (capture, name) = start_cpal_microphone(choice, label, queue)?;
84
112
Ok(MicrophoneStart {
85
113
capture,
86
114
source: format!("cpal ({name})"),
87
115
})
88
116
}
89
117
90
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {
118
fn start_cpal_microphone(
119
choice: &DeviceChoice,
120
label: Option<&str>,
121
queue: SampleQueue,
122
) -> Result<(Capture, String)> {
91
123
let device = match choice {
92
124
DeviceChoice::SystemDefault => cpal::default_host()
93
125
.default_input_device()
94
126
.ok_or_else(|| Error::Audio("no microphone".into()))?,
95
DeviceChoice::Device(wanted) => named_input(choice).ok_or_else(|| {
127
DeviceChoice::Device(wanted) => named_input(wanted, label).ok_or_else(|| {
96
128
Error::Audio(format!(
97
129
"microphone `{wanted}` not found for capture; pick Default device or another mic"
98
130
))
@@ -267,3 +299,35 @@ fn build_stream(
267
299
}
268
300
.map_err(|error| audio_error("open input", error))
269
301
}
302
303
#[cfg(test)]
304
mod tests {
305
use super::capture_name_matches;
306
307
#[test]
308
fn a_named_microphone_matches_the_listed_name() {
309
assert!(capture_name_matches(
310
"Headset Microphone",
311
"headset microphone"
312
));
313
assert!(!capture_name_matches(
314
"Headset Microphone",
315
"{0.0.0.00000000}.{bbbb}"
316
));
317
assert!(!capture_name_matches("Mic", ""));
318
#[cfg(windows)]
319
assert!(!capture_name_matches("Headset Microphone", "Microphone"));
320
#[cfg(not(windows))]
321
{
322
assert!(capture_name_matches("sysdefault:CARD=Jabra", "Jabra"));
323
assert!(capture_name_matches(
324
"Jabra Speak 750 Mono",
325
"Jabra Speak 750"
326
));
327
assert!(capture_name_matches(
328
"Jabra Speak 750",
329
"Jabra Speak 750 Mono"
330
));
331
}
332
}
333
}
@@ -32,17 +32,37 @@ fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {32
Error::Audio(format!("{what}: {error}"))32
Error::Audio(format!("{what}: {error}"))33
}33
}34
34
35
fn named_input(choice: &DeviceChoice) -> Option<Device> {35
pub fn capture_name_matches(device_name: &str, target: &str) -> bool {36
let DeviceChoice::Device(wanted) = choice else {36
if target.is_empty() {37
return None;37
return false;38
};38
}39
if device_name.eq_ignore_ascii_case(target) {40
return true;41
}42
// cpal on Linux and macOS uses ALSA or CoreAudio names, which differ from43
// the Pulse or CoreAudio descriptions in the device list.44
#[cfg(not(windows))]45
{46
let device = device_name.to_ascii_lowercase();47
let wanted = target.to_ascii_lowercase();48
return device.contains(&wanted) || wanted.contains(&device);49
}50
#[cfg(windows)]51
false52
}53
54
fn named_input(wanted: &str, label: Option<&str>) -> Option<Device> {55
#[cfg(windows)]56
let resolved = crate::mic_windows::friendly_name_for_id(wanted);57
#[cfg(not(windows))]58
let resolved: Option<String> = None;59
let target = resolved.as_deref().or(label).unwrap_or(wanted);39
let host = cpal::default_host();60
let host = cpal::default_host();40
let mut devices = host.input_devices().ok()?;61
let mut devices = host.input_devices().ok()?;41
devices.find(|device| {62
devices.find(|device| {42
device.description().is_ok_and(|description| {63
device43
let name = description.name();64
.description()44
name == *wanted || name.contains(wanted) || wanted.contains(&name)65
.is_ok_and(|description| capture_name_matches(&description.name(), target))45
})46
})66
})47
}67
}48
68
@@ -52,7 +72,11 @@ pub struct MicrophoneStart {52
}72
}53
73
54
#[cfg(windows)]74
#[cfg(windows)]55
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {75
pub fn start_microphone(76
choice: &DeviceChoice,77
label: Option<&str>,78
queue: SampleQueue,79
) -> Result<MicrophoneStart> {56
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {80
match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {57
Ok((capture, name, effects)) => {81
Ok((capture, name, effects)) => {58
let active: Vec<String> = effects82
let active: Vec<String> = effects@@ -69,7 +93,7 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic69
})93
})70
}94
}71
Err(error) => {95
Err(error) => {72
let (capture, name) = start_cpal_microphone(choice, queue)?;96
let (capture, name) = start_cpal_microphone(choice, label, queue)?;73
Ok(MicrophoneStart {97
Ok(MicrophoneStart {74
capture,98
capture,75
source: format!("cpal ({name}), wasapi communications failed: {error}"),99
source: format!("cpal ({name}), wasapi communications failed: {error}"),@@ -79,20 +103,28 @@ pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Mic79
}103
}80
104
81
#[cfg(not(windows))]105
#[cfg(not(windows))]82
pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {106
pub fn start_microphone(83
let (capture, name) = start_cpal_microphone(choice, queue)?;107
choice: &DeviceChoice,108
label: Option<&str>,109
queue: SampleQueue,110
) -> Result<MicrophoneStart> {111
let (capture, name) = start_cpal_microphone(choice, label, queue)?;84
Ok(MicrophoneStart {112
Ok(MicrophoneStart {85
capture,113
capture,86
source: format!("cpal ({name})"),114
source: format!("cpal ({name})"),87
})115
})88
}116
}89
117
90
fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<(Capture, String)> {118
fn start_cpal_microphone(119
choice: &DeviceChoice,120
label: Option<&str>,121
queue: SampleQueue,122
) -> Result<(Capture, String)> {91
let device = match choice {123
let device = match choice {92
DeviceChoice::SystemDefault => cpal::default_host()124
DeviceChoice::SystemDefault => cpal::default_host()93
.default_input_device()125
.default_input_device()94
.ok_or_else(|| Error::Audio("no microphone".into()))?,126
.ok_or_else(|| Error::Audio("no microphone".into()))?,95
DeviceChoice::Device(wanted) => named_input(choice).ok_or_else(|| {127
DeviceChoice::Device(wanted) => named_input(wanted, label).ok_or_else(|| {96
Error::Audio(format!(128
Error::Audio(format!(97
"microphone `{wanted}` not found for capture; pick Default device or another mic"129
"microphone `{wanted}` not found for capture; pick Default device or another mic"98
))130
))@@ -267,3 +299,35 @@ fn build_stream(267
}299
}268
.map_err(|error| audio_error("open input", error))300
.map_err(|error| audio_error("open input", error))269
}301
}302
303
#[cfg(test)]304
mod tests {305
use super::capture_name_matches;306
307
#[test]308
fn a_named_microphone_matches_the_listed_name() {309
assert!(capture_name_matches(310
"Headset Microphone",311
"headset microphone"312
));313
assert!(!capture_name_matches(314
"Headset Microphone",315
"{0.0.0.00000000}.{bbbb}"316
));317
assert!(!capture_name_matches("Mic", ""));318
#[cfg(windows)]319
assert!(!capture_name_matches("Headset Microphone", "Microphone"));320
#[cfg(not(windows))]321
{322
assert!(capture_name_matches("sysdefault:CARD=Jabra", "Jabra"));323
assert!(capture_name_matches(324
"Jabra Speak 750 Mono",325
"Jabra Speak 750"326
));327
assert!(capture_name_matches(328
"Jabra Speak 750",329
"Jabra Speak 750 Mono"330
));331
}332
}333
}@@ -1,6 +1,6 @@
1
1
use crate::audio::SAMPLE_RATE;
2
2
3
pub const CUTOFF_HZ: f32 = 120.0;
3
pub const CUTOFF_HZ: f32 = 80.0;
4
4
const BUTTERWORTH_FOURTH_ORDER_Q: [f32; 2] = [0.541_196_1, 1.306_563];
5
5
6
6
#[derive(Debug, Clone, Copy)]
@@ -115,6 +115,6 @@ mod tests {
115
115
"cutoff {}",
116
116
gain_db(CUTOFF_HZ)
117
117
);
118
assert!(gain_db(60.0) < -20.0, "60 Hz {}", gain_db(60.0));
118
assert!(gain_db(40.0) < -20.0, "40 Hz {}", gain_db(40.0));
119
119
}
120
120
}
@@ -1,6 +1,6 @@1
use crate::audio::SAMPLE_RATE;1
use crate::audio::SAMPLE_RATE;2
2
3
pub const CUTOFF_HZ: f32 = 120.0;3
pub const CUTOFF_HZ: f32 = 80.0;4
const BUTTERWORTH_FOURTH_ORDER_Q: [f32; 2] = [0.541_196_1, 1.306_563];4
const BUTTERWORTH_FOURTH_ORDER_Q: [f32; 2] = [0.541_196_1, 1.306_563];5
5
6
#[derive(Debug, Clone, Copy)]6
#[derive(Debug, Clone, Copy)]@@ -115,6 +115,6 @@ mod tests {115
"cutoff {}",115
"cutoff {}",116
gain_db(CUTOFF_HZ)116
gain_db(CUTOFF_HZ)117
);117
);118
assert!(gain_db(60.0) < -20.0, "60 Hz {}", gain_db(60.0));118
assert!(gain_db(40.0) < -20.0, "40 Hz {}", gain_db(40.0));119
}119
}120
}120
}@@ -0,0 +1,106 @@
1
use std::time::{Duration, Instant};
2
3
/// High-resolution frame pacer.
4
///
5
/// On Windows, `std::thread::sleep` is quantized to the 15.6 ms system timer tick,
6
/// causing audio underruns at 10 ms and uneven 30 fps screen capture. A high-resolution
7
/// waitable timer (`CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`, Windows 10 1803+) wakes
8
/// within ~0.5 ms without changing the global multimedia timer period.
9
pub struct HighResSleep {
10
#[cfg(windows)]
11
handle: windows::Win32::Foundation::HANDLE,
12
}
13
14
#[cfg(windows)]
15
unsafe impl Send for HighResSleep {}
16
17
impl HighResSleep {
18
pub fn new() -> Self {
19
#[cfg(windows)]
20
{
21
use windows::Win32::Foundation::HANDLE;
22
use windows::Win32::System::Threading::{
23
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, TIMER_ALL_ACCESS,
24
};
25
let handle = unsafe {
26
CreateWaitableTimerExW(
27
None,
28
None,
29
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,
30
TIMER_ALL_ACCESS.0,
31
)
32
.or_else(|_| CreateWaitableTimerExW(None, None, 0, TIMER_ALL_ACCESS.0))
33
.unwrap_or_else(|_| HANDLE::default())
34
};
35
HighResSleep { handle }
36
}
37
#[cfg(not(windows))]
38
{
39
HighResSleep {}
40
}
41
}
42
43
pub fn sleep(&self, duration: Duration) {
44
if duration.is_zero() {
45
return;
46
}
47
#[cfg(windows)]
48
{
49
use windows::Win32::System::Threading::{
50
INFINITE, SetWaitableTimer, WaitForSingleObject,
51
};
52
if !self.handle.is_invalid() {
53
// Negative relative due time in 100-nanosecond intervals.
54
let ticks_100ns = (duration.as_nanos() / 100).max(1) as i64;
55
let due_time = -ticks_100ns;
56
let ok = unsafe { SetWaitableTimer(self.handle, &due_time, 0, None, None, false) };
57
if ok.is_ok() {
58
unsafe {
59
let _ = WaitForSingleObject(self.handle, INFINITE);
60
}
61
return;
62
}
63
}
64
}
65
std::thread::sleep(duration);
66
}
67
68
pub fn sleep_until(&self, deadline: Instant) {
69
let now = Instant::now();
70
if deadline > now {
71
self.sleep(deadline - now);
72
}
73
}
74
}
75
76
impl Default for HighResSleep {
77
fn default() -> Self {
78
Self::new()
79
}
80
}
81
82
#[cfg(windows)]
83
impl Drop for HighResSleep {
84
fn drop(&mut self) {
85
use windows::Win32::Foundation::{CloseHandle, HANDLE};
86
if !self.handle.is_invalid() {
87
unsafe {
88
let _ = CloseHandle(self.handle);
89
}
90
self.handle = HANDLE::default();
91
}
92
}
93
}
94
95
#[cfg(test)]
96
mod tests {
97
use super::*;
98
99
#[test]
100
fn high_res_sleep_waits_for_a_short_interval() {
101
let sleeper = HighResSleep::new();
102
let started = Instant::now();
103
sleeper.sleep(Duration::from_millis(5));
104
assert!(started.elapsed() >= Duration::from_millis(3));
105
}
106
}
@@ -0,0 +1,106 @@1
use std::time::{Duration, Instant};2
3
/// High-resolution frame pacer.4
///5
/// On Windows, `std::thread::sleep` is quantized to the 15.6 ms system timer tick,6
/// causing audio underruns at 10 ms and uneven 30 fps screen capture. A high-resolution7
/// waitable timer (`CREATE_WAITABLE_TIMER_HIGH_RESOLUTION`, Windows 10 1803+) wakes8
/// within ~0.5 ms without changing the global multimedia timer period.9
pub struct HighResSleep {10
#[cfg(windows)]11
handle: windows::Win32::Foundation::HANDLE,12
}13
14
#[cfg(windows)]15
unsafe impl Send for HighResSleep {}16
17
impl HighResSleep {18
pub fn new() -> Self {19
#[cfg(windows)]20
{21
use windows::Win32::Foundation::HANDLE;22
use windows::Win32::System::Threading::{23
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION, CreateWaitableTimerExW, TIMER_ALL_ACCESS,24
};25
let handle = unsafe {26
CreateWaitableTimerExW(27
None,28
None,29
CREATE_WAITABLE_TIMER_HIGH_RESOLUTION,30
TIMER_ALL_ACCESS.0,31
)32
.or_else(|_| CreateWaitableTimerExW(None, None, 0, TIMER_ALL_ACCESS.0))33
.unwrap_or_else(|_| HANDLE::default())34
};35
HighResSleep { handle }36
}37
#[cfg(not(windows))]38
{39
HighResSleep {}40
}41
}42
43
pub fn sleep(&self, duration: Duration) {44
if duration.is_zero() {45
return;46
}47
#[cfg(windows)]48
{49
use windows::Win32::System::Threading::{50
INFINITE, SetWaitableTimer, WaitForSingleObject,51
};52
if !self.handle.is_invalid() {53
// Negative relative due time in 100-nanosecond intervals.54
let ticks_100ns = (duration.as_nanos() / 100).max(1) as i64;55
let due_time = -ticks_100ns;56
let ok = unsafe { SetWaitableTimer(self.handle, &due_time, 0, None, None, false) };57
if ok.is_ok() {58
unsafe {59
let _ = WaitForSingleObject(self.handle, INFINITE);60
}61
return;62
}63
}64
}65
std::thread::sleep(duration);66
}67
68
pub fn sleep_until(&self, deadline: Instant) {69
let now = Instant::now();70
if deadline > now {71
self.sleep(deadline - now);72
}73
}74
}75
76
impl Default for HighResSleep {77
fn default() -> Self {78
Self::new()79
}80
}81
82
#[cfg(windows)]83
impl Drop for HighResSleep {84
fn drop(&mut self) {85
use windows::Win32::Foundation::{CloseHandle, HANDLE};86
if !self.handle.is_invalid() {87
unsafe {88
let _ = CloseHandle(self.handle);89
}90
self.handle = HANDLE::default();91
}92
}93
}94
95
#[cfg(test)]96
mod tests {97
use super::*;98
99
#[test]100
fn high_res_sleep_waits_for_a_short_interval() {101
let sleeper = HighResSleep::new();102
let started = Instant::now();103
sleeper.sleep(Duration::from_millis(5));104
assert!(started.elapsed() >= Duration::from_millis(3));105
}106
}@@ -13,7 +13,9 @@ Options were: one software pipeline for every mode, or the same split the browse
13
13
14
14
## Decision
15
15
16
On Linux, Auto and Low send through the Pulse device track. On macOS, Auto and Low send through the CoreAudio device track. Music mode, Off, and computer sound use the software chain on both.
16
On Linux, Auto and Low send through the Pulse device track. On macOS, Auto and Low send through the CoreAudio device track. On Windows, Auto and Low send through the WASAPI device track. Music mode, Off, and computer sound use the software chain on every desktop OS.
17
18
Windows Voice Clarity (`AudioCategory_Communications`) applies only to the software WASAPI capture used by Music mode and Off. The platform device track does not request that category, so a laptop microphone array can keep more room echo in Auto and Low than the software path did.
17
19
18
20
Hangup tears the audio graph down without hanging the call task. On macOS, camera preview and send use the system camera.
19
21
@@ -13,7 +13,9 @@ Options were: one software pipeline for every mode, or the same split the browse13
13
14
## Decision14
## Decision15
15
16
On Linux, Auto and Low send through the Pulse device track. On macOS, Auto and Low send through the CoreAudio device track. Music mode, Off, and computer sound use the software chain on both.16
On Linux, Auto and Low send through the Pulse device track. On macOS, Auto and Low send through the CoreAudio device track. On Windows, Auto and Low send through the WASAPI device track. Music mode, Off, and computer sound use the software chain on every desktop OS.17
18
Windows Voice Clarity (`AudioCategory_Communications`) applies only to the software WASAPI capture used by Music mode and Off. The platform device track does not request that category, so a laptop microphone array can keep more room echo in Auto and Low than the software path did.17
19
18
Hangup tears the audio graph down without hanging the call task. On macOS, camera preview and send use the system camera.20
Hangup tears the audio graph down without hanging the call task. On macOS, camera preview and send use the system camera.19
21
@@ -0,0 +1,2 @@
1
schema: spec-driven
2
created: 2026-11-23
@@ -0,0 +1,2 @@1
schema: spec-driven2
created: 2026-11-23@@ -0,0 +1,45 @@
1
## Context
2
3
Auto and Low already send the platform ADM track. Music, Off, and computer sound use the software chain. Screen share converts native BGRA to I420 at capture size, and the encoder scales afterwards. `with_full_hd_level` only rewrites the level when both limits are at the 1080p thresholds.
4
5
## Goals / Non-Goals
6
7
**Goals:**
8
9
- Close the organizer-mute desync without posting a second mute.
10
- Stop Off and Music from restoring the noise-suppression track.
11
- Resolve a named microphone by the listed name. Windows compares that name exactly, ignoring ASCII case. Linux and macOS also match when either name contains the other, because cpal names differ from Pulse and CoreAudio.
12
- Treat Init/Start failure as a failed device switch on Windows. On Linux and macOS the switch counts once the index is selected.
13
- Raise an H.264 level only when the peer's own limits need it.
14
- Shrink screen frames with libyuv to at most 8160 macroblocks before `argb_to_i420`.
15
- Drive the existing device-change debounce from a once-per-second list diff on Linux and macOS.
16
17
**Non-Goals:**
18
19
- VAAPI decode, Media Foundation decode, and GPU scaling.
20
- A CoreAudio computer-sound tap.
21
- Excluding local playout from the Pulse monitor.
22
- Camera effects or the 720p camera ceiling during share.
23
24
## Decisions
25
26
1. Server mute stays on `Member.server_muted`. The call loop silences the local tracks and sends the muted update. It does not call `updateEndpointState`. An unmute while `server_muted` is still set marks the mute cleared until the roster drops `serverMuted`, so the next roster tick does not mute again.
27
2. `device_track` returns `track_with_ns` only for Low without music mode.
28
3. CPAL lookup uses the device-list name when the stored choice is an endpoint id. Windows compares that name with case-insensitive equality. Linux and macOS also accept a case-insensitive substring in either direction. An empty target never matches. While sharing computer sound, a failed named microphone falls back to the default microphone and shows that notice. Silence is used only when the default also fails.
29
4. On Windows, `select_input_index` and `select_output_index` return `selected && started`, including the Bluetooth retry. On Linux and macOS they return whether the index was selected, so one failed start does not keep retrying the same switch.
30
5. H.264 levels come from Table A-1. The rewrite replaces the last two hex digits when the needed level is higher. 1080p limits still land on level 4.0.
31
6. Screen scale uses libyuv `ARGBScale` with box filtering. The limit is the same 8160 macroblocks the screen receive request uses. Short buffers return no frame.
32
7. Linux and macOS poll `list_devices` once a second while the ADM is in use. `list_devices` acquires and releases a reference, so an already held ADM stays up. Changed endpoint ids go through `Debounce` and `follow_device_change`.
33
34
## Risks / Trade-offs
35
36
- A roster that keeps `serverMuted` after a successful unmute stays cleared until that flag drops. If the server rejects the unmute, the mic stays open locally until the next distinct server mute.
37
- Polling the device list once a second can miss a headset that drops and returns inside that second. The debounce still collapses a burst into one follow-up. That poll is the device-arrival path on Linux and macOS.
38
39
## Migration Plan
40
41
No stored-data migration. Rollback is reverting the change.
42
43
## Open Questions
44
45
None. Live echo, headset, and Retina share checks stay manual after the unit tests.
@@ -0,0 +1,45 @@1
## Context2
3
Auto and Low already send the platform ADM track. Music, Off, and computer sound use the software chain. Screen share converts native BGRA to I420 at capture size, and the encoder scales afterwards. `with_full_hd_level` only rewrites the level when both limits are at the 1080p thresholds.4
5
## Goals / Non-Goals6
7
**Goals:**8
9
- Close the organizer-mute desync without posting a second mute.10
- Stop Off and Music from restoring the noise-suppression track.11
- Resolve a named microphone by the listed name. Windows compares that name exactly, ignoring ASCII case. Linux and macOS also match when either name contains the other, because cpal names differ from Pulse and CoreAudio.12
- Treat Init/Start failure as a failed device switch on Windows. On Linux and macOS the switch counts once the index is selected.13
- Raise an H.264 level only when the peer's own limits need it.14
- Shrink screen frames with libyuv to at most 8160 macroblocks before `argb_to_i420`.15
- Drive the existing device-change debounce from a once-per-second list diff on Linux and macOS.16
17
**Non-Goals:**18
19
- VAAPI decode, Media Foundation decode, and GPU scaling.20
- A CoreAudio computer-sound tap.21
- Excluding local playout from the Pulse monitor.22
- Camera effects or the 720p camera ceiling during share.23
24
## Decisions25
26
1. Server mute stays on `Member.server_muted`. The call loop silences the local tracks and sends the muted update. It does not call `updateEndpointState`. An unmute while `server_muted` is still set marks the mute cleared until the roster drops `serverMuted`, so the next roster tick does not mute again.27
2. `device_track` returns `track_with_ns` only for Low without music mode.28
3. CPAL lookup uses the device-list name when the stored choice is an endpoint id. Windows compares that name with case-insensitive equality. Linux and macOS also accept a case-insensitive substring in either direction. An empty target never matches. While sharing computer sound, a failed named microphone falls back to the default microphone and shows that notice. Silence is used only when the default also fails.29
4. On Windows, `select_input_index` and `select_output_index` return `selected && started`, including the Bluetooth retry. On Linux and macOS they return whether the index was selected, so one failed start does not keep retrying the same switch.30
5. H.264 levels come from Table A-1. The rewrite replaces the last two hex digits when the needed level is higher. 1080p limits still land on level 4.0.31
6. Screen scale uses libyuv `ARGBScale` with box filtering. The limit is the same 8160 macroblocks the screen receive request uses. Short buffers return no frame.32
7. Linux and macOS poll `list_devices` once a second while the ADM is in use. `list_devices` acquires and releases a reference, so an already held ADM stays up. Changed endpoint ids go through `Debounce` and `follow_device_change`.33
34
## Risks / Trade-offs35
36
- A roster that keeps `serverMuted` after a successful unmute stays cleared until that flag drops. If the server rejects the unmute, the mic stays open locally until the next distinct server mute.37
- Polling the device list once a second can miss a headset that drops and returns inside that second. The debounce still collapses a burst into one follow-up. That poll is the device-arrival path on Linux and macOS.38
39
## Migration Plan40
41
No stored-data migration. Rollback is reverting the change.42
43
## Open Questions44
45
None. Live echo, headset, and Retina share checks stay manual after the unit tests.@@ -0,0 +1,28 @@
1
## Why
2
3
Live calls still lose the local microphone after an organizer mute, send the wrong noise-suppression track when a named microphone cannot be opened, stall 720p when Teams answers H.264 level 3.0, and spend the screen-share budget converting a full Retina or 5K frame. Linux and macOS also ignore device arrival until the user refreshes the device list.
4
5
## What Changes
6
7
- A server mute of the local participant closes the microphone in the call and in the button. The next toggle clears that mute. A later organizer mute applies again.
8
- Low is the only mode that publishes the WebRTC noise-suppression track. A named software-path microphone matches the listed name exactly on Windows. On Linux and macOS either name may contain the other, because cpal names differ from Pulse and CoreAudio. While sharing computer sound, a failed named microphone falls back to the default microphone. Selecting a device counts as applied only when recording or playout starts on Windows. On Linux and macOS it counts when the index is selected.
9
- An H.264 answer level rises to the lowest table level that covers the peer's `max-fs` and `max-mbps`. The level is never lowered. An answer without those limits is unchanged.
10
- Screen share scales the captured frame with libyuv down to the 1080p macroblock budget before the I420 conversion. A short buffer produces no frame.
11
- On Linux and macOS the call compares the audio device list once a second and feeds the existing device-change path when an endpoint appears or disappears.
12
13
## Capabilities
14
15
### New Capabilities
16
17
- `call-server-mute`: Organizer mute of the local participant is reflected on the microphone control and can be cleared by the local user.
18
19
### Modified Capabilities
20
21
- `linux-call-audio`: Named software-path capture fails clearly, and Low is the only device-track mode that enables classical noise suppression.
22
- `macos-call-audio`: Same named-microphone and noise-suppression rules on the CoreAudio path.
23
- `camera-video-quality`: Answered H.264 level follows the peer's explicit frame-size limits, including level 3.0 answers that still allow 720p.
24
- `screen-share`: Shared frames are reduced to the send budget before colorspace conversion.
25
26
## Impact
27
28
Calling, the call model, and the screen-capture path. No new encoder, decoder, or GPU scaler. Device hotplug on Linux and macOS reuses the existing follow-up that Windows already runs from endpoint notifications.
@@ -0,0 +1,28 @@1
## Why2
3
Live calls still lose the local microphone after an organizer mute, send the wrong noise-suppression track when a named microphone cannot be opened, stall 720p when Teams answers H.264 level 3.0, and spend the screen-share budget converting a full Retina or 5K frame. Linux and macOS also ignore device arrival until the user refreshes the device list.4
5
## What Changes6
7
- A server mute of the local participant closes the microphone in the call and in the button. The next toggle clears that mute. A later organizer mute applies again.8
- Low is the only mode that publishes the WebRTC noise-suppression track. A named software-path microphone matches the listed name exactly on Windows. On Linux and macOS either name may contain the other, because cpal names differ from Pulse and CoreAudio. While sharing computer sound, a failed named microphone falls back to the default microphone. Selecting a device counts as applied only when recording or playout starts on Windows. On Linux and macOS it counts when the index is selected.9
- An H.264 answer level rises to the lowest table level that covers the peer's `max-fs` and `max-mbps`. The level is never lowered. An answer without those limits is unchanged.10
- Screen share scales the captured frame with libyuv down to the 1080p macroblock budget before the I420 conversion. A short buffer produces no frame.11
- On Linux and macOS the call compares the audio device list once a second and feeds the existing device-change path when an endpoint appears or disappears.12
13
## Capabilities14
15
### New Capabilities16
17
- `call-server-mute`: Organizer mute of the local participant is reflected on the microphone control and can be cleared by the local user.18
19
### Modified Capabilities20
21
- `linux-call-audio`: Named software-path capture fails clearly, and Low is the only device-track mode that enables classical noise suppression.22
- `macos-call-audio`: Same named-microphone and noise-suppression rules on the CoreAudio path.23
- `camera-video-quality`: Answered H.264 level follows the peer's explicit frame-size limits, including level 3.0 answers that still allow 720p.24
- `screen-share`: Shared frames are reduced to the send budget before colorspace conversion.25
26
## Impact27
28
Calling, the call model, and the screen-capture path. No new encoder, decoder, or GPU scaler. Device hotplug on Linux and macOS reuses the existing follow-up that Windows already runs from endpoint notifications.@@ -0,0 +1,27 @@
1
## ADDED Requirements
2
3
### Requirement: Organizer mute closes the local microphone
4
5
When the roster reports the local participant as server-muted, the client SHALL show the microphone as muted and SHALL stop sending microphone audio. It MUST NOT post another mute for that transition.
6
7
#### Scenario: A colleague mutes the local user
8
9
- **WHEN** the local microphone is open and the roster marks the local participant server-muted
10
- **THEN** the microphone control shows muted
11
- **AND** the outgoing microphone track is disabled
12
- **AND** the client does not send a new mute state for that roster update
13
14
### Requirement: The local user can clear an organizer mute
15
16
The next microphone toggle after an organizer mute SHALL unmute. A roster update that still reports the same server mute MUST NOT mute the local user again. A later server mute, after the flag has cleared, SHALL mute the local user again.
17
18
#### Scenario: Toggle after an organizer mute
19
20
- **WHEN** the local user was muted by the server and presses the microphone control
21
- **THEN** the client requests an unmuted endpoint state
22
- **AND** a following roster update that still says server-muted leaves the microphone open
23
24
#### Scenario: A new organizer mute applies again
25
26
- **WHEN** the server mute flag drops and a later roster update sets it again while the local microphone is open
27
- **THEN** the microphone control shows muted again
@@ -0,0 +1,27 @@1
## ADDED Requirements2
3
### Requirement: Organizer mute closes the local microphone4
5
When the roster reports the local participant as server-muted, the client SHALL show the microphone as muted and SHALL stop sending microphone audio. It MUST NOT post another mute for that transition.6
7
#### Scenario: A colleague mutes the local user8
9
- **WHEN** the local microphone is open and the roster marks the local participant server-muted10
- **THEN** the microphone control shows muted11
- **AND** the outgoing microphone track is disabled12
- **AND** the client does not send a new mute state for that roster update13
14
### Requirement: The local user can clear an organizer mute15
16
The next microphone toggle after an organizer mute SHALL unmute. A roster update that still reports the same server mute MUST NOT mute the local user again. A later server mute, after the flag has cleared, SHALL mute the local user again.17
18
#### Scenario: Toggle after an organizer mute19
20
- **WHEN** the local user was muted by the server and presses the microphone control21
- **THEN** the client requests an unmuted endpoint state22
- **AND** a following roster update that still says server-muted leaves the microphone open23
24
#### Scenario: A new organizer mute applies again25
26
- **WHEN** the server mute flag drops and a later roster update sets it again while the local microphone is open27
- **THEN** the microphone control shows muted again@@ -0,0 +1,16 @@
1
## ADDED Requirements
2
3
### Requirement: Answered H.264 level covers the peer frame limits
4
5
When an H.264 answer carries both `max-fs` and `max-mbps`, the client SHALL raise `profile-level-id` to the lowest H.264 Table A-1 level that covers both limits. The client MUST NOT lower a level. An answer without both limits SHALL keep its level. A level-3.0 answer with 720p limits SHALL become level 3.1. A 1080p answer that already required level 4.0 SHALL stay at level 4.0.
6
7
#### Scenario: Level 3.0 with 720p limits
8
9
- **WHEN** the answer contains `profile-level-id` ending in level 3.0 and `max-fs=3600` with `max-mbps=108000`
10
- **THEN** the sent level is 3.1
11
- **AND** the `max-fs` and `max-mbps` values are unchanged
12
13
#### Scenario: Missing limits stay put
14
15
- **WHEN** the answer has a profile level and no `max-fs` or no `max-mbps`
16
- **THEN** the profile level is unchanged
@@ -0,0 +1,16 @@1
## ADDED Requirements2
3
### Requirement: Answered H.264 level covers the peer frame limits4
5
When an H.264 answer carries both `max-fs` and `max-mbps`, the client SHALL raise `profile-level-id` to the lowest H.264 Table A-1 level that covers both limits. The client MUST NOT lower a level. An answer without both limits SHALL keep its level. A level-3.0 answer with 720p limits SHALL become level 3.1. A 1080p answer that already required level 4.0 SHALL stay at level 4.0.6
7
#### Scenario: Level 3.0 with 720p limits8
9
- **WHEN** the answer contains `profile-level-id` ending in level 3.0 and `max-fs=3600` with `max-mbps=108000`10
- **THEN** the sent level is 3.111
- **AND** the `max-fs` and `max-mbps` values are unchanged12
13
#### Scenario: Missing limits stay put14
15
- **WHEN** the answer has a profile level and no `max-fs` or no `max-mbps`16
- **THEN** the profile level is unchanged@@ -0,0 +1,42 @@
1
## ADDED Requirements
2
3
### Requirement: Only Low uses the classical noise-suppression track
4
5
On the device track, Low SHALL publish the track with classical noise suppression. Auto, Off, and music mode SHALL publish the track without that stage. A failed software-path start MUST NOT restore the classical noise-suppression track for Off or music mode.
6
7
#### Scenario: Off does not restore noise suppression
8
9
- **WHEN** noise suppression is Off or music mode is on and the software path cannot start
10
- **THEN** the restored device track is the track without classical noise suppression
11
12
### Requirement: A named microphone matches the capture name
13
14
A named input on the software path SHALL match a capture device when the names are equal ignoring ASCII case, or when either name contains the other. cpal names differ from the Pulse description. An empty target SHALL NOT match. An unmatched name SHALL fail the capture with an error or the existing notice and MUST NOT silently capture a different microphone.
15
16
#### Scenario: A Pulse description matches a shorter capture name
17
18
- **WHEN** the listed name is "Jabra Speak 750 Mono" and cpal reports "Jabra Speak 750"
19
- **THEN** that capture device is selected
20
21
#### Scenario: Endpoint id is not a capture name
22
23
- **WHEN** the software path is asked for a named input whose key is an endpoint id and whose listed name is absent from the capture devices
24
- **THEN** capture fails with an error or notice
25
26
### Requirement: Computer sound falls back to the default microphone
27
28
While sharing computer sound, a failed named microphone SHALL fall back to the default microphone and show that notice. Silence is used only when the default microphone also fails.
29
30
#### Scenario: The default microphone opens
31
32
- **WHEN** the named microphone fails and the default microphone starts
33
- **THEN** the call uses the default microphone and shows the fallback notice
34
35
### Requirement: A device switch counts when the index is selected
36
37
Selecting an input or output SHALL be reported as applied when the device index is selected, even if recording or playout does not start on that attempt. A single failed start MUST NOT leave the previous device marked as current.
38
39
#### Scenario: Start fails once
40
41
- **WHEN** the device index is accepted and recording or playout does not start
42
- **THEN** the selection is still reported as applied
@@ -0,0 +1,42 @@1
## ADDED Requirements2
3
### Requirement: Only Low uses the classical noise-suppression track4
5
On the device track, Low SHALL publish the track with classical noise suppression. Auto, Off, and music mode SHALL publish the track without that stage. A failed software-path start MUST NOT restore the classical noise-suppression track for Off or music mode.6
7
#### Scenario: Off does not restore noise suppression8
9
- **WHEN** noise suppression is Off or music mode is on and the software path cannot start10
- **THEN** the restored device track is the track without classical noise suppression11
12
### Requirement: A named microphone matches the capture name13
14
A named input on the software path SHALL match a capture device when the names are equal ignoring ASCII case, or when either name contains the other. cpal names differ from the Pulse description. An empty target SHALL NOT match. An unmatched name SHALL fail the capture with an error or the existing notice and MUST NOT silently capture a different microphone.15
16
#### Scenario: A Pulse description matches a shorter capture name17
18
- **WHEN** the listed name is "Jabra Speak 750 Mono" and cpal reports "Jabra Speak 750"19
- **THEN** that capture device is selected20
21
#### Scenario: Endpoint id is not a capture name22
23
- **WHEN** the software path is asked for a named input whose key is an endpoint id and whose listed name is absent from the capture devices24
- **THEN** capture fails with an error or notice25
26
### Requirement: Computer sound falls back to the default microphone27
28
While sharing computer sound, a failed named microphone SHALL fall back to the default microphone and show that notice. Silence is used only when the default microphone also fails.29
30
#### Scenario: The default microphone opens31
32
- **WHEN** the named microphone fails and the default microphone starts33
- **THEN** the call uses the default microphone and shows the fallback notice34
35
### Requirement: A device switch counts when the index is selected36
37
Selecting an input or output SHALL be reported as applied when the device index is selected, even if recording or playout does not start on that attempt. A single failed start MUST NOT leave the previous device marked as current.38
39
#### Scenario: Start fails once40
41
- **WHEN** the device index is accepted and recording or playout does not start42
- **THEN** the selection is still reported as applied@@ -0,0 +1,37 @@
1
## ADDED Requirements
2
3
### Requirement: Only Low uses the classical noise-suppression track
4
5
On the device track, Low SHALL publish the track with classical noise suppression. Auto, Off, and music mode SHALL publish the track without that stage. A failed software-path start MUST NOT restore the classical noise-suppression track for Off or music mode.
6
7
#### Scenario: Music mode does not restore noise suppression
8
9
- **WHEN** music mode is on and the software path cannot start
10
- **THEN** the restored device track is the track without classical noise suppression
11
12
### Requirement: A named microphone matches the capture name
13
14
A named input on the software path SHALL match a capture device when the names are equal ignoring ASCII case, or when either name contains the other. cpal names can differ from the CoreAudio description. An empty target SHALL NOT match. An unmatched name SHALL fail the capture with an error or the existing notice and MUST NOT silently capture a different microphone.
15
16
#### Scenario: A shorter description matches a longer capture name
17
18
- **WHEN** the requested name is contained in a longer capture-device name
19
- **THEN** that capture device is selected
20
21
### Requirement: Computer sound falls back to the default microphone
22
23
While sharing computer sound, a failed named microphone SHALL fall back to the default microphone and show that notice. Silence is used only when the default microphone also fails.
24
25
#### Scenario: The default microphone opens
26
27
- **WHEN** the named microphone fails and the default microphone starts
28
- **THEN** the call uses the default microphone and shows the fallback notice
29
30
### Requirement: A device switch counts when the index is selected
31
32
Selecting an input or output SHALL be reported as applied when the device index is selected, even if recording or playout does not start on that attempt. A single failed start MUST NOT leave the previous device marked as current.
33
34
#### Scenario: Start fails once
35
36
- **WHEN** the device index is accepted and recording or playout does not start
37
- **THEN** the selection is still reported as applied
@@ -0,0 +1,37 @@1
## ADDED Requirements2
3
### Requirement: Only Low uses the classical noise-suppression track4
5
On the device track, Low SHALL publish the track with classical noise suppression. Auto, Off, and music mode SHALL publish the track without that stage. A failed software-path start MUST NOT restore the classical noise-suppression track for Off or music mode.6
7
#### Scenario: Music mode does not restore noise suppression8
9
- **WHEN** music mode is on and the software path cannot start10
- **THEN** the restored device track is the track without classical noise suppression11
12
### Requirement: A named microphone matches the capture name13
14
A named input on the software path SHALL match a capture device when the names are equal ignoring ASCII case, or when either name contains the other. cpal names can differ from the CoreAudio description. An empty target SHALL NOT match. An unmatched name SHALL fail the capture with an error or the existing notice and MUST NOT silently capture a different microphone.15
16
#### Scenario: A shorter description matches a longer capture name17
18
- **WHEN** the requested name is contained in a longer capture-device name19
- **THEN** that capture device is selected20
21
### Requirement: Computer sound falls back to the default microphone22
23
While sharing computer sound, a failed named microphone SHALL fall back to the default microphone and show that notice. Silence is used only when the default microphone also fails.24
25
#### Scenario: The default microphone opens26
27
- **WHEN** the named microphone fails and the default microphone starts28
- **THEN** the call uses the default microphone and shows the fallback notice29
30
### Requirement: A device switch counts when the index is selected31
32
Selecting an input or output SHALL be reported as applied when the device index is selected, even if recording or playout does not start on that attempt. A single failed start MUST NOT leave the previous device marked as current.33
34
#### Scenario: Start fails once35
36
- **WHEN** the device index is accepted and recording or playout does not start37
- **THEN** the selection is still reported as applied@@ -0,0 +1,33 @@
1
## 1. Server mute
2
3
- [x] 1.1 Record `server_muted` on the roster member and silence the local mic without posting
4
- [x] 1.2 Let the next unmute clear that mute until `serverMuted` drops
5
- [x] 1.3 Unit tests for the sync decision and the roster flag
6
7
## 2. Microphone selection
8
9
- [x] 2.1 Return the noise-suppression track only for Low
10
- [x] 2.2 Match named software-path inputs by listed name. Windows is exact and case-insensitive. Linux and macOS also match when either name contains the other
11
- [x] 2.3 Fall back to the default microphone while sharing computer sound, and stay silent only when that also fails
12
- [x] 2.4 Report a device switch as applied only when start succeeds on Windows. On Linux and macOS report it when the index is selected
13
- [x] 2.5 Unit tests for track choice, name match, and the start result
14
15
## 3. H.264 level
16
17
- [x] 3.1 Raise the answer level from `max-fs` and `max-mbps` without lowering it
18
- [x] 3.2 Keep the 1080p test and add the level-3.0 720p case
19
20
## 4. Screen share scale
21
22
- [x] 4.1 Scale live share frames with libyuv to 8160 macroblocks before I420 and reject short buffers
23
- [x] 4.2 Unit test the 2560 by 1440 budget and the short buffer
24
25
## 5. Device list poll
26
27
- [x] 5.1 Diff endpoint ids and feed the existing debounce on Linux and macOS once a second
28
- [x] 5.2 Unit test that a remove-and-return inside the quiet period is one event
29
30
## 6. Verify
31
32
- [x] 6.1 `openspec validate call-media-hardening`
33
- [x] 6.2 `cargo test -p calling --lib` and `cargo test -p app-call-model`
@@ -0,0 +1,33 @@1
## 1. Server mute2
3
- [x] 1.1 Record `server_muted` on the roster member and silence the local mic without posting4
- [x] 1.2 Let the next unmute clear that mute until `serverMuted` drops5
- [x] 1.3 Unit tests for the sync decision and the roster flag6
7
## 2. Microphone selection8
9
- [x] 2.1 Return the noise-suppression track only for Low10
- [x] 2.2 Match named software-path inputs by listed name. Windows is exact and case-insensitive. Linux and macOS also match when either name contains the other11
- [x] 2.3 Fall back to the default microphone while sharing computer sound, and stay silent only when that also fails12
- [x] 2.4 Report a device switch as applied only when start succeeds on Windows. On Linux and macOS report it when the index is selected13
- [x] 2.5 Unit tests for track choice, name match, and the start result14
15
## 3. H.264 level16
17
- [x] 3.1 Raise the answer level from `max-fs` and `max-mbps` without lowering it18
- [x] 3.2 Keep the 1080p test and add the level-3.0 720p case19
20
## 4. Screen share scale21
22
- [x] 4.1 Scale live share frames with libyuv to 8160 macroblocks before I420 and reject short buffers23
- [x] 4.2 Unit test the 2560 by 1440 budget and the short buffer24
25
## 5. Device list poll26
27
- [x] 5.1 Diff endpoint ids and feed the existing debounce on Linux and macOS once a second28
- [x] 5.2 Unit test that a remove-and-return inside the quiet period is one event29
30
## 6. Verify31
32
- [x] 6.1 `openspec validate call-media-hardening`33
- [x] 6.2 `cargo test -p calling --lib` and `cargo test -p app-call-model`@@ -133,6 +133,22 @@ impl PeerConnectionFactory {
133
133
}
134
134
}
135
135
136
/// Create an audio track that uses the Platform ADM for capture with explicit
137
/// WebRTC noise suppression control (e.g. off when an external ML post-processor replaces it).
138
pub fn create_device_audio_track_with_options(
139
&self,
140
label: &str,
141
noise_suppression: bool,
142
) -> RtcAudioTrack {
143
RtcAudioTrack {
144
handle: imp_at::RtcAudioTrack {
145
sys_handle: self
146
.sys_handle
147
.create_device_audio_track_with_options(label.to_string(), noise_suppression),
148
},
149
}
150
}
151
136
152
pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {
137
153
self.sys_handle.rtp_sender_capabilities(media_type.into()).into()
138
154
}
@@ -133,6 +133,22 @@ impl PeerConnectionFactory {133
}133
}134
}134
}135
135
136
/// Create an audio track that uses the Platform ADM for capture with explicit137
/// WebRTC noise suppression control (e.g. off when an external ML post-processor replaces it).138
pub fn create_device_audio_track_with_options(139
&self,140
label: &str,141
noise_suppression: bool,142
) -> RtcAudioTrack {143
RtcAudioTrack {144
handle: imp_at::RtcAudioTrack {145
sys_handle: self146
.sys_handle147
.create_device_audio_track_with_options(label.to_string(), noise_suppression),148
},149
}150
}151
136
pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {152
pub fn get_rtp_sender_capabilities(&self, media_type: MediaType) -> RtpCapabilities {137
self.sys_handle.rtp_sender_capabilities(media_type.into()).into()153
self.sys_handle.rtp_sender_capabilities(media_type.into()).into()138
}154
}@@ -866,3 +866,76 @@ pub fn argb_to_nv12(
866
866
.unwrap()
867
867
}
868
868
}
869
870
pub fn yuy2_to_i420(
871
src_yuy2: &[u8],
872
src_stride_yuy2: u32,
873
dst_y: &mut [u8],
874
dst_stride_y: u32,
875
dst_u: &mut [u8],
876
dst_stride_u: u32,
877
dst_v: &mut [u8],
878
dst_stride_v: u32,
879
width: i32,
880
height: i32,
881
) {
882
let row_bytes = width.unsigned_abs().saturating_mul(2);
883
assert!(
884
src_stride_yuy2 >= row_bytes,
885
"yuy2 stride is shorter than the row"
886
);
887
argb_assert_safety(src_yuy2, src_stride_yuy2, width, height);
888
i420_assert_safety(
889
dst_y,
890
dst_stride_y,
891
dst_u,
892
dst_stride_u,
893
dst_v,
894
dst_stride_v,
895
width,
896
height,
897
);
898
899
unsafe {
900
yuv_sys::ffi::yuy2_to_i420(
901
src_yuy2.as_ptr(),
902
src_stride_yuy2 as i32,
903
dst_y.as_mut_ptr(),
904
dst_stride_y as i32,
905
dst_u.as_mut_ptr(),
906
dst_stride_u as i32,
907
dst_v.as_mut_ptr(),
908
dst_stride_v as i32,
909
width,
910
height,
911
)
912
.unwrap()
913
}
914
}
915
916
pub fn argb_scale(
917
src: &[u8],
918
src_stride: u32,
919
src_width: i32,
920
src_height: i32,
921
dst: &mut [u8],
922
dst_stride: u32,
923
dst_width: i32,
924
dst_height: i32,
925
) {
926
argb_assert_safety(src, src_stride, src_width, src_height);
927
argb_assert_safety(dst, dst_stride, dst_width, dst_height);
928
unsafe {
929
yuv_sys::ffi::argb_scale(
930
src.as_ptr(),
931
src_stride as i32,
932
src_width,
933
src_height,
934
dst.as_mut_ptr(),
935
dst_stride as i32,
936
dst_width,
937
dst_height,
938
)
939
.unwrap()
940
}
941
}
@@ -866,3 +866,76 @@ pub fn argb_to_nv12(866
.unwrap()866
.unwrap()867
}867
}868
}868
}869
870
pub fn yuy2_to_i420(871
src_yuy2: &[u8],872
src_stride_yuy2: u32,873
dst_y: &mut [u8],874
dst_stride_y: u32,875
dst_u: &mut [u8],876
dst_stride_u: u32,877
dst_v: &mut [u8],878
dst_stride_v: u32,879
width: i32,880
height: i32,881
) {882
let row_bytes = width.unsigned_abs().saturating_mul(2);883
assert!(884
src_stride_yuy2 >= row_bytes,885
"yuy2 stride is shorter than the row"886
);887
argb_assert_safety(src_yuy2, src_stride_yuy2, width, height);888
i420_assert_safety(889
dst_y,890
dst_stride_y,891
dst_u,892
dst_stride_u,893
dst_v,894
dst_stride_v,895
width,896
height,897
);898
899
unsafe {900
yuv_sys::ffi::yuy2_to_i420(901
src_yuy2.as_ptr(),902
src_stride_yuy2 as i32,903
dst_y.as_mut_ptr(),904
dst_stride_y as i32,905
dst_u.as_mut_ptr(),906
dst_stride_u as i32,907
dst_v.as_mut_ptr(),908
dst_stride_v as i32,909
width,910
height,911
)912
.unwrap()913
}914
}915
916
pub fn argb_scale(917
src: &[u8],918
src_stride: u32,919
src_width: i32,920
src_height: i32,921
dst: &mut [u8],922
dst_stride: u32,923
dst_width: i32,924
dst_height: i32,925
) {926
argb_assert_safety(src, src_stride, src_width, src_height);927
argb_assert_safety(dst, dst_stride, dst_width, dst_height);928
unsafe {929
yuv_sys::ffi::argb_scale(930
src.as_ptr(),931
src_stride as i32,932
src_width,933
src_height,934
dst.as_mut_ptr(),935
dst_stride as i32,936
dst_width,937
dst_height,938
)939
.unwrap()940
}941
}@@ -146,6 +146,13 @@ pub mod native {
146
146
/// The track will capture audio from the selected recording device.
147
147
fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack;
148
148
149
/// Create a Platform ADM audio track with explicit WebRTC noise suppression toggle.
150
fn create_device_audio_track_with_options(
151
&self,
152
label: &str,
153
noise_suppression: bool,
154
) -> RtcAudioTrack;
155
149
156
// Device enumeration
150
157
fn playout_devices(&self) -> i16;
151
158
fn recording_devices(&self) -> i16;
@@ -218,6 +225,14 @@ pub mod native {
218
225
self.handle.create_device_audio_track(label)
219
226
}
220
227
228
fn create_device_audio_track_with_options(
229
&self,
230
label: &str,
231
noise_suppression: bool,
232
) -> RtcAudioTrack {
233
self.handle.create_device_audio_track_with_options(label, noise_suppression)
234
}
235
221
236
fn playout_devices(&self) -> i16 {
222
237
self.handle.playout_devices()
223
238
}
@@ -146,6 +146,13 @@ pub mod native {146
/// The track will capture audio from the selected recording device.146
/// The track will capture audio from the selected recording device.147
fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack;147
fn create_device_audio_track(&self, label: &str) -> RtcAudioTrack;148
148
149
/// Create a Platform ADM audio track with explicit WebRTC noise suppression toggle.150
fn create_device_audio_track_with_options(151
&self,152
label: &str,153
noise_suppression: bool,154
) -> RtcAudioTrack;155
149
// Device enumeration156
// Device enumeration150
fn playout_devices(&self) -> i16;157
fn playout_devices(&self) -> i16;151
fn recording_devices(&self) -> i16;158
fn recording_devices(&self) -> i16;@@ -218,6 +225,14 @@ pub mod native {218
self.handle.create_device_audio_track(label)225
self.handle.create_device_audio_track(label)219
}226
}220
227
228
fn create_device_audio_track_with_options(229
&self,230
label: &str,231
noise_suppression: bool,232
) -> RtcAudioTrack {233
self.handle.create_device_audio_track_with_options(label, noise_suppression)234
}235
221
fn playout_devices(&self) -> i16 {236
fn playout_devices(&self) -> i16 {222
self.handle.playout_devices()237
self.handle.playout_devices()223
}238
}@@ -144,6 +144,7 @@ fn main() {
144
144
println!("cargo:rustc-link-lib=dylib=crypt32");
145
145
println!("cargo:rustc-link-lib=dylib=iphlpapi");
146
146
println!("cargo:rustc-link-lib=dylib=ole32");
147
println!("cargo:rustc-link-lib=dylib=oleaut32");
147
148
println!("cargo:rustc-link-lib=dylib=secur32");
148
149
println!("cargo:rustc-link-lib=dylib=winmm");
149
150
println!("cargo:rustc-link-lib=dylib=ws2_32");
@@ -153,23 +154,15 @@ fn main() {
153
154
println!("cargo:rustc-link-lib=dylib=dxgi");
154
155
println!("cargo:rustc-link-lib=dylib=dwmapi");
155
156
println!("cargo:rustc-link-lib=dylib=shcore");
156
157
//let path = env::current_dir().unwrap();
158
//println!("cargo:rustc-link-search=native={}/vaapi-windows/x64/lib", path.display());
159
//println!("cargo:rustc-link-lib=dylib=va");
160
//println!("cargo:rustc-link-lib=dylib=va_win32");
157
println!("cargo:rustc-link-lib=dylib=mfplat");
158
println!("cargo:rustc-link-lib=dylib=mfuuid");
159
println!("cargo:rustc-link-lib=dylib=mf");
161
160
162
161
builder
163
//.include("./vaapi-windows/DirectX-Headers-1.0/include")
164
//.include(path::PathBuf::from("./vaapi-windows/x64/include"))
165
//.file("vaapi-windows/DirectX-Headers-1.0/src/dxguids.cpp")
166
//.file("src/vaapi/vaapi_display_win32.cpp")
167
//.file("src/vaapi/vaapi_h264_encoder_wrapper.cpp")
168
//.file("src/vaapi/vaapi_encoder_factory.cpp")
169
//.file("src/vaapi/h264_encoder_impl.cpp")
162
.file("src/mf/mf_encoder_factory.cpp")
163
.file("src/mf/mf_h264_encoder_impl.cpp")
164
.define("USE_MF_VIDEO_CODEC", "1")
170
165
.flag("/std:c++20")
171
//.flag("/wd4819")
172
//.flag("/wd4068")
173
166
.flag("/EHsc");
174
167
}
175
168
"linux" => {
@@ -144,6 +144,7 @@ fn main() {144
println!("cargo:rustc-link-lib=dylib=crypt32");144
println!("cargo:rustc-link-lib=dylib=crypt32");145
println!("cargo:rustc-link-lib=dylib=iphlpapi");145
println!("cargo:rustc-link-lib=dylib=iphlpapi");146
println!("cargo:rustc-link-lib=dylib=ole32");146
println!("cargo:rustc-link-lib=dylib=ole32");147
println!("cargo:rustc-link-lib=dylib=oleaut32");147
println!("cargo:rustc-link-lib=dylib=secur32");148
println!("cargo:rustc-link-lib=dylib=secur32");148
println!("cargo:rustc-link-lib=dylib=winmm");149
println!("cargo:rustc-link-lib=dylib=winmm");149
println!("cargo:rustc-link-lib=dylib=ws2_32");150
println!("cargo:rustc-link-lib=dylib=ws2_32");@@ -153,23 +154,15 @@ fn main() {153
println!("cargo:rustc-link-lib=dylib=dxgi");154
println!("cargo:rustc-link-lib=dylib=dxgi");154
println!("cargo:rustc-link-lib=dylib=dwmapi");155
println!("cargo:rustc-link-lib=dylib=dwmapi");155
println!("cargo:rustc-link-lib=dylib=shcore");156
println!("cargo:rustc-link-lib=dylib=shcore");156
157
println!("cargo:rustc-link-lib=dylib=mfplat");157
//let path = env::current_dir().unwrap();158
println!("cargo:rustc-link-lib=dylib=mfuuid");158
//println!("cargo:rustc-link-search=native={}/vaapi-windows/x64/lib", path.display());159
println!("cargo:rustc-link-lib=dylib=mf");159
//println!("cargo:rustc-link-lib=dylib=va");160
//println!("cargo:rustc-link-lib=dylib=va_win32");161
160
162
builder161
builder163
//.include("./vaapi-windows/DirectX-Headers-1.0/include")162
.file("src/mf/mf_encoder_factory.cpp")164
//.include(path::PathBuf::from("./vaapi-windows/x64/include"))163
.file("src/mf/mf_h264_encoder_impl.cpp")165
//.file("vaapi-windows/DirectX-Headers-1.0/src/dxguids.cpp")164
.define("USE_MF_VIDEO_CODEC", "1")166
//.file("src/vaapi/vaapi_display_win32.cpp")167
//.file("src/vaapi/vaapi_h264_encoder_wrapper.cpp")168
//.file("src/vaapi/vaapi_encoder_factory.cpp")169
//.file("src/vaapi/h264_encoder_impl.cpp")170
.flag("/std:c++20")165
.flag("/std:c++20")171
//.flag("/wd4819")172
//.flag("/wd4068")173
.flag("/EHsc");166
.flag("/EHsc");174
}167
}175
"linux" => {168
"linux" => {@@ -69,6 +69,10 @@ class PeerConnectionFactory {
69
69
std::shared_ptr<AudioTrack> create_device_audio_track(
70
70
rust::String label) const;
71
71
72
std::shared_ptr<AudioTrack> create_device_audio_track_with_options(
73
rust::String label,
74
bool noise_suppression) const;
75
72
76
RtpCapabilities rtp_sender_capabilities(MediaType type) const;
73
77
74
78
RtpCapabilities rtp_receiver_capabilities(MediaType type) const;
@@ -69,6 +69,10 @@ class PeerConnectionFactory {69
std::shared_ptr<AudioTrack> create_device_audio_track(69
std::shared_ptr<AudioTrack> create_device_audio_track(70
rust::String label) const;70
rust::String label) const;71
71
72
std::shared_ptr<AudioTrack> create_device_audio_track_with_options(73
rust::String label,74
bool noise_suppression) const;75
72
RtpCapabilities rtp_sender_capabilities(MediaType type) const;76
RtpCapabilities rtp_sender_capabilities(MediaType type) const;73
77
74
RtpCapabilities rtp_receiver_capabilities(MediaType type) const;78
RtpCapabilities rtp_receiver_capabilities(MediaType type) const;@@ -117,4 +117,6 @@ rust::String create_random_uuid();
117
117
118
118
rust::Vec<VideoEncoderBackend> video_encoder_backend_list();
119
119
120
void tune_windows_camera(rust::Str target);
121
120
122
} // namespace livekit_ffi
@@ -117,4 +117,6 @@ rust::String create_random_uuid();117
117
118
rust::Vec<VideoEncoderBackend> video_encoder_backend_list();118
rust::Vec<VideoEncoderBackend> video_encoder_backend_list();119
119
120
void tune_windows_camera(rust::Str target);121
120
} // namespace livekit_ffi122
} // namespace livekit_ffi@@ -361,4 +361,32 @@ static void argb_to_nv12(const uint8_t* src_argb,
361
361
height));
362
362
}
363
363
364
static void yuy2_to_i420(const uint8_t* src_yuy2,
365
int src_stride_yuy2,
366
uint8_t* dst_y,
367
int dst_stride_y,
368
uint8_t* dst_u,
369
int dst_stride_u,
370
uint8_t* dst_v,
371
int dst_stride_v,
372
int width,
373
int height) {
374
THROW_ON_ERROR(libyuv::YUY2ToI420(src_yuy2, src_stride_yuy2, dst_y,
375
dst_stride_y, dst_u, dst_stride_u, dst_v,
376
dst_stride_v, width, height));
377
}
378
379
static void argb_scale(const uint8_t* src_argb,
380
int src_stride_argb,
381
int src_width,
382
int src_height,
383
uint8_t* dst_argb,
384
int dst_stride_argb,
385
int dst_width,
386
int dst_height) {
387
THROW_ON_ERROR(libyuv::ARGBScale(src_argb, src_stride_argb, src_width,
388
src_height, dst_argb, dst_stride_argb,
389
dst_width, dst_height, libyuv::kFilterBox));
390
}
391
364
392
} // namespace livekit_ffi
@@ -361,4 +361,32 @@ static void argb_to_nv12(const uint8_t* src_argb,361
height));361
height));362
}362
}363
363
364
static void yuy2_to_i420(const uint8_t* src_yuy2,365
int src_stride_yuy2,366
uint8_t* dst_y,367
int dst_stride_y,368
uint8_t* dst_u,369
int dst_stride_u,370
uint8_t* dst_v,371
int dst_stride_v,372
int width,373
int height) {374
THROW_ON_ERROR(libyuv::YUY2ToI420(src_yuy2, src_stride_yuy2, dst_y,375
dst_stride_y, dst_u, dst_stride_u, dst_v,376
dst_stride_v, width, height));377
}378
379
static void argb_scale(const uint8_t* src_argb,380
int src_stride_argb,381
int src_width,382
int src_height,383
uint8_t* dst_argb,384
int dst_stride_argb,385
int dst_width,386
int dst_height) {387
THROW_ON_ERROR(libyuv::ARGBScale(src_argb, src_stride_argb, src_width,388
src_height, dst_argb, dst_stride_argb,389
dst_width, dst_height, libyuv::kFilterBox));390
}391
364
} // namespace livekit_ffi392
} // namespace livekit_ffi@@ -0,0 +1,111 @@
1
#include "mf_encoder_factory.h"
2
3
#ifndef NOMINMAX
4
#define NOMINMAX
5
#endif
6
#include <windows.h>
7
#include <mfapi.h>
8
#include <mfidl.h>
9
#include <mftransform.h>
10
#include <objbase.h>
11
12
#include <map>
13
#include <memory>
14
#include <mutex>
15
#include <string>
16
17
#include "mf_h264_encoder_impl.h"
18
#include "rtc_base/logging.h"
19
20
namespace webrtc {
21
22
MFVideoEncoderFactory::MFVideoEncoderFactory() {
23
std::map<std::string, std::string> baseline_parameters = {
24
{"profile-level-id", "42e028"},
25
{"level-asymmetry-allowed", "1"},
26
{"packetization-mode", "1"},
27
};
28
supported_formats_.push_back(SdpVideoFormat("H264", baseline_parameters));
29
}
30
31
MFVideoEncoderFactory::~MFVideoEncoderFactory() = default;
32
33
namespace {
34
35
bool ProbeHardwareEncoder() {
36
HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
37
const bool com_owned = SUCCEEDED(hr_com);
38
39
HRESULT hr_mf = MFStartup(MF_VERSION, MFSTARTUP_LITE);
40
if (FAILED(hr_mf)) {
41
if (com_owned) {
42
CoUninitialize();
43
}
44
return false;
45
}
46
47
MFT_REGISTER_TYPE_INFO output_type = {MFMediaType_Video, MFVideoFormat_H264};
48
IMFActivate** activates = nullptr;
49
UINT32 count = 0;
50
51
HRESULT hr = MFTEnumEx(
52
MFT_CATEGORY_VIDEO_ENCODER,
53
MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER,
54
nullptr,
55
&output_type,
56
&activates,
57
&count);
58
59
bool supported = SUCCEEDED(hr) && count > 0;
60
if (activates) {
61
for (UINT32 i = 0; i < count; ++i) {
62
if (activates[i]) {
63
activates[i]->Release();
64
}
65
}
66
CoTaskMemFree(activates);
67
}
68
69
MFShutdown();
70
if (com_owned) {
71
CoUninitialize();
72
}
73
74
if (supported) {
75
RTC_LOG(LS_INFO) << "Media Foundation hardware H.264 encoder available ("
76
<< count << " MFT(s))";
77
} else {
78
RTC_LOG(LS_INFO) << "No Media Foundation hardware H.264 encoder found";
79
}
80
return supported;
81
}
82
83
} // namespace
84
85
bool MFVideoEncoderFactory::IsSupported() {
86
static std::once_flag once;
87
static bool supported = false;
88
std::call_once(once, [] { supported = ProbeHardwareEncoder(); });
89
return supported;
90
}
91
92
std::unique_ptr<VideoEncoder> MFVideoEncoderFactory::Create(
93
const Environment& env,
94
const SdpVideoFormat& format) {
95
for (const auto& supported_format : supported_formats_) {
96
if (format.IsSameCodec(supported_format)) {
97
return std::make_unique<MFH264EncoderImpl>(env, format);
98
}
99
}
100
return nullptr;
101
}
102
103
std::vector<SdpVideoFormat> MFVideoEncoderFactory::GetSupportedFormats() const {
104
return supported_formats_;
105
}
106
107
std::vector<SdpVideoFormat> MFVideoEncoderFactory::GetImplementations() const {
108
return supported_formats_;
109
}
110
111
} // namespace webrtc
@@ -0,0 +1,111 @@1
#include "mf_encoder_factory.h"2
3
#ifndef NOMINMAX4
#define NOMINMAX5
#endif6
#include <windows.h>7
#include <mfapi.h>8
#include <mfidl.h>9
#include <mftransform.h>10
#include <objbase.h>11
12
#include <map>13
#include <memory>14
#include <mutex>15
#include <string>16
17
#include "mf_h264_encoder_impl.h"18
#include "rtc_base/logging.h"19
20
namespace webrtc {21
22
MFVideoEncoderFactory::MFVideoEncoderFactory() {23
std::map<std::string, std::string> baseline_parameters = {24
{"profile-level-id", "42e028"},25
{"level-asymmetry-allowed", "1"},26
{"packetization-mode", "1"},27
};28
supported_formats_.push_back(SdpVideoFormat("H264", baseline_parameters));29
}30
31
MFVideoEncoderFactory::~MFVideoEncoderFactory() = default;32
33
namespace {34
35
bool ProbeHardwareEncoder() {36
HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);37
const bool com_owned = SUCCEEDED(hr_com);38
39
HRESULT hr_mf = MFStartup(MF_VERSION, MFSTARTUP_LITE);40
if (FAILED(hr_mf)) {41
if (com_owned) {42
CoUninitialize();43
}44
return false;45
}46
47
MFT_REGISTER_TYPE_INFO output_type = {MFMediaType_Video, MFVideoFormat_H264};48
IMFActivate** activates = nullptr;49
UINT32 count = 0;50
51
HRESULT hr = MFTEnumEx(52
MFT_CATEGORY_VIDEO_ENCODER,53
MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER,54
nullptr,55
&output_type,56
&activates,57
&count);58
59
bool supported = SUCCEEDED(hr) && count > 0;60
if (activates) {61
for (UINT32 i = 0; i < count; ++i) {62
if (activates[i]) {63
activates[i]->Release();64
}65
}66
CoTaskMemFree(activates);67
}68
69
MFShutdown();70
if (com_owned) {71
CoUninitialize();72
}73
74
if (supported) {75
RTC_LOG(LS_INFO) << "Media Foundation hardware H.264 encoder available ("76
<< count << " MFT(s))";77
} else {78
RTC_LOG(LS_INFO) << "No Media Foundation hardware H.264 encoder found";79
}80
return supported;81
}82
83
} // namespace84
85
bool MFVideoEncoderFactory::IsSupported() {86
static std::once_flag once;87
static bool supported = false;88
std::call_once(once, [] { supported = ProbeHardwareEncoder(); });89
return supported;90
}91
92
std::unique_ptr<VideoEncoder> MFVideoEncoderFactory::Create(93
const Environment& env,94
const SdpVideoFormat& format) {95
for (const auto& supported_format : supported_formats_) {96
if (format.IsSameCodec(supported_format)) {97
return std::make_unique<MFH264EncoderImpl>(env, format);98
}99
}100
return nullptr;101
}102
103
std::vector<SdpVideoFormat> MFVideoEncoderFactory::GetSupportedFormats() const {104
return supported_formats_;105
}106
107
std::vector<SdpVideoFormat> MFVideoEncoderFactory::GetImplementations() const {108
return supported_formats_;109
}110
111
} // namespace webrtc@@ -0,0 +1,36 @@
1
#ifndef MF_VIDEO_ENCODER_FACTORY_H_
2
#define MF_VIDEO_ENCODER_FACTORY_H_
3
4
#include <vector>
5
6
#include "api/environment/environment.h"
7
#include "api/video_codecs/sdp_video_format.h"
8
#include "api/video_codecs/video_encoder_factory.h"
9
10
namespace webrtc {
11
12
class MFVideoEncoderFactory : public VideoEncoderFactory {
13
public:
14
MFVideoEncoderFactory();
15
~MFVideoEncoderFactory() override;
16
17
static bool IsSupported();
18
19
std::unique_ptr<VideoEncoder> Create(const Environment& env,
20
const SdpVideoFormat& format) override;
21
22
std::vector<SdpVideoFormat> GetSupportedFormats() const override;
23
24
std::vector<SdpVideoFormat> GetImplementations() const override;
25
26
std::unique_ptr<EncoderSelectorInterface> GetEncoderSelector() const override {
27
return nullptr;
28
}
29
30
private:
31
std::vector<SdpVideoFormat> supported_formats_;
32
};
33
34
} // namespace webrtc
35
36
#endif // MF_VIDEO_ENCODER_FACTORY_H_
@@ -0,0 +1,36 @@1
#ifndef MF_VIDEO_ENCODER_FACTORY_H_2
#define MF_VIDEO_ENCODER_FACTORY_H_3
4
#include <vector>5
6
#include "api/environment/environment.h"7
#include "api/video_codecs/sdp_video_format.h"8
#include "api/video_codecs/video_encoder_factory.h"9
10
namespace webrtc {11
12
class MFVideoEncoderFactory : public VideoEncoderFactory {13
public:14
MFVideoEncoderFactory();15
~MFVideoEncoderFactory() override;16
17
static bool IsSupported();18
19
std::unique_ptr<VideoEncoder> Create(const Environment& env,20
const SdpVideoFormat& format) override;21
22
std::vector<SdpVideoFormat> GetSupportedFormats() const override;23
24
std::vector<SdpVideoFormat> GetImplementations() const override;25
26
std::unique_ptr<EncoderSelectorInterface> GetEncoderSelector() const override {27
return nullptr;28
}29
30
private:31
std::vector<SdpVideoFormat> supported_formats_;32
};33
34
} // namespace webrtc35
36
#endif // MF_VIDEO_ENCODER_FACTORY_H_@@ -0,0 +1,686 @@
1
#include "mf_h264_encoder_impl.h"
2
3
#include <mferror.h>
4
#include <objbase.h>
5
#include <oleauto.h>
6
7
#include <algorithm>
8
#include <chrono>
9
#include <cstring>
10
11
#include "api/video/i420_buffer.h"
12
#include "modules/video_coding/include/video_codec_interface.h"
13
#include "modules/video_coding/include/video_error_codes.h"
14
#include "rtc_base/logging.h"
15
#include "third_party/libyuv/include/libyuv/convert.h"
16
17
namespace webrtc {
18
19
namespace {
20
21
using Microsoft::WRL::ComPtr;
22
23
bool ContainsIdrNal(const uint8_t* data, size_t size) {
24
for (size_t i = 0; i + 4 <= size; ++i) {
25
size_t start_len = 0;
26
if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) {
27
start_len = 3;
28
} else if (i + 5 <= size && data[i] == 0 && data[i + 1] == 0 &&
29
data[i + 2] == 0 && data[i + 3] == 1) {
30
start_len = 4;
31
}
32
if (start_len > 0) {
33
uint8_t nal_type = data[i + start_len] & 0x1F;
34
if (nal_type == 5) {
35
return true;
36
}
37
i += start_len;
38
}
39
}
40
return false;
41
}
42
43
} // namespace
44
45
MFH264EncoderImpl::MFH264EncoderImpl(const Environment& env,
46
const SdpVideoFormat& format)
47
: env_(env),
48
format_(format),
49
packetization_mode_(
50
H264EncoderSettings::Parse(format).packetization_mode) {}
51
52
MFH264EncoderImpl::~MFH264EncoderImpl() {
53
Release();
54
}
55
56
void MFH264EncoderImpl::SetCodecUint32(const GUID& key, uint32_t value) {
57
if (!codec_api_) {
58
return;
59
}
60
VARIANT var;
61
VariantInit(&var);
62
var.vt = VT_UI4;
63
var.ulVal = value;
64
codec_api_->SetValue(&key, &var);
65
VariantClear(&var);
66
}
67
68
void MFH264EncoderImpl::SetCodecBool(const GUID& key, bool value) {
69
if (!codec_api_) {
70
return;
71
}
72
VARIANT var;
73
VariantInit(&var);
74
var.vt = VT_BOOL;
75
var.boolVal = value ? VARIANT_TRUE : VARIANT_FALSE;
76
codec_api_->SetValue(&key, &var);
77
VariantClear(&var);
78
}
79
80
bool MFH264EncoderImpl::ConfigureMft(uint32_t width,
81
uint32_t height,
82
uint32_t fps,
83
uint32_t bitrate_bps) {
84
MFT_REGISTER_TYPE_INFO output_filter = {MFMediaType_Video,
85
MFVideoFormat_H264};
86
IMFActivate** activates = nullptr;
87
UINT32 count = 0;
88
89
HRESULT hr = MFTEnumEx(
90
MFT_CATEGORY_VIDEO_ENCODER,
91
MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER,
92
nullptr,
93
&output_filter,
94
&activates,
95
&count);
96
if (FAILED(hr) || count == 0 || !activates) {
97
RTC_LOG(LS_WARNING) << "MFH264: no hardware H.264 MFT available";
98
return false;
99
}
100
101
for (UINT32 i = 0; i < count && !mft_; ++i) {
102
if (!activates[i]) {
103
continue;
104
}
105
ComPtr<IMFTransform> candidate;
106
if (SUCCEEDED(activates[i]->ActivateObject(IID_PPV_ARGS(&candidate))) &&
107
candidate) {
108
mft_ = candidate;
109
}
110
}
111
for (UINT32 i = 0; i < count; ++i) {
112
if (activates[i]) {
113
activates[i]->Release();
114
}
115
}
116
CoTaskMemFree(activates);
117
118
if (!mft_) {
119
RTC_LOG(LS_WARNING) << "MFH264: failed to activate hardware H.264 MFT";
120
return false;
121
}
122
123
// Unlock async hardware MFTs (AMD AMF, Intel QSV, NVIDIA MFT).
124
ComPtr<IMFAttributes> attrs;
125
if (SUCCEEDED(mft_->GetAttributes(&attrs)) && attrs) {
126
UINT32 async_flag = 0;
127
if (SUCCEEDED(attrs->GetUINT32(MF_TRANSFORM_ASYNC, &async_flag)) &&
128
async_flag != 0) {
129
hr = attrs->SetUINT32(MF_TRANSFORM_ASYNC_UNLOCK, TRUE);
130
if (FAILED(hr)) {
131
RTC_LOG(LS_WARNING) << "MFH264: failed to unlock async MFT";
132
return false;
133
}
134
hr = mft_.As(&event_gen_);
135
if (FAILED(hr) || !event_gen_) {
136
RTC_LOG(LS_WARNING) << "MFH264: async MFT missing IMFMediaEventGenerator";
137
return false;
138
}
139
is_async_ = true;
140
}
141
}
142
143
DWORD in_count = 0;
144
DWORD out_count = 0;
145
if (SUCCEEDED(mft_->GetStreamCount(&in_count, &out_count)) &&
146
in_count > 0 && out_count > 0) {
147
std::vector<DWORD> in_ids(in_count, 0);
148
std::vector<DWORD> out_ids(out_count, 0);
149
if (SUCCEEDED(
150
mft_->GetStreamIDs(in_count, in_ids.data(), out_count, out_ids.data()))) {
151
in_stream_id_ = in_ids[0];
152
out_stream_id_ = out_ids[0];
153
} else {
154
in_stream_id_ = 0;
155
out_stream_id_ = 0;
156
}
157
}
158
159
// Configure low-latency WebRTC properties before media types.
160
mft_.As(&codec_api_);
161
SetCodecBool(CODECAPI_AVLowLatencyMode, true);
162
SetCodecUint32(CODECAPI_AVEncCommonRateControlMode,
163
eAVEncCommonRateControlMode_CBR);
164
SetCodecUint32(CODECAPI_AVEncCommonMeanBitRate, bitrate_bps);
165
SetCodecUint32(CODECAPI_AVEncCommonQualityVsSpeed, 33);
166
SetCodecBool(CODECAPI_AVEncH264CABACEnable, false);
167
SetCodecUint32(CODECAPI_AVEncMPVDefaultBPictureCount, 0);
168
SetCodecUint32(CODECAPI_AVEncMPVGOPSize, std::max<uint32_t>(fps * 5, 30));
169
170
ComPtr<IMFMediaType> out_type;
171
hr = MFCreateMediaType(&out_type);
172
if (FAILED(hr)) {
173
return false;
174
}
175
out_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
176
out_type->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);
177
out_type->SetUINT32(MF_MT_AVG_BITRATE, bitrate_bps);
178
out_type->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
179
out_type->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_Base);
180
// Level 3.1 covers 720p30. Anything larger is level 4.0, matching the
181
// 42e028 offer so the SPS does not exceed the negotiated level.
182
const uint32_t h264_level =
183
(height > 720 || fps > 30) ? eAVEncH264VLevel4 : eAVEncH264VLevel3_1;
184
out_type->SetUINT32(MF_MT_MPEG2_LEVEL, h264_level);
185
SetCodecUint32(CODECAPI_AVEncMPVLevel, h264_level);
186
MFSetAttributeSize(out_type.Get(), MF_MT_FRAME_SIZE, width, height);
187
MFSetAttributeRatio(out_type.Get(), MF_MT_FRAME_RATE, fps, 1);
188
MFSetAttributeRatio(out_type.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
189
190
hr = mft_->SetOutputType(out_stream_id_, out_type.Get(), 0);
191
if (FAILED(hr)) {
192
RTC_LOG(LS_WARNING) << "MFH264: SetOutputType failed: 0x" << std::hex << hr;
193
return false;
194
}
195
196
ComPtr<IMFMediaType> in_type;
197
hr = MFCreateMediaType(&in_type);
198
if (FAILED(hr)) {
199
return false;
200
}
201
in_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);
202
in_type->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_NV12);
203
in_type->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);
204
MFSetAttributeSize(in_type.Get(), MF_MT_FRAME_SIZE, width, height);
205
MFSetAttributeRatio(in_type.Get(), MF_MT_FRAME_RATE, fps, 1);
206
MFSetAttributeRatio(in_type.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);
207
208
hr = mft_->SetInputType(in_stream_id_, in_type.Get(), 0);
209
if (FAILED(hr)) {
210
RTC_LOG(LS_WARNING) << "MFH264: SetInputType(NV12) failed: 0x" << std::hex
211
<< hr;
212
return false;
213
}
214
215
MFT_OUTPUT_STREAM_INFO out_info = {};
216
if (SUCCEEDED(mft_->GetOutputStreamInfo(out_stream_id_, &out_info))) {
217
output_provides_samples_ =
218
(out_info.dwFlags &
219
(MFT_OUTPUT_STREAM_PROVIDES_SAMPLES |
220
MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES)) != 0;
221
}
222
223
hr = mft_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0);
224
if (FAILED(hr)) {
225
RTC_LOG(LS_WARNING) << "MFH264: BEGIN_STREAMING failed: 0x" << std::hex
226
<< hr;
227
return false;
228
}
229
hr = mft_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);
230
if (FAILED(hr)) {
231
RTC_LOG(LS_WARNING) << "MFH264: START_OF_STREAM failed: 0x" << std::hex
232
<< hr;
233
return false;
234
}
235
236
RTC_LOG(LS_INFO) << "MFH264: initialized " << width << "x" << height << " @"
237
<< fps << "fps " << (bitrate_bps / 1000) << " kbps (async="
238
<< (is_async_ ? "true" : "false") << ")";
239
return true;
240
}
241
242
int32_t MFH264EncoderImpl::InitEncode(const VideoCodec* inst,
243
const Settings& /*settings*/) {
244
if (!inst || inst->codecType != kVideoCodecH264 || inst->width < 2 ||
245
inst->height < 2) {
246
return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;
247
}
248
249
Release();
250
251
HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
252
com_initialized_ = SUCCEEDED(hr_com);
253
254
if (FAILED(MFStartup(MF_VERSION, MFSTARTUP_LITE))) {
255
Release();
256
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
257
}
258
mf_started_ = true;
259
260
width_ = inst->width;
261
height_ = inst->height;
262
max_fps_ = std::max<uint32_t>(inst->maxFramerate, 1);
263
target_bps_ = std::max<uint32_t>(inst->startBitrate * 1000, 150000);
264
frame_index_ = 0;
265
sending_ = true;
266
key_frame_request_ = true;
267
async_need_input_ = 0;
268
pending_meta_.clear();
269
270
if (!ConfigureMft(width_, height_, max_fps_, target_bps_)) {
271
Release();
272
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
273
}
274
275
initialized_ = true;
276
return WEBRTC_VIDEO_CODEC_OK;
277
}
278
279
int32_t MFH264EncoderImpl::RegisterEncodeCompleteCallback(
280
EncodedImageCallback* callback) {
281
encoded_image_callback_ = callback;
282
return WEBRTC_VIDEO_CODEC_OK;
283
}
284
285
int32_t MFH264EncoderImpl::Release() {
286
if (mft_) {
287
mft_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);
288
mft_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);
289
}
290
event_gen_.Reset();
291
codec_api_.Reset();
292
mft_.Reset();
293
pending_meta_.clear();
294
initialized_ = false;
295
is_async_ = false;
296
async_need_input_ = 0;
297
298
if (mf_started_) {
299
MFShutdown();
300
mf_started_ = false;
301
}
302
if (com_initialized_) {
303
CoUninitialize();
304
com_initialized_ = false;
305
}
306
return WEBRTC_VIDEO_CODEC_OK;
307
}
308
309
void MFH264EncoderImpl::EmitEncodedBuffer(const uint8_t* data,
310
size_t size,
311
bool clean_point,
312
LONGLONG sample_time) {
313
if (!encoded_image_callback_ || !data || size == 0) {
314
return;
315
}
316
317
PendingFrameMeta meta = {0, 0, std::nullopt};
318
auto matched = pending_meta_.find(sample_time);
319
if (matched != pending_meta_.end()) {
320
meta = matched->second;
321
}
322
// Drop this sample and any older unmatched input. A dropped MFT frame must
323
// not shift the RTP timestamp of every later frame.
324
if (sample_time >= 0) {
325
auto end = pending_meta_.upper_bound(sample_time);
326
pending_meta_.erase(pending_meta_.begin(), end);
327
}
328
329
const bool is_key = clean_point || ContainsIdrNal(data, size);
330
331
encoded_image_.SetEncodedData(EncodedImageBuffer::Create(data, size));
332
h264_bitstream_parser_.ParseBitstream(encoded_image_);
333
encoded_image_.qp_ = h264_bitstream_parser_.GetLastSliceQp().value_or(-1);
334
encoded_image_._encodedWidth = width_;
335
encoded_image_._encodedHeight = height_;
336
encoded_image_.SetRtpTimestamp(meta.rtp_timestamp);
337
encoded_image_.capture_time_ms_ = meta.capture_time_ms;
338
encoded_image_.SetColorSpace(meta.color_space);
339
encoded_image_._frameType =
340
is_key ? VideoFrameType::kVideoFrameKey : VideoFrameType::kVideoFrameDelta;
341
342
CodecSpecificInfo codec_specific;
343
codec_specific.codecType = kVideoCodecH264;
344
codec_specific.codecSpecific.H264.packetization_mode = packetization_mode_;
345
codec_specific.codecSpecific.H264.temporal_idx = kNoTemporalIdx;
346
codec_specific.codecSpecific.H264.base_layer_sync = false;
347
codec_specific.codecSpecific.H264.idr_frame = is_key;
348
349
encoded_image_callback_->OnEncodedImage(encoded_image_, &codec_specific);
350
}
351
352
bool MFH264EncoderImpl::ProcessOneOutputSample() {
353
MFT_OUTPUT_DATA_BUFFER out_buf = {};
354
out_buf.dwStreamID = out_stream_id_;
355
ComPtr<IMFSample> owned_sample;
356
357
if (!output_provides_samples_) {
358
MFT_OUTPUT_STREAM_INFO info = {};
359
if (FAILED(mft_->GetOutputStreamInfo(out_stream_id_, &info))) {
360
return false;
361
}
362
DWORD alloc_size = std::max<DWORD>(info.cbSize, width_ * height_ * 3 / 2);
363
ComPtr<IMFMediaBuffer> buf;
364
if (FAILED(MFCreateMemoryBuffer(alloc_size, &buf)) ||
365
FAILED(MFCreateSample(&owned_sample))) {
366
return false;
367
}
368
owned_sample->AddBuffer(buf.Get());
369
out_buf.pSample = owned_sample.Get();
370
}
371
372
DWORD status = 0;
373
HRESULT hr = mft_->ProcessOutput(0, 1, &out_buf, &status);
374
375
if (out_buf.pEvents) {
376
out_buf.pEvents->Release();
377
out_buf.pEvents = nullptr;
378
}
379
380
if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {
381
ComPtr<IMFMediaType> new_type;
382
if (SUCCEEDED(mft_->GetOutputAvailableType(out_stream_id_, 0, &new_type))) {
383
mft_->SetOutputType(out_stream_id_, new_type.Get(), 0);
384
}
385
return true;
386
}
387
388
if (FAILED(hr) || !out_buf.pSample) {
389
return false;
390
}
391
392
ComPtr<IMFSample> sample;
393
if (output_provides_samples_) {
394
sample.Attach(out_buf.pSample);
395
} else {
396
sample = owned_sample;
397
}
398
399
UINT32 clean_point = 0;
400
sample->GetUINT32(MFSampleExtension_CleanPoint, &clean_point);
401
LONGLONG sample_time = -1;
402
sample->GetSampleTime(&sample_time);
403
404
ComPtr<IMFMediaBuffer> contiguous;
405
if (SUCCEEDED(sample->ConvertToContiguousBuffer(&contiguous)) && contiguous) {
406
BYTE* ptr = nullptr;
407
DWORD cur_len = 0;
408
if (SUCCEEDED(contiguous->Lock(&ptr, nullptr, &cur_len)) && ptr &&
409
cur_len > 0) {
410
EmitEncodedBuffer(ptr, cur_len, clean_point != 0, sample_time);
411
contiguous->Unlock();
412
}
413
}
414
return true;
415
}
416
417
bool MFH264EncoderImpl::DrainSyncOutput() {
418
for (;;) {
419
MFT_OUTPUT_DATA_BUFFER out_buf = {};
420
out_buf.dwStreamID = out_stream_id_;
421
ComPtr<IMFSample> owned_sample;
422
423
if (!output_provides_samples_) {
424
MFT_OUTPUT_STREAM_INFO info = {};
425
if (FAILED(mft_->GetOutputStreamInfo(out_stream_id_, &info))) {
426
return false;
427
}
428
DWORD alloc_size = std::max<DWORD>(info.cbSize, width_ * height_ * 3 / 2);
429
ComPtr<IMFMediaBuffer> buf;
430
if (FAILED(MFCreateMemoryBuffer(alloc_size, &buf)) ||
431
FAILED(MFCreateSample(&owned_sample))) {
432
return false;
433
}
434
owned_sample->AddBuffer(buf.Get());
435
out_buf.pSample = owned_sample.Get();
436
}
437
438
DWORD status = 0;
439
HRESULT hr = mft_->ProcessOutput(0, 1, &out_buf, &status);
440
if (out_buf.pEvents) {
441
out_buf.pEvents->Release();
442
out_buf.pEvents = nullptr;
443
}
444
if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) {
445
return true;
446
}
447
if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {
448
ComPtr<IMFMediaType> new_type;
449
if (SUCCEEDED(
450
mft_->GetOutputAvailableType(out_stream_id_, 0, &new_type))) {
451
mft_->SetOutputType(out_stream_id_, new_type.Get(), 0);
452
}
453
continue;
454
}
455
if (FAILED(hr) || !out_buf.pSample) {
456
return false;
457
}
458
459
ComPtr<IMFSample> sample;
460
if (output_provides_samples_) {
461
sample.Attach(out_buf.pSample);
462
} else {
463
sample = owned_sample;
464
}
465
466
UINT32 clean_point = 0;
467
sample->GetUINT32(MFSampleExtension_CleanPoint, &clean_point);
468
LONGLONG sample_time = -1;
469
sample->GetSampleTime(&sample_time);
470
471
ComPtr<IMFMediaBuffer> contiguous;
472
if (SUCCEEDED(sample->ConvertToContiguousBuffer(&contiguous)) &&
473
contiguous) {
474
BYTE* ptr = nullptr;
475
DWORD cur_len = 0;
476
if (SUCCEEDED(contiguous->Lock(&ptr, nullptr, &cur_len)) && ptr &&
477
cur_len > 0) {
478
EmitEncodedBuffer(ptr, cur_len, clean_point != 0, sample_time);
479
contiguous->Unlock();
480
}
481
}
482
}
483
}
484
485
bool MFH264EncoderImpl::PumpAsyncUntilInputNeeded() {
486
const auto deadline =
487
std::chrono::steady_clock::now() + std::chrono::milliseconds(200);
488
while (async_need_input_ <= 0) {
489
if (std::chrono::steady_clock::now() >= deadline) {
490
RTC_LOG(LS_WARNING)
491
<< "MFH264: async MFT sent no input event within 200 ms";
492
return false;
493
}
494
ComPtr<IMFMediaEvent> event;
495
HRESULT hr = event_gen_->GetEvent(MF_EVENT_FLAG_NO_WAIT, &event);
496
if (hr == MF_E_NO_EVENTS_AVAILABLE) {
497
Sleep(1);
498
continue;
499
}
500
if (FAILED(hr) || !event) {
501
return false;
502
}
503
MediaEventType type = MEUnknown;
504
event->GetType(&type);
505
if (type == METransformNeedInput) {
506
++async_need_input_;
507
} else if (type == METransformHaveOutput) {
508
if (!ProcessOneOutputSample()) {
509
return false;
510
}
511
}
512
}
513
return async_need_input_ > 0;
514
}
515
516
bool MFH264EncoderImpl::DrainAsyncReadyOutputs() {
517
for (int attempts = 0; attempts < 16; ++attempts) {
518
ComPtr<IMFMediaEvent> event;
519
HRESULT hr = event_gen_->GetEvent(MF_EVENT_FLAG_NO_WAIT, &event);
520
if (hr == MF_E_NO_EVENTS_AVAILABLE) {
521
return true;
522
}
523
if (FAILED(hr) || !event) {
524
return false;
525
}
526
MediaEventType type = MEUnknown;
527
event->GetType(&type);
528
if (type == METransformNeedInput) {
529
++async_need_input_;
530
} else if (type == METransformHaveOutput) {
531
if (!ProcessOneOutputSample()) {
532
return false;
533
}
534
}
535
}
536
return true;
537
}
538
539
int32_t MFH264EncoderImpl::Encode(
540
const VideoFrame& input_frame,
541
const std::vector<VideoFrameType>* frame_types) {
542
if (!initialized_ || !mft_ || !encoded_image_callback_) {
543
return WEBRTC_VIDEO_CODEC_UNINITIALIZED;
544
}
545
if (!sending_) {
546
return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
547
}
548
if (frame_types && !frame_types->empty() &&
549
(*frame_types)[0] == VideoFrameType::kEmptyFrame) {
550
return WEBRTC_VIDEO_CODEC_NO_OUTPUT;
551
}
552
553
webrtc::scoped_refptr<I420BufferInterface> i420 =
554
input_frame.video_frame_buffer()->ToI420();
555
if (!i420) {
556
return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
557
}
558
559
if (static_cast<uint32_t>(i420->width()) != width_ ||
560
static_cast<uint32_t>(i420->height()) != height_) {
561
// Resolution changed dynamically: re-init MFT or fall back cleanly.
562
width_ = static_cast<uint32_t>(i420->width());
563
height_ = static_cast<uint32_t>(i420->height());
564
mft_.Reset();
565
codec_api_.Reset();
566
event_gen_.Reset();
567
is_async_ = false;
568
async_need_input_ = 0;
569
pending_meta_.clear();
570
if (!ConfigureMft(width_, height_, max_fps_, target_bps_)) {
571
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
572
}
573
key_frame_request_ = true;
574
}
575
576
const bool send_key_frame =
577
key_frame_request_ ||
578
(frame_types && !frame_types->empty() &&
579
(*frame_types)[0] == VideoFrameType::kVideoFrameKey);
580
if (send_key_frame) {
581
key_frame_request_ = false;
582
SetCodecUint32(CODECAPI_AVEncVideoForceKeyFrame, 1);
583
}
584
585
const uint32_t nv12_size = width_ * height_ * 3 / 2;
586
ComPtr<IMFMediaBuffer> in_buffer;
587
ComPtr<IMFSample> in_sample;
588
if (FAILED(MFCreateMemoryBuffer(nv12_size, &in_buffer)) ||
589
FAILED(MFCreateSample(&in_sample))) {
590
return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
591
}
592
593
BYTE* dst = nullptr;
594
if (FAILED(in_buffer->Lock(&dst, nullptr, nullptr)) || !dst) {
595
return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;
596
}
597
uint8_t* dst_y = dst;
598
uint8_t* dst_uv = dst + width_ * height_;
599
libyuv::I420ToNV12(i420->DataY(), i420->StrideY(), i420->DataU(),
600
i420->StrideU(), i420->DataV(), i420->StrideV(), dst_y,
601
static_cast<int>(width_), dst_uv,
602
static_cast<int>(width_), static_cast<int>(width_),
603
static_cast<int>(height_));
604
in_buffer->Unlock();
605
in_buffer->SetCurrentLength(nv12_size);
606
in_sample->AddBuffer(in_buffer.Get());
607
608
const LONGLONG duration_100ns = 10000000LL / std::max<uint32_t>(max_fps_, 1);
609
const LONGLONG sample_time = frame_index_ * duration_100ns;
610
in_sample->SetSampleTime(sample_time);
611
in_sample->SetSampleDuration(duration_100ns);
612
++frame_index_;
613
614
pending_meta_[sample_time] = PendingFrameMeta{
615
input_frame.rtp_timestamp(),
616
input_frame.render_time_ms(),
617
input_frame.color_space(),
618
};
619
620
if (is_async_) {
621
if (!PumpAsyncUntilInputNeeded()) {
622
pending_meta_.erase(sample_time);
623
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
624
}
625
--async_need_input_;
626
HRESULT hr = mft_->ProcessInput(in_stream_id_, in_sample.Get(), 0);
627
if (FAILED(hr)) {
628
pending_meta_.erase(sample_time);
629
RTC_LOG(LS_WARNING) << "MFH264: async ProcessInput failed: 0x" << std::hex
630
<< hr;
631
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
632
}
633
if (!DrainAsyncReadyOutputs()) {
634
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
635
}
636
} else {
637
HRESULT hr = mft_->ProcessInput(in_stream_id_, in_sample.Get(), 0);
638
if (FAILED(hr)) {
639
pending_meta_.erase(sample_time);
640
RTC_LOG(LS_WARNING) << "MFH264: sync ProcessInput failed: 0x" << std::hex
641
<< hr;
642
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
643
}
644
if (!DrainSyncOutput()) {
645
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;
646
}
647
}
648
649
return WEBRTC_VIDEO_CODEC_OK;
650
}
651
652
void MFH264EncoderImpl::SetRates(const RateControlParameters& parameters) {
653
if (!initialized_) {
654
return;
655
}
656
if (parameters.bitrate.get_sum_bps() == 0) {
657
sending_ = false;
658
return;
659
}
660
const uint32_t new_bps =
661
std::max<uint32_t>(parameters.bitrate.GetSpatialLayerSum(0), 100000);
662
if (!sending_) {
663
sending_ = true;
664
key_frame_request_ = true;
665
}
666
if (parameters.framerate_fps >= 1.0) {
667
max_fps_ = static_cast<uint32_t>(parameters.framerate_fps);
668
}
669
if (new_bps != target_bps_) {
670
target_bps_ = new_bps;
671
SetCodecUint32(CODECAPI_AVEncCommonMeanBitRate, target_bps_);
672
}
673
}
674
675
VideoEncoder::EncoderInfo MFH264EncoderImpl::GetEncoderInfo() const {
676
EncoderInfo info;
677
info.supports_native_handle = false;
678
info.implementation_name = "MediaFoundation H264";
679
info.scaling_settings = VideoEncoder::ScalingSettings::kOff;
680
info.is_hardware_accelerated = true;
681
info.supports_simulcast = false;
682
info.preferred_pixel_formats = {VideoFrameBuffer::Type::kI420};
683
return info;
684
}
685
686
} // namespace webrtc
@@ -0,0 +1,686 @@1
#include "mf_h264_encoder_impl.h"2
3
#include <mferror.h>4
#include <objbase.h>5
#include <oleauto.h>6
7
#include <algorithm>8
#include <chrono>9
#include <cstring>10
11
#include "api/video/i420_buffer.h"12
#include "modules/video_coding/include/video_codec_interface.h"13
#include "modules/video_coding/include/video_error_codes.h"14
#include "rtc_base/logging.h"15
#include "third_party/libyuv/include/libyuv/convert.h"16
17
namespace webrtc {18
19
namespace {20
21
using Microsoft::WRL::ComPtr;22
23
bool ContainsIdrNal(const uint8_t* data, size_t size) {24
for (size_t i = 0; i + 4 <= size; ++i) {25
size_t start_len = 0;26
if (data[i] == 0 && data[i + 1] == 0 && data[i + 2] == 1) {27
start_len = 3;28
} else if (i + 5 <= size && data[i] == 0 && data[i + 1] == 0 &&29
data[i + 2] == 0 && data[i + 3] == 1) {30
start_len = 4;31
}32
if (start_len > 0) {33
uint8_t nal_type = data[i + start_len] & 0x1F;34
if (nal_type == 5) {35
return true;36
}37
i += start_len;38
}39
}40
return false;41
}42
43
} // namespace44
45
MFH264EncoderImpl::MFH264EncoderImpl(const Environment& env,46
const SdpVideoFormat& format)47
: env_(env),48
format_(format),49
packetization_mode_(50
H264EncoderSettings::Parse(format).packetization_mode) {}51
52
MFH264EncoderImpl::~MFH264EncoderImpl() {53
Release();54
}55
56
void MFH264EncoderImpl::SetCodecUint32(const GUID& key, uint32_t value) {57
if (!codec_api_) {58
return;59
}60
VARIANT var;61
VariantInit(&var);62
var.vt = VT_UI4;63
var.ulVal = value;64
codec_api_->SetValue(&key, &var);65
VariantClear(&var);66
}67
68
void MFH264EncoderImpl::SetCodecBool(const GUID& key, bool value) {69
if (!codec_api_) {70
return;71
}72
VARIANT var;73
VariantInit(&var);74
var.vt = VT_BOOL;75
var.boolVal = value ? VARIANT_TRUE : VARIANT_FALSE;76
codec_api_->SetValue(&key, &var);77
VariantClear(&var);78
}79
80
bool MFH264EncoderImpl::ConfigureMft(uint32_t width,81
uint32_t height,82
uint32_t fps,83
uint32_t bitrate_bps) {84
MFT_REGISTER_TYPE_INFO output_filter = {MFMediaType_Video,85
MFVideoFormat_H264};86
IMFActivate** activates = nullptr;87
UINT32 count = 0;88
89
HRESULT hr = MFTEnumEx(90
MFT_CATEGORY_VIDEO_ENCODER,91
MFT_ENUM_FLAG_HARDWARE | MFT_ENUM_FLAG_SORTANDFILTER,92
nullptr,93
&output_filter,94
&activates,95
&count);96
if (FAILED(hr) || count == 0 || !activates) {97
RTC_LOG(LS_WARNING) << "MFH264: no hardware H.264 MFT available";98
return false;99
}100
101
for (UINT32 i = 0; i < count && !mft_; ++i) {102
if (!activates[i]) {103
continue;104
}105
ComPtr<IMFTransform> candidate;106
if (SUCCEEDED(activates[i]->ActivateObject(IID_PPV_ARGS(&candidate))) &&107
candidate) {108
mft_ = candidate;109
}110
}111
for (UINT32 i = 0; i < count; ++i) {112
if (activates[i]) {113
activates[i]->Release();114
}115
}116
CoTaskMemFree(activates);117
118
if (!mft_) {119
RTC_LOG(LS_WARNING) << "MFH264: failed to activate hardware H.264 MFT";120
return false;121
}122
123
// Unlock async hardware MFTs (AMD AMF, Intel QSV, NVIDIA MFT).124
ComPtr<IMFAttributes> attrs;125
if (SUCCEEDED(mft_->GetAttributes(&attrs)) && attrs) {126
UINT32 async_flag = 0;127
if (SUCCEEDED(attrs->GetUINT32(MF_TRANSFORM_ASYNC, &async_flag)) &&128
async_flag != 0) {129
hr = attrs->SetUINT32(MF_TRANSFORM_ASYNC_UNLOCK, TRUE);130
if (FAILED(hr)) {131
RTC_LOG(LS_WARNING) << "MFH264: failed to unlock async MFT";132
return false;133
}134
hr = mft_.As(&event_gen_);135
if (FAILED(hr) || !event_gen_) {136
RTC_LOG(LS_WARNING) << "MFH264: async MFT missing IMFMediaEventGenerator";137
return false;138
}139
is_async_ = true;140
}141
}142
143
DWORD in_count = 0;144
DWORD out_count = 0;145
if (SUCCEEDED(mft_->GetStreamCount(&in_count, &out_count)) &&146
in_count > 0 && out_count > 0) {147
std::vector<DWORD> in_ids(in_count, 0);148
std::vector<DWORD> out_ids(out_count, 0);149
if (SUCCEEDED(150
mft_->GetStreamIDs(in_count, in_ids.data(), out_count, out_ids.data()))) {151
in_stream_id_ = in_ids[0];152
out_stream_id_ = out_ids[0];153
} else {154
in_stream_id_ = 0;155
out_stream_id_ = 0;156
}157
}158
159
// Configure low-latency WebRTC properties before media types.160
mft_.As(&codec_api_);161
SetCodecBool(CODECAPI_AVLowLatencyMode, true);162
SetCodecUint32(CODECAPI_AVEncCommonRateControlMode,163
eAVEncCommonRateControlMode_CBR);164
SetCodecUint32(CODECAPI_AVEncCommonMeanBitRate, bitrate_bps);165
SetCodecUint32(CODECAPI_AVEncCommonQualityVsSpeed, 33);166
SetCodecBool(CODECAPI_AVEncH264CABACEnable, false);167
SetCodecUint32(CODECAPI_AVEncMPVDefaultBPictureCount, 0);168
SetCodecUint32(CODECAPI_AVEncMPVGOPSize, std::max<uint32_t>(fps * 5, 30));169
170
ComPtr<IMFMediaType> out_type;171
hr = MFCreateMediaType(&out_type);172
if (FAILED(hr)) {173
return false;174
}175
out_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);176
out_type->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_H264);177
out_type->SetUINT32(MF_MT_AVG_BITRATE, bitrate_bps);178
out_type->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);179
out_type->SetUINT32(MF_MT_MPEG2_PROFILE, eAVEncH264VProfile_Base);180
// Level 3.1 covers 720p30. Anything larger is level 4.0, matching the181
// 42e028 offer so the SPS does not exceed the negotiated level.182
const uint32_t h264_level =183
(height > 720 || fps > 30) ? eAVEncH264VLevel4 : eAVEncH264VLevel3_1;184
out_type->SetUINT32(MF_MT_MPEG2_LEVEL, h264_level);185
SetCodecUint32(CODECAPI_AVEncMPVLevel, h264_level);186
MFSetAttributeSize(out_type.Get(), MF_MT_FRAME_SIZE, width, height);187
MFSetAttributeRatio(out_type.Get(), MF_MT_FRAME_RATE, fps, 1);188
MFSetAttributeRatio(out_type.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);189
190
hr = mft_->SetOutputType(out_stream_id_, out_type.Get(), 0);191
if (FAILED(hr)) {192
RTC_LOG(LS_WARNING) << "MFH264: SetOutputType failed: 0x" << std::hex << hr;193
return false;194
}195
196
ComPtr<IMFMediaType> in_type;197
hr = MFCreateMediaType(&in_type);198
if (FAILED(hr)) {199
return false;200
}201
in_type->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Video);202
in_type->SetGUID(MF_MT_SUBTYPE, MFVideoFormat_NV12);203
in_type->SetUINT32(MF_MT_INTERLACE_MODE, MFVideoInterlace_Progressive);204
MFSetAttributeSize(in_type.Get(), MF_MT_FRAME_SIZE, width, height);205
MFSetAttributeRatio(in_type.Get(), MF_MT_FRAME_RATE, fps, 1);206
MFSetAttributeRatio(in_type.Get(), MF_MT_PIXEL_ASPECT_RATIO, 1, 1);207
208
hr = mft_->SetInputType(in_stream_id_, in_type.Get(), 0);209
if (FAILED(hr)) {210
RTC_LOG(LS_WARNING) << "MFH264: SetInputType(NV12) failed: 0x" << std::hex211
<< hr;212
return false;213
}214
215
MFT_OUTPUT_STREAM_INFO out_info = {};216
if (SUCCEEDED(mft_->GetOutputStreamInfo(out_stream_id_, &out_info))) {217
output_provides_samples_ =218
(out_info.dwFlags &219
(MFT_OUTPUT_STREAM_PROVIDES_SAMPLES |220
MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES)) != 0;221
}222
223
hr = mft_->ProcessMessage(MFT_MESSAGE_NOTIFY_BEGIN_STREAMING, 0);224
if (FAILED(hr)) {225
RTC_LOG(LS_WARNING) << "MFH264: BEGIN_STREAMING failed: 0x" << std::hex226
<< hr;227
return false;228
}229
hr = mft_->ProcessMessage(MFT_MESSAGE_NOTIFY_START_OF_STREAM, 0);230
if (FAILED(hr)) {231
RTC_LOG(LS_WARNING) << "MFH264: START_OF_STREAM failed: 0x" << std::hex232
<< hr;233
return false;234
}235
236
RTC_LOG(LS_INFO) << "MFH264: initialized " << width << "x" << height << " @"237
<< fps << "fps " << (bitrate_bps / 1000) << " kbps (async="238
<< (is_async_ ? "true" : "false") << ")";239
return true;240
}241
242
int32_t MFH264EncoderImpl::InitEncode(const VideoCodec* inst,243
const Settings& /*settings*/) {244
if (!inst || inst->codecType != kVideoCodecH264 || inst->width < 2 ||245
inst->height < 2) {246
return WEBRTC_VIDEO_CODEC_ERR_PARAMETER;247
}248
249
Release();250
251
HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);252
com_initialized_ = SUCCEEDED(hr_com);253
254
if (FAILED(MFStartup(MF_VERSION, MFSTARTUP_LITE))) {255
Release();256
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;257
}258
mf_started_ = true;259
260
width_ = inst->width;261
height_ = inst->height;262
max_fps_ = std::max<uint32_t>(inst->maxFramerate, 1);263
target_bps_ = std::max<uint32_t>(inst->startBitrate * 1000, 150000);264
frame_index_ = 0;265
sending_ = true;266
key_frame_request_ = true;267
async_need_input_ = 0;268
pending_meta_.clear();269
270
if (!ConfigureMft(width_, height_, max_fps_, target_bps_)) {271
Release();272
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;273
}274
275
initialized_ = true;276
return WEBRTC_VIDEO_CODEC_OK;277
}278
279
int32_t MFH264EncoderImpl::RegisterEncodeCompleteCallback(280
EncodedImageCallback* callback) {281
encoded_image_callback_ = callback;282
return WEBRTC_VIDEO_CODEC_OK;283
}284
285
int32_t MFH264EncoderImpl::Release() {286
if (mft_) {287
mft_->ProcessMessage(MFT_MESSAGE_NOTIFY_END_OF_STREAM, 0);288
mft_->ProcessMessage(MFT_MESSAGE_COMMAND_FLUSH, 0);289
}290
event_gen_.Reset();291
codec_api_.Reset();292
mft_.Reset();293
pending_meta_.clear();294
initialized_ = false;295
is_async_ = false;296
async_need_input_ = 0;297
298
if (mf_started_) {299
MFShutdown();300
mf_started_ = false;301
}302
if (com_initialized_) {303
CoUninitialize();304
com_initialized_ = false;305
}306
return WEBRTC_VIDEO_CODEC_OK;307
}308
309
void MFH264EncoderImpl::EmitEncodedBuffer(const uint8_t* data,310
size_t size,311
bool clean_point,312
LONGLONG sample_time) {313
if (!encoded_image_callback_ || !data || size == 0) {314
return;315
}316
317
PendingFrameMeta meta = {0, 0, std::nullopt};318
auto matched = pending_meta_.find(sample_time);319
if (matched != pending_meta_.end()) {320
meta = matched->second;321
}322
// Drop this sample and any older unmatched input. A dropped MFT frame must323
// not shift the RTP timestamp of every later frame.324
if (sample_time >= 0) {325
auto end = pending_meta_.upper_bound(sample_time);326
pending_meta_.erase(pending_meta_.begin(), end);327
}328
329
const bool is_key = clean_point || ContainsIdrNal(data, size);330
331
encoded_image_.SetEncodedData(EncodedImageBuffer::Create(data, size));332
h264_bitstream_parser_.ParseBitstream(encoded_image_);333
encoded_image_.qp_ = h264_bitstream_parser_.GetLastSliceQp().value_or(-1);334
encoded_image_._encodedWidth = width_;335
encoded_image_._encodedHeight = height_;336
encoded_image_.SetRtpTimestamp(meta.rtp_timestamp);337
encoded_image_.capture_time_ms_ = meta.capture_time_ms;338
encoded_image_.SetColorSpace(meta.color_space);339
encoded_image_._frameType =340
is_key ? VideoFrameType::kVideoFrameKey : VideoFrameType::kVideoFrameDelta;341
342
CodecSpecificInfo codec_specific;343
codec_specific.codecType = kVideoCodecH264;344
codec_specific.codecSpecific.H264.packetization_mode = packetization_mode_;345
codec_specific.codecSpecific.H264.temporal_idx = kNoTemporalIdx;346
codec_specific.codecSpecific.H264.base_layer_sync = false;347
codec_specific.codecSpecific.H264.idr_frame = is_key;348
349
encoded_image_callback_->OnEncodedImage(encoded_image_, &codec_specific);350
}351
352
bool MFH264EncoderImpl::ProcessOneOutputSample() {353
MFT_OUTPUT_DATA_BUFFER out_buf = {};354
out_buf.dwStreamID = out_stream_id_;355
ComPtr<IMFSample> owned_sample;356
357
if (!output_provides_samples_) {358
MFT_OUTPUT_STREAM_INFO info = {};359
if (FAILED(mft_->GetOutputStreamInfo(out_stream_id_, &info))) {360
return false;361
}362
DWORD alloc_size = std::max<DWORD>(info.cbSize, width_ * height_ * 3 / 2);363
ComPtr<IMFMediaBuffer> buf;364
if (FAILED(MFCreateMemoryBuffer(alloc_size, &buf)) ||365
FAILED(MFCreateSample(&owned_sample))) {366
return false;367
}368
owned_sample->AddBuffer(buf.Get());369
out_buf.pSample = owned_sample.Get();370
}371
372
DWORD status = 0;373
HRESULT hr = mft_->ProcessOutput(0, 1, &out_buf, &status);374
375
if (out_buf.pEvents) {376
out_buf.pEvents->Release();377
out_buf.pEvents = nullptr;378
}379
380
if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {381
ComPtr<IMFMediaType> new_type;382
if (SUCCEEDED(mft_->GetOutputAvailableType(out_stream_id_, 0, &new_type))) {383
mft_->SetOutputType(out_stream_id_, new_type.Get(), 0);384
}385
return true;386
}387
388
if (FAILED(hr) || !out_buf.pSample) {389
return false;390
}391
392
ComPtr<IMFSample> sample;393
if (output_provides_samples_) {394
sample.Attach(out_buf.pSample);395
} else {396
sample = owned_sample;397
}398
399
UINT32 clean_point = 0;400
sample->GetUINT32(MFSampleExtension_CleanPoint, &clean_point);401
LONGLONG sample_time = -1;402
sample->GetSampleTime(&sample_time);403
404
ComPtr<IMFMediaBuffer> contiguous;405
if (SUCCEEDED(sample->ConvertToContiguousBuffer(&contiguous)) && contiguous) {406
BYTE* ptr = nullptr;407
DWORD cur_len = 0;408
if (SUCCEEDED(contiguous->Lock(&ptr, nullptr, &cur_len)) && ptr &&409
cur_len > 0) {410
EmitEncodedBuffer(ptr, cur_len, clean_point != 0, sample_time);411
contiguous->Unlock();412
}413
}414
return true;415
}416
417
bool MFH264EncoderImpl::DrainSyncOutput() {418
for (;;) {419
MFT_OUTPUT_DATA_BUFFER out_buf = {};420
out_buf.dwStreamID = out_stream_id_;421
ComPtr<IMFSample> owned_sample;422
423
if (!output_provides_samples_) {424
MFT_OUTPUT_STREAM_INFO info = {};425
if (FAILED(mft_->GetOutputStreamInfo(out_stream_id_, &info))) {426
return false;427
}428
DWORD alloc_size = std::max<DWORD>(info.cbSize, width_ * height_ * 3 / 2);429
ComPtr<IMFMediaBuffer> buf;430
if (FAILED(MFCreateMemoryBuffer(alloc_size, &buf)) ||431
FAILED(MFCreateSample(&owned_sample))) {432
return false;433
}434
owned_sample->AddBuffer(buf.Get());435
out_buf.pSample = owned_sample.Get();436
}437
438
DWORD status = 0;439
HRESULT hr = mft_->ProcessOutput(0, 1, &out_buf, &status);440
if (out_buf.pEvents) {441
out_buf.pEvents->Release();442
out_buf.pEvents = nullptr;443
}444
if (hr == MF_E_TRANSFORM_NEED_MORE_INPUT) {445
return true;446
}447
if (hr == MF_E_TRANSFORM_STREAM_CHANGE) {448
ComPtr<IMFMediaType> new_type;449
if (SUCCEEDED(450
mft_->GetOutputAvailableType(out_stream_id_, 0, &new_type))) {451
mft_->SetOutputType(out_stream_id_, new_type.Get(), 0);452
}453
continue;454
}455
if (FAILED(hr) || !out_buf.pSample) {456
return false;457
}458
459
ComPtr<IMFSample> sample;460
if (output_provides_samples_) {461
sample.Attach(out_buf.pSample);462
} else {463
sample = owned_sample;464
}465
466
UINT32 clean_point = 0;467
sample->GetUINT32(MFSampleExtension_CleanPoint, &clean_point);468
LONGLONG sample_time = -1;469
sample->GetSampleTime(&sample_time);470
471
ComPtr<IMFMediaBuffer> contiguous;472
if (SUCCEEDED(sample->ConvertToContiguousBuffer(&contiguous)) &&473
contiguous) {474
BYTE* ptr = nullptr;475
DWORD cur_len = 0;476
if (SUCCEEDED(contiguous->Lock(&ptr, nullptr, &cur_len)) && ptr &&477
cur_len > 0) {478
EmitEncodedBuffer(ptr, cur_len, clean_point != 0, sample_time);479
contiguous->Unlock();480
}481
}482
}483
}484
485
bool MFH264EncoderImpl::PumpAsyncUntilInputNeeded() {486
const auto deadline =487
std::chrono::steady_clock::now() + std::chrono::milliseconds(200);488
while (async_need_input_ <= 0) {489
if (std::chrono::steady_clock::now() >= deadline) {490
RTC_LOG(LS_WARNING)491
<< "MFH264: async MFT sent no input event within 200 ms";492
return false;493
}494
ComPtr<IMFMediaEvent> event;495
HRESULT hr = event_gen_->GetEvent(MF_EVENT_FLAG_NO_WAIT, &event);496
if (hr == MF_E_NO_EVENTS_AVAILABLE) {497
Sleep(1);498
continue;499
}500
if (FAILED(hr) || !event) {501
return false;502
}503
MediaEventType type = MEUnknown;504
event->GetType(&type);505
if (type == METransformNeedInput) {506
++async_need_input_;507
} else if (type == METransformHaveOutput) {508
if (!ProcessOneOutputSample()) {509
return false;510
}511
}512
}513
return async_need_input_ > 0;514
}515
516
bool MFH264EncoderImpl::DrainAsyncReadyOutputs() {517
for (int attempts = 0; attempts < 16; ++attempts) {518
ComPtr<IMFMediaEvent> event;519
HRESULT hr = event_gen_->GetEvent(MF_EVENT_FLAG_NO_WAIT, &event);520
if (hr == MF_E_NO_EVENTS_AVAILABLE) {521
return true;522
}523
if (FAILED(hr) || !event) {524
return false;525
}526
MediaEventType type = MEUnknown;527
event->GetType(&type);528
if (type == METransformNeedInput) {529
++async_need_input_;530
} else if (type == METransformHaveOutput) {531
if (!ProcessOneOutputSample()) {532
return false;533
}534
}535
}536
return true;537
}538
539
int32_t MFH264EncoderImpl::Encode(540
const VideoFrame& input_frame,541
const std::vector<VideoFrameType>* frame_types) {542
if (!initialized_ || !mft_ || !encoded_image_callback_) {543
return WEBRTC_VIDEO_CODEC_UNINITIALIZED;544
}545
if (!sending_) {546
return WEBRTC_VIDEO_CODEC_NO_OUTPUT;547
}548
if (frame_types && !frame_types->empty() &&549
(*frame_types)[0] == VideoFrameType::kEmptyFrame) {550
return WEBRTC_VIDEO_CODEC_NO_OUTPUT;551
}552
553
webrtc::scoped_refptr<I420BufferInterface> i420 =554
input_frame.video_frame_buffer()->ToI420();555
if (!i420) {556
return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;557
}558
559
if (static_cast<uint32_t>(i420->width()) != width_ ||560
static_cast<uint32_t>(i420->height()) != height_) {561
// Resolution changed dynamically: re-init MFT or fall back cleanly.562
width_ = static_cast<uint32_t>(i420->width());563
height_ = static_cast<uint32_t>(i420->height());564
mft_.Reset();565
codec_api_.Reset();566
event_gen_.Reset();567
is_async_ = false;568
async_need_input_ = 0;569
pending_meta_.clear();570
if (!ConfigureMft(width_, height_, max_fps_, target_bps_)) {571
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;572
}573
key_frame_request_ = true;574
}575
576
const bool send_key_frame =577
key_frame_request_ ||578
(frame_types && !frame_types->empty() &&579
(*frame_types)[0] == VideoFrameType::kVideoFrameKey);580
if (send_key_frame) {581
key_frame_request_ = false;582
SetCodecUint32(CODECAPI_AVEncVideoForceKeyFrame, 1);583
}584
585
const uint32_t nv12_size = width_ * height_ * 3 / 2;586
ComPtr<IMFMediaBuffer> in_buffer;587
ComPtr<IMFSample> in_sample;588
if (FAILED(MFCreateMemoryBuffer(nv12_size, &in_buffer)) ||589
FAILED(MFCreateSample(&in_sample))) {590
return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;591
}592
593
BYTE* dst = nullptr;594
if (FAILED(in_buffer->Lock(&dst, nullptr, nullptr)) || !dst) {595
return WEBRTC_VIDEO_CODEC_ENCODER_FAILURE;596
}597
uint8_t* dst_y = dst;598
uint8_t* dst_uv = dst + width_ * height_;599
libyuv::I420ToNV12(i420->DataY(), i420->StrideY(), i420->DataU(),600
i420->StrideU(), i420->DataV(), i420->StrideV(), dst_y,601
static_cast<int>(width_), dst_uv,602
static_cast<int>(width_), static_cast<int>(width_),603
static_cast<int>(height_));604
in_buffer->Unlock();605
in_buffer->SetCurrentLength(nv12_size);606
in_sample->AddBuffer(in_buffer.Get());607
608
const LONGLONG duration_100ns = 10000000LL / std::max<uint32_t>(max_fps_, 1);609
const LONGLONG sample_time = frame_index_ * duration_100ns;610
in_sample->SetSampleTime(sample_time);611
in_sample->SetSampleDuration(duration_100ns);612
++frame_index_;613
614
pending_meta_[sample_time] = PendingFrameMeta{615
input_frame.rtp_timestamp(),616
input_frame.render_time_ms(),617
input_frame.color_space(),618
};619
620
if (is_async_) {621
if (!PumpAsyncUntilInputNeeded()) {622
pending_meta_.erase(sample_time);623
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;624
}625
--async_need_input_;626
HRESULT hr = mft_->ProcessInput(in_stream_id_, in_sample.Get(), 0);627
if (FAILED(hr)) {628
pending_meta_.erase(sample_time);629
RTC_LOG(LS_WARNING) << "MFH264: async ProcessInput failed: 0x" << std::hex630
<< hr;631
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;632
}633
if (!DrainAsyncReadyOutputs()) {634
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;635
}636
} else {637
HRESULT hr = mft_->ProcessInput(in_stream_id_, in_sample.Get(), 0);638
if (FAILED(hr)) {639
pending_meta_.erase(sample_time);640
RTC_LOG(LS_WARNING) << "MFH264: sync ProcessInput failed: 0x" << std::hex641
<< hr;642
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;643
}644
if (!DrainSyncOutput()) {645
return WEBRTC_VIDEO_CODEC_FALLBACK_SOFTWARE;646
}647
}648
649
return WEBRTC_VIDEO_CODEC_OK;650
}651
652
void MFH264EncoderImpl::SetRates(const RateControlParameters& parameters) {653
if (!initialized_) {654
return;655
}656
if (parameters.bitrate.get_sum_bps() == 0) {657
sending_ = false;658
return;659
}660
const uint32_t new_bps =661
std::max<uint32_t>(parameters.bitrate.GetSpatialLayerSum(0), 100000);662
if (!sending_) {663
sending_ = true;664
key_frame_request_ = true;665
}666
if (parameters.framerate_fps >= 1.0) {667
max_fps_ = static_cast<uint32_t>(parameters.framerate_fps);668
}669
if (new_bps != target_bps_) {670
target_bps_ = new_bps;671
SetCodecUint32(CODECAPI_AVEncCommonMeanBitRate, target_bps_);672
}673
}674
675
VideoEncoder::EncoderInfo MFH264EncoderImpl::GetEncoderInfo() const {676
EncoderInfo info;677
info.supports_native_handle = false;678
info.implementation_name = "MediaFoundation H264";679
info.scaling_settings = VideoEncoder::ScalingSettings::kOff;680
info.is_hardware_accelerated = true;681
info.supports_simulcast = false;682
info.preferred_pixel_formats = {VideoFrameBuffer::Type::kI420};683
return info;684
}685
686
} // namespace webrtc@@ -0,0 +1,105 @@
1
#ifndef MF_H264_ENCODER_IMPL_H_
2
#define MF_H264_ENCODER_IMPL_H_
3
4
#ifndef NOMINMAX
5
#define NOMINMAX
6
#endif
7
#include <windows.h>
8
#include <codecapi.h>
9
#include <mfapi.h>
10
#include <mfidl.h>
11
#include <mftransform.h>
12
#include <strmif.h>
13
#include <wrl/client.h>
14
15
#include <cstdint>
16
#include <map>
17
#include <optional>
18
#include <vector>
19
20
#include "api/environment/environment.h"
21
#include "api/video/encoded_image.h"
22
#include "api/video_codecs/sdp_video_format.h"
23
#include "api/video_codecs/video_encoder.h"
24
#include "common_video/h264/h264_bitstream_parser.h"
25
#include "modules/video_coding/codecs/h264/include/h264.h"
26
27
namespace webrtc {
28
29
class MFH264EncoderImpl : public VideoEncoder {
30
public:
31
MFH264EncoderImpl(const Environment& env, const SdpVideoFormat& format);
32
~MFH264EncoderImpl() override;
33
34
int32_t InitEncode(const VideoCodec* codec_settings,
35
const Settings& settings) override;
36
37
int32_t RegisterEncodeCompleteCallback(
38
EncodedImageCallback* callback) override;
39
40
int32_t Release() override;
41
42
int32_t Encode(const VideoFrame& frame,
43
const std::vector<VideoFrameType>* frame_types) override;
44
45
void SetRates(const RateControlParameters& parameters) override;
46
47
EncoderInfo GetEncoderInfo() const override;
48
49
private:
50
struct PendingFrameMeta {
51
uint32_t rtp_timestamp;
52
int64_t capture_time_ms;
53
std::optional<ColorSpace> color_space;
54
};
55
56
bool ConfigureMft(uint32_t width,
57
uint32_t height,
58
uint32_t fps,
59
uint32_t bitrate_bps);
60
bool DrainSyncOutput();
61
bool PumpAsyncUntilInputNeeded();
62
bool DrainAsyncReadyOutputs();
63
bool ProcessOneOutputSample();
64
void EmitEncodedBuffer(const uint8_t* data,
65
size_t size,
66
bool clean_point,
67
LONGLONG sample_time);
68
void SetCodecUint32(const GUID& key, uint32_t value);
69
void SetCodecBool(const GUID& key, bool value);
70
71
const Environment env_;
72
const SdpVideoFormat format_;
73
EncodedImageCallback* encoded_image_callback_ = nullptr;
74
H264PacketizationMode packetization_mode_ =
75
H264PacketizationMode::NonInterleaved;
76
H264BitstreamParser h264_bitstream_parser_;
77
EncodedImage encoded_image_;
78
79
bool com_initialized_ = false;
80
bool mf_started_ = false;
81
bool initialized_ = false;
82
bool is_async_ = false;
83
bool sending_ = true;
84
bool key_frame_request_ = false;
85
bool output_provides_samples_ = false;
86
87
DWORD in_stream_id_ = 0;
88
DWORD out_stream_id_ = 0;
89
uint32_t width_ = 0;
90
uint32_t height_ = 0;
91
uint32_t max_fps_ = 30;
92
uint32_t target_bps_ = 1000000;
93
int64_t frame_index_ = 0;
94
int async_need_input_ = 0;
95
96
Microsoft::WRL::ComPtr<IMFTransform> mft_;
97
Microsoft::WRL::ComPtr<ICodecAPI> codec_api_;
98
Microsoft::WRL::ComPtr<IMFMediaEventGenerator> event_gen_;
99
100
std::map<LONGLONG, PendingFrameMeta> pending_meta_;
101
};
102
103
} // namespace webrtc
104
105
#endif // MF_H264_ENCODER_IMPL_H_
@@ -0,0 +1,105 @@1
#ifndef MF_H264_ENCODER_IMPL_H_2
#define MF_H264_ENCODER_IMPL_H_3
4
#ifndef NOMINMAX5
#define NOMINMAX6
#endif7
#include <windows.h>8
#include <codecapi.h>9
#include <mfapi.h>10
#include <mfidl.h>11
#include <mftransform.h>12
#include <strmif.h>13
#include <wrl/client.h>14
15
#include <cstdint>16
#include <map>17
#include <optional>18
#include <vector>19
20
#include "api/environment/environment.h"21
#include "api/video/encoded_image.h"22
#include "api/video_codecs/sdp_video_format.h"23
#include "api/video_codecs/video_encoder.h"24
#include "common_video/h264/h264_bitstream_parser.h"25
#include "modules/video_coding/codecs/h264/include/h264.h"26
27
namespace webrtc {28
29
class MFH264EncoderImpl : public VideoEncoder {30
public:31
MFH264EncoderImpl(const Environment& env, const SdpVideoFormat& format);32
~MFH264EncoderImpl() override;33
34
int32_t InitEncode(const VideoCodec* codec_settings,35
const Settings& settings) override;36
37
int32_t RegisterEncodeCompleteCallback(38
EncodedImageCallback* callback) override;39
40
int32_t Release() override;41
42
int32_t Encode(const VideoFrame& frame,43
const std::vector<VideoFrameType>* frame_types) override;44
45
void SetRates(const RateControlParameters& parameters) override;46
47
EncoderInfo GetEncoderInfo() const override;48
49
private:50
struct PendingFrameMeta {51
uint32_t rtp_timestamp;52
int64_t capture_time_ms;53
std::optional<ColorSpace> color_space;54
};55
56
bool ConfigureMft(uint32_t width,57
uint32_t height,58
uint32_t fps,59
uint32_t bitrate_bps);60
bool DrainSyncOutput();61
bool PumpAsyncUntilInputNeeded();62
bool DrainAsyncReadyOutputs();63
bool ProcessOneOutputSample();64
void EmitEncodedBuffer(const uint8_t* data,65
size_t size,66
bool clean_point,67
LONGLONG sample_time);68
void SetCodecUint32(const GUID& key, uint32_t value);69
void SetCodecBool(const GUID& key, bool value);70
71
const Environment env_;72
const SdpVideoFormat format_;73
EncodedImageCallback* encoded_image_callback_ = nullptr;74
H264PacketizationMode packetization_mode_ =75
H264PacketizationMode::NonInterleaved;76
H264BitstreamParser h264_bitstream_parser_;77
EncodedImage encoded_image_;78
79
bool com_initialized_ = false;80
bool mf_started_ = false;81
bool initialized_ = false;82
bool is_async_ = false;83
bool sending_ = true;84
bool key_frame_request_ = false;85
bool output_provides_samples_ = false;86
87
DWORD in_stream_id_ = 0;88
DWORD out_stream_id_ = 0;89
uint32_t width_ = 0;90
uint32_t height_ = 0;91
uint32_t max_fps_ = 30;92
uint32_t target_bps_ = 1000000;93
int64_t frame_index_ = 0;94
int async_need_input_ = 0;95
96
Microsoft::WRL::ComPtr<IMFTransform> mft_;97
Microsoft::WRL::ComPtr<ICodecAPI> codec_api_;98
Microsoft::WRL::ComPtr<IMFMediaEventGenerator> event_gen_;99
100
std::map<LONGLONG, PendingFrameMeta> pending_meta_;101
};102
103
} // namespace webrtc104
105
#endif // MF_H264_ENCODER_IMPL_H_@@ -249,11 +249,18 @@ std::shared_ptr<AudioTrack> PeerConnectionFactory::create_audio_track(
249
249
250
250
std::shared_ptr<AudioTrack> PeerConnectionFactory::create_device_audio_track(
251
251
rust::String label) const {
252
return create_device_audio_track_with_options(std::move(label), true);
253
}
254
255
std::shared_ptr<AudioTrack>
256
PeerConnectionFactory::create_device_audio_track_with_options(
257
rust::String label,
258
bool noise_suppression) const {
252
259
// Create an audio source that uses the ADM for capture
253
260
webrtc::AudioOptions audio_options;
254
261
audio_options.echo_cancellation = true;
255
262
audio_options.auto_gain_control = true;
256
audio_options.noise_suppression = true;
263
audio_options.noise_suppression = noise_suppression;
257
264
258
265
webrtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source =
259
266
peer_factory_->CreateAudioSource(audio_options);
@@ -249,11 +249,18 @@ std::shared_ptr<AudioTrack> PeerConnectionFactory::create_audio_track(249
249
250
std::shared_ptr<AudioTrack> PeerConnectionFactory::create_device_audio_track(250
std::shared_ptr<AudioTrack> PeerConnectionFactory::create_device_audio_track(251
rust::String label) const {251
rust::String label) const {252
return create_device_audio_track_with_options(std::move(label), true);253
}254
255
std::shared_ptr<AudioTrack>256
PeerConnectionFactory::create_device_audio_track_with_options(257
rust::String label,258
bool noise_suppression) const {252
// Create an audio source that uses the ADM for capture259
// Create an audio source that uses the ADM for capture253
webrtc::AudioOptions audio_options;260
webrtc::AudioOptions audio_options;254
audio_options.echo_cancellation = true;261
audio_options.echo_cancellation = true;255
audio_options.auto_gain_control = true;262
audio_options.auto_gain_control = true;256
audio_options.noise_suppression = true;263
audio_options.noise_suppression = noise_suppression;257
264
258
webrtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source =265
webrtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source =259
peer_factory_->CreateAudioSource(audio_options);266
peer_factory_->CreateAudioSource(audio_options);@@ -121,6 +121,12 @@ pub mod ffi {
121
121
label: String,
122
122
) -> SharedPtr<AudioTrack>;
123
123
124
fn create_device_audio_track_with_options(
125
self: &PeerConnectionFactory,
126
label: String,
127
noise_suppression: bool,
128
) -> SharedPtr<AudioTrack>;
129
124
130
fn rtp_sender_capabilities(
125
131
self: &PeerConnectionFactory,
126
132
kind: MediaType,
@@ -121,6 +121,12 @@ pub mod ffi {121
label: String,121
label: String,122
) -> SharedPtr<AudioTrack>;122
) -> SharedPtr<AudioTrack>;123
123
124
fn create_device_audio_track_with_options(125
self: &PeerConnectionFactory,126
label: String,127
noise_suppression: bool,128
) -> SharedPtr<AudioTrack>;129
124
fn rtp_sender_capabilities(130
fn rtp_sender_capabilities(125
self: &PeerConnectionFactory,131
self: &PeerConnectionFactory,126
kind: MediaType,132
kind: MediaType,@@ -64,6 +64,10 @@
64
64
#include "jetson/jetson_encoder_factory.h"
65
65
#endif
66
66
67
#if defined(USE_MF_VIDEO_CODEC)
68
#include "mf/mf_encoder_factory.h"
69
#endif
70
67
71
namespace livekit_ffi {
68
72
69
73
namespace {
@@ -340,6 +344,12 @@ rust::Vec<VideoEncoderBackend> video_encoder_backend_list() {
340
344
}
341
345
#endif
342
346
347
#if defined(USE_MF_VIDEO_CODEC)
348
if (webrtc::MFVideoEncoderFactory::IsSupported()) {
349
has_hardware_backend = true;
350
}
351
#endif
352
343
353
if (has_hardware_backend && !hardware_backend_listed) {
344
354
backends.push_back(VideoEncoderBackend::Hardware);
345
355
}
@@ -378,6 +388,15 @@ VideoEncoderFactory::InternalFactory::InternalFactory() {
378
388
AddNvencFactory(factories_, preferred_hw_encoder.explicitly_set);
379
389
AddVaapiFactory(factories_, false);
380
390
}
391
392
#if defined(USE_MF_VIDEO_CODEC)
393
if (webrtc::MFVideoEncoderFactory::IsSupported()) {
394
AddBackendFactory(
395
factories_,
396
VideoEncoderBackend::Hardware,
397
std::make_unique<webrtc::MFVideoEncoderFactory>());
398
}
399
#endif
381
400
}
382
401
383
402
std::vector<webrtc::SdpVideoFormat>
@@ -64,6 +64,10 @@64
#include "jetson/jetson_encoder_factory.h"64
#include "jetson/jetson_encoder_factory.h"65
#endif65
#endif66
66
67
#if defined(USE_MF_VIDEO_CODEC)68
#include "mf/mf_encoder_factory.h"69
#endif70
67
namespace livekit_ffi {71
namespace livekit_ffi {68
72
69
namespace {73
namespace {@@ -340,6 +344,12 @@ rust::Vec<VideoEncoderBackend> video_encoder_backend_list() {340
}344
}341
#endif345
#endif342
346
347
#if defined(USE_MF_VIDEO_CODEC)348
if (webrtc::MFVideoEncoderFactory::IsSupported()) {349
has_hardware_backend = true;350
}351
#endif352
343
if (has_hardware_backend && !hardware_backend_listed) {353
if (has_hardware_backend && !hardware_backend_listed) {344
backends.push_back(VideoEncoderBackend::Hardware);354
backends.push_back(VideoEncoderBackend::Hardware);345
}355
}@@ -378,6 +388,15 @@ VideoEncoderFactory::InternalFactory::InternalFactory() {378
AddNvencFactory(factories_, preferred_hw_encoder.explicitly_set);388
AddNvencFactory(factories_, preferred_hw_encoder.explicitly_set);379
AddVaapiFactory(factories_, false);389
AddVaapiFactory(factories_, false);380
}390
}391
392
#if defined(USE_MF_VIDEO_CODEC)393
if (webrtc::MFVideoEncoderFactory::IsSupported()) {394
AddBackendFactory(395
factories_,396
VideoEncoderBackend::Hardware,397
std::make_unique<webrtc::MFVideoEncoderFactory>());398
}399
#endif381
}400
}382
401
383
std::vector<webrtc::SdpVideoFormat>402
std::vector<webrtc::SdpVideoFormat>@@ -31,6 +31,15 @@
31
31
#include "rtc_base/synchronization/mutex.h"
32
32
33
33
#ifdef WEBRTC_WIN
34
#ifndef NOMINMAX
35
#define NOMINMAX
36
#endif
37
#include <windows.h>
38
#include <dshow.h>
39
#include <ks.h>
40
#include <ksmedia.h>
41
#include <wrl/client.h>
42
34
43
#include "rtc_base/win32.h"
35
44
#endif
36
45
@@ -181,4 +190,140 @@ rust::String create_random_uuid() {
181
190
return webrtc::CreateRandomUuid();
182
191
}
183
192
193
void tune_windows_camera(rust::Str target) {
194
#ifdef WEBRTC_WIN
195
if (target.empty()) {
196
return;
197
}
198
using Microsoft::WRL::ComPtr;
199
200
static const GUID kPropSetVidCapVideoProcAmp = {
201
0xC6E13360,
202
0x30AC,
203
0x11d0,
204
{0xA1, 0x8C, 0x00, 0xA0, 0xC9, 0x11, 0x89, 0x56}};
205
static const GUID kPropSetVidCapCameraControl = {
206
0xC6E13370,
207
0x30AC,
208
0x11d0,
209
{0xA1, 0x8C, 0x00, 0xA0, 0xC9, 0x11, 0x89, 0x56}};
210
211
std::wstring wanted;
212
if (!target.empty()) {
213
int wide_len = MultiByteToWideChar(CP_UTF8, 0, target.data(),
214
static_cast<int>(target.size()), nullptr,
215
0);
216
if (wide_len > 0) {
217
wanted.resize(wide_len);
218
MultiByteToWideChar(CP_UTF8, 0, target.data(),
219
static_cast<int>(target.size()), wanted.data(),
220
wide_len);
221
}
222
}
223
auto to_lower = [](std::wstring text) {
224
for (wchar_t& ch : text) {
225
if (ch >= L'A' && ch <= L'Z') {
226
ch = static_cast<wchar_t>(ch - L'A' + L'a');
227
}
228
}
229
return text;
230
};
231
const std::wstring wanted_lower = to_lower(wanted);
232
if (wanted_lower.empty()) {
233
return;
234
}
235
236
HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);
237
const bool com_owned = SUCCEEDED(hr_com);
238
239
ComPtr<ICreateDevEnum> dev_enum;
240
if (SUCCEEDED(CoCreateInstance(CLSID_SystemDeviceEnum, nullptr,
241
CLSCTX_INPROC_SERVER,
242
IID_PPV_ARGS(&dev_enum))) &&
243
dev_enum) {
244
ComPtr<IEnumMoniker> enum_moniker;
245
if (SUCCEEDED(dev_enum->CreateClassEnumerator(
246
CLSID_VideoInputDeviceCategory, &enum_moniker, 0)) &&
247
enum_moniker) {
248
ComPtr<IMoniker> moniker;
249
ULONG fetched = 0;
250
while (enum_moniker->Next(1, &moniker, &fetched) == S_OK && moniker) {
251
bool matches = false;
252
if (!matches) {
253
ComPtr<IPropertyBag> bag;
254
if (SUCCEEDED(moniker->BindToStorage(nullptr, nullptr,
255
IID_PPV_ARGS(&bag))) &&
256
bag) {
257
for (const wchar_t* prop : {L"DevicePath", L"FriendlyName"}) {
258
VARIANT var;
259
VariantInit(&var);
260
if (SUCCEEDED(bag->Read(prop, &var, nullptr)) &&
261
var.vt == VT_BSTR && var.bstrVal) {
262
std::wstring value_lower = to_lower(var.bstrVal);
263
if (value_lower == wanted_lower ||
264
value_lower.find(wanted_lower) != std::wstring::npos ||
265
wanted_lower.find(value_lower) != std::wstring::npos) {
266
matches = true;
267
}
268
}
269
VariantClear(&var);
270
if (matches) {
271
break;
272
}
273
}
274
}
275
}
276
277
if (matches) {
278
ComPtr<IBaseFilter> filter;
279
if (SUCCEEDED(moniker->BindToObject(nullptr, nullptr,
280
IID_PPV_ARGS(&filter))) &&
281
filter) {
282
ComPtr<IKsPropertySet> ks;
283
if (SUCCEEDED(filter.As(&ks)) && ks) {
284
// 50 Hz anti-flicker (power line frequency = 1)
285
KSPROPERTY_VIDEOPROCAMP_S powerline = {};
286
powerline.Property.Set = kPropSetVidCapVideoProcAmp;
287
powerline.Property.Id =
288
KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY;
289
powerline.Property.Flags = KSPROPERTY_TYPE_SET;
290
powerline.Value = 1;
291
powerline.Flags = KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL;
292
ks->Set(kPropSetVidCapVideoProcAmp,
293
KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY,
294
&powerline.Value,
295
sizeof(powerline) - sizeof(KSPROPERTY), &powerline,
296
sizeof(powerline));
297
298
// Disable low-light auto-exposure frame-rate drop
299
KSPROPERTY_CAMERACONTROL_S priority = {};
300
priority.Property.Set = kPropSetVidCapCameraControl;
301
priority.Property.Id =
302
KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY;
303
priority.Property.Flags = KSPROPERTY_TYPE_SET;
304
priority.Value = 0;
305
priority.Flags = KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL;
306
ks->Set(kPropSetVidCapCameraControl,
307
KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY,
308
&priority.Value,
309
sizeof(priority) - sizeof(KSPROPERTY), &priority,
310
sizeof(priority));
311
}
312
}
313
moniker.Reset();
314
break;
315
}
316
moniker.Reset();
317
}
318
}
319
}
320
321
if (com_owned) {
322
CoUninitialize();
323
}
324
#else
325
(void)target;
326
#endif
327
}
328
184
329
} // namespace livekit_ffi
@@ -31,6 +31,15 @@31
#include "rtc_base/synchronization/mutex.h"31
#include "rtc_base/synchronization/mutex.h"32
32
33
#ifdef WEBRTC_WIN33
#ifdef WEBRTC_WIN34
#ifndef NOMINMAX35
#define NOMINMAX36
#endif37
#include <windows.h>38
#include <dshow.h>39
#include <ks.h>40
#include <ksmedia.h>41
#include <wrl/client.h>42
34
#include "rtc_base/win32.h"43
#include "rtc_base/win32.h"35
#endif44
#endif36
45
@@ -181,4 +190,140 @@ rust::String create_random_uuid() {181
return webrtc::CreateRandomUuid();190
return webrtc::CreateRandomUuid();182
}191
}183
192
193
void tune_windows_camera(rust::Str target) {194
#ifdef WEBRTC_WIN195
if (target.empty()) {196
return;197
}198
using Microsoft::WRL::ComPtr;199
200
static const GUID kPropSetVidCapVideoProcAmp = {201
0xC6E13360,202
0x30AC,203
0x11d0,204
{0xA1, 0x8C, 0x00, 0xA0, 0xC9, 0x11, 0x89, 0x56}};205
static const GUID kPropSetVidCapCameraControl = {206
0xC6E13370,207
0x30AC,208
0x11d0,209
{0xA1, 0x8C, 0x00, 0xA0, 0xC9, 0x11, 0x89, 0x56}};210
211
std::wstring wanted;212
if (!target.empty()) {213
int wide_len = MultiByteToWideChar(CP_UTF8, 0, target.data(),214
static_cast<int>(target.size()), nullptr,215
0);216
if (wide_len > 0) {217
wanted.resize(wide_len);218
MultiByteToWideChar(CP_UTF8, 0, target.data(),219
static_cast<int>(target.size()), wanted.data(),220
wide_len);221
}222
}223
auto to_lower = [](std::wstring text) {224
for (wchar_t& ch : text) {225
if (ch >= L'A' && ch <= L'Z') {226
ch = static_cast<wchar_t>(ch - L'A' + L'a');227
}228
}229
return text;230
};231
const std::wstring wanted_lower = to_lower(wanted);232
if (wanted_lower.empty()) {233
return;234
}235
236
HRESULT hr_com = CoInitializeEx(nullptr, COINIT_MULTITHREADED);237
const bool com_owned = SUCCEEDED(hr_com);238
239
ComPtr<ICreateDevEnum> dev_enum;240
if (SUCCEEDED(CoCreateInstance(CLSID_SystemDeviceEnum, nullptr,241
CLSCTX_INPROC_SERVER,242
IID_PPV_ARGS(&dev_enum))) &&243
dev_enum) {244
ComPtr<IEnumMoniker> enum_moniker;245
if (SUCCEEDED(dev_enum->CreateClassEnumerator(246
CLSID_VideoInputDeviceCategory, &enum_moniker, 0)) &&247
enum_moniker) {248
ComPtr<IMoniker> moniker;249
ULONG fetched = 0;250
while (enum_moniker->Next(1, &moniker, &fetched) == S_OK && moniker) {251
bool matches = false;252
if (!matches) {253
ComPtr<IPropertyBag> bag;254
if (SUCCEEDED(moniker->BindToStorage(nullptr, nullptr,255
IID_PPV_ARGS(&bag))) &&256
bag) {257
for (const wchar_t* prop : {L"DevicePath", L"FriendlyName"}) {258
VARIANT var;259
VariantInit(&var);260
if (SUCCEEDED(bag->Read(prop, &var, nullptr)) &&261
var.vt == VT_BSTR && var.bstrVal) {262
std::wstring value_lower = to_lower(var.bstrVal);263
if (value_lower == wanted_lower ||264
value_lower.find(wanted_lower) != std::wstring::npos ||265
wanted_lower.find(value_lower) != std::wstring::npos) {266
matches = true;267
}268
}269
VariantClear(&var);270
if (matches) {271
break;272
}273
}274
}275
}276
277
if (matches) {278
ComPtr<IBaseFilter> filter;279
if (SUCCEEDED(moniker->BindToObject(nullptr, nullptr,280
IID_PPV_ARGS(&filter))) &&281
filter) {282
ComPtr<IKsPropertySet> ks;283
if (SUCCEEDED(filter.As(&ks)) && ks) {284
// 50 Hz anti-flicker (power line frequency = 1)285
KSPROPERTY_VIDEOPROCAMP_S powerline = {};286
powerline.Property.Set = kPropSetVidCapVideoProcAmp;287
powerline.Property.Id =288
KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY;289
powerline.Property.Flags = KSPROPERTY_TYPE_SET;290
powerline.Value = 1;291
powerline.Flags = KSPROPERTY_VIDEOPROCAMP_FLAGS_MANUAL;292
ks->Set(kPropSetVidCapVideoProcAmp,293
KSPROPERTY_VIDEOPROCAMP_POWERLINE_FREQUENCY,294
&powerline.Value,295
sizeof(powerline) - sizeof(KSPROPERTY), &powerline,296
sizeof(powerline));297
298
// Disable low-light auto-exposure frame-rate drop299
KSPROPERTY_CAMERACONTROL_S priority = {};300
priority.Property.Set = kPropSetVidCapCameraControl;301
priority.Property.Id =302
KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY;303
priority.Property.Flags = KSPROPERTY_TYPE_SET;304
priority.Value = 0;305
priority.Flags = KSPROPERTY_CAMERACONTROL_FLAGS_MANUAL;306
ks->Set(kPropSetVidCapCameraControl,307
KSPROPERTY_CAMERACONTROL_AUTO_EXPOSURE_PRIORITY,308
&priority.Value,309
sizeof(priority) - sizeof(KSPROPERTY), &priority,310
sizeof(priority));311
}312
}313
moniker.Reset();314
break;315
}316
moniker.Reset();317
}318
}319
}320
321
if (com_owned) {322
CoUninitialize();323
}324
#else325
(void)target;326
#endif327
}328
184
} // namespace livekit_ffi329
} // namespace livekit_ffi@@ -74,6 +74,7 @@ pub mod ffi {
74
74
fn create_random_uuid() -> String;
75
75
fn video_encoder_backend_list() -> Vec<VideoEncoderBackend>;
76
76
fn new_log_sink(fnc: fn(String, LoggingSeverity)) -> UniquePtr<LogSink>;
77
fn tune_windows_camera(target: &str);
77
78
}
78
79
}
79
80
@@ -74,6 +74,7 @@ pub mod ffi {74
fn create_random_uuid() -> String;74
fn create_random_uuid() -> String;75
fn video_encoder_backend_list() -> Vec<VideoEncoderBackend>;75
fn video_encoder_backend_list() -> Vec<VideoEncoderBackend>;76
fn new_log_sink(fnc: fn(String, LoggingSeverity)) -> UniquePtr<LogSink>;76
fn new_log_sink(fnc: fn(String, LoggingSeverity)) -> UniquePtr<LogSink>;77
fn tune_windows_camera(target: &str);77
}78
}78
}79
}79
80
@@ -308,5 +308,29 @@ pub mod ffi {
308
308
width: i32,
309
309
height: i32,
310
310
) -> Result<()>;
311
312
unsafe fn yuy2_to_i420(
313
src_yuy2: *const u8,
314
src_stride_yuy2: i32,
315
dst_y: *mut u8,
316
dst_stride_y: i32,
317
dst_u: *mut u8,
318
dst_stride_u: i32,
319
dst_v: *mut u8,
320
dst_stride_v: i32,
321
width: i32,
322
height: i32,
323
) -> Result<()>;
324
325
unsafe fn argb_scale(
326
src_argb: *const u8,
327
src_stride_argb: i32,
328
src_width: i32,
329
src_height: i32,
330
dst_argb: *mut u8,
331
dst_stride_argb: i32,
332
dst_width: i32,
333
dst_height: i32,
334
) -> Result<()>;
311
335
}
312
336
}
@@ -308,5 +308,29 @@ pub mod ffi {308
width: i32,308
width: i32,309
height: i32,309
height: i32,310
) -> Result<()>;310
) -> Result<()>;311
312
unsafe fn yuy2_to_i420(313
src_yuy2: *const u8,314
src_stride_yuy2: i32,315
dst_y: *mut u8,316
dst_stride_y: i32,317
dst_u: *mut u8,318
dst_stride_u: i32,319
dst_v: *mut u8,320
dst_stride_v: i32,321
width: i32,322
height: i32,323
) -> Result<()>;324
325
unsafe fn argb_scale(326
src_argb: *const u8,327
src_stride_argb: i32,328
src_width: i32,329
src_height: i32,330
dst_argb: *mut u8,331
dst_stride_argb: i32,332
dst_width: i32,333
dst_height: i32,334
) -> Result<()>;311
}335
}312
}336
}