Merge branch 'fix/call-field-bugs' into integrate/calls-10
@@ -2,11 +2,14 @@ use std::path::PathBuf;
2
2
use std::time::Duration;
3
3
4
4
use calling::audio_io::AUDIO_MODE_ENV;
5
use calling::{AudioMode, CallOptions, CallReport, call_channel, run_test_call};
5
use calling::{AudioMode, CallCommand, CallOptions, CallReport, CallState, CallUpdate, call_channel, run_test_call};
6
6
use session::{DEFAULT_ENDPOINT, Session};
7
7
8
8
const HOLD_AFTER_CONNECTED: Duration = Duration::from_secs(12);
9
9
const HARD_LIMIT: Duration = Duration::from_secs(20);
10
const HOLD_START: Duration = Duration::from_secs(4);
11
const HOLD_LENGTH: Duration = Duration::from_secs(10);
12
const AFTER_RESUME: Duration = Duration::from_secs(20);
10
13
11
14
fn print_report(report: &CallReport) {
12
15
println!("# ice connected at {:?} ms, peer connected at {:?} ms", report.ice_connected_ms, report.peer_connected_ms);
@@ -42,6 +45,7 @@ async fn main() {
42
45
let session = Session::connect(&endpoint).await.expect("browser");
43
46
let poll_session = Session::connect(&endpoint).await.expect("browser");
44
47
let audio = AudioMode::parse(Some(&std::env::var(AUDIO_MODE_ENV).unwrap_or_else(|_| "tone".to_owned())));
48
let hold = std::env::args().any(|argument| argument == "--hold");
45
49
let rounds: usize = std::env::args().skip_while(|argument| argument != "--rounds").nth(1).and_then(|value| value.parse().ok()).unwrap_or(1);
46
50
for round in 1..=rounds {
47
51
println!("# round {round} of {rounds}");
@@ -49,15 +53,16 @@ async fn main() {
49
53
(Some(path), 2..) => Some(path.with_extension(format!("{round}.wav"))),
50
54
_ => wav_path.clone(),
51
55
};
52
test_call(&session, &poll_session, audio, round_wav).await;
56
test_call(&session, &poll_session, audio, round_wav, hold).await;
53
57
}
54
58
}
55
59
56
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>) {
60
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>, hold: bool) {
61
let connected_for = if hold { HOLD_START + HOLD_LENGTH + AFTER_RESUME } else { HOLD_AFTER_CONNECTED };
57
62
let options = CallOptions {
58
63
audio,
59
hold_after_connected: Some(HOLD_AFTER_CONNECTED),
60
hard_limit: Some(HARD_LIMIT),
64
hold_after_connected: Some(connected_for),
65
hard_limit: Some(connected_for + HARD_LIMIT - HOLD_AFTER_CONNECTED),
61
66
record_remote: true,
62
67
wav_path: wav_path.clone(),
63
68
sdp_dump_dir: std::env::var("CALLING_SDP_DUMP").ok().map(PathBuf::from),
@@ -66,10 +71,32 @@ async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode,
66
71
};
67
72
println!(
68
73
"# Test call, audio {:?}, hang up after {:?} connected (hard limit {:?})",
69
options.audio, HOLD_AFTER_CONNECTED, HARD_LIMIT
74
options.audio, options.hold_after_connected, options.hard_limit
70
75
);
71
76
let (mut handle, control) = call_channel();
72
let drain = tokio::spawn(async move { while handle.updates.recv().await.is_some() {} });
77
let commands = handle.commands.clone();
78
let drain = tokio::spawn(async move {
79
let mut hold_scheduled = !hold;
80
while let Some(update) = handle.updates.recv().await {
81
match update {
82
CallUpdate::State(CallState::Connected { .. }) if !hold_scheduled => {
83
hold_scheduled = true;
84
let commands = commands.clone();
85
tokio::spawn(async move {
86
tokio::time::sleep(HOLD_START).await;
87
println!("# hold");
88
let _ = commands.send(CallCommand::Hold(true));
89
tokio::time::sleep(HOLD_LENGTH).await;
90
println!("# resume");
91
let _ = commands.send(CallCommand::Hold(false));
92
});
93
}
94
CallUpdate::Hold(state) => println!("# hold state {state:?}"),
95
CallUpdate::Notice(text) => println!("# notice {text}"),
96
_ => {}
97
}
98
}
99
});
73
100
let outcome = run_test_call(session, poll_session, options, control).await;
74
101
drain.abort();
75
102
match outcome {
@@ -2,11 +2,14 @@ use std::path::PathBuf;2
use std::time::Duration;2
use std::time::Duration;3
3
4
use calling::audio_io::AUDIO_MODE_ENV;4
use calling::audio_io::AUDIO_MODE_ENV;5
use calling::{AudioMode, CallOptions, CallReport, call_channel, run_test_call};5
use calling::{AudioMode, CallCommand, CallOptions, CallReport, CallState, CallUpdate, call_channel, run_test_call};6
use session::{DEFAULT_ENDPOINT, Session};6
use session::{DEFAULT_ENDPOINT, Session};7
7
8
const HOLD_AFTER_CONNECTED: Duration = Duration::from_secs(12);8
const HOLD_AFTER_CONNECTED: Duration = Duration::from_secs(12);9
const HARD_LIMIT: Duration = Duration::from_secs(20);9
const HARD_LIMIT: Duration = Duration::from_secs(20);10
const HOLD_START: Duration = Duration::from_secs(4);11
const HOLD_LENGTH: Duration = Duration::from_secs(10);12
const AFTER_RESUME: Duration = Duration::from_secs(20);10
13
11
fn print_report(report: &CallReport) {14
fn print_report(report: &CallReport) {12
println!("# ice connected at {:?} ms, peer connected at {:?} ms", report.ice_connected_ms, report.peer_connected_ms);15
println!("# ice connected at {:?} ms, peer connected at {:?} ms", report.ice_connected_ms, report.peer_connected_ms);@@ -42,6 +45,7 @@ async fn main() {42
let session = Session::connect(&endpoint).await.expect("browser");45
let session = Session::connect(&endpoint).await.expect("browser");43
let poll_session = Session::connect(&endpoint).await.expect("browser");46
let poll_session = Session::connect(&endpoint).await.expect("browser");44
let audio = AudioMode::parse(Some(&std::env::var(AUDIO_MODE_ENV).unwrap_or_else(|_| "tone".to_owned())));47
let audio = AudioMode::parse(Some(&std::env::var(AUDIO_MODE_ENV).unwrap_or_else(|_| "tone".to_owned())));48
let hold = std::env::args().any(|argument| argument == "--hold");45
let rounds: usize = std::env::args().skip_while(|argument| argument != "--rounds").nth(1).and_then(|value| value.parse().ok()).unwrap_or(1);49
let rounds: usize = std::env::args().skip_while(|argument| argument != "--rounds").nth(1).and_then(|value| value.parse().ok()).unwrap_or(1);46
for round in 1..=rounds {50
for round in 1..=rounds {47
println!("# round {round} of {rounds}");51
println!("# round {round} of {rounds}");@@ -49,15 +53,16 @@ async fn main() {49
(Some(path), 2..) => Some(path.with_extension(format!("{round}.wav"))),53
(Some(path), 2..) => Some(path.with_extension(format!("{round}.wav"))),50
_ => wav_path.clone(),54
_ => wav_path.clone(),51
};55
};52
test_call(&session, &poll_session, audio, round_wav).await;56
test_call(&session, &poll_session, audio, round_wav, hold).await;53
}57
}54
}58
}55
59
56
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>) {60
async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode, wav_path: Option<PathBuf>, hold: bool) {61
let connected_for = if hold { HOLD_START + HOLD_LENGTH + AFTER_RESUME } else { HOLD_AFTER_CONNECTED };57
let options = CallOptions {62
let options = CallOptions {58
audio,63
audio,59
hold_after_connected: Some(HOLD_AFTER_CONNECTED),64
hold_after_connected: Some(connected_for),60
hard_limit: Some(HARD_LIMIT),65
hard_limit: Some(connected_for + HARD_LIMIT - HOLD_AFTER_CONNECTED),61
record_remote: true,66
record_remote: true,62
wav_path: wav_path.clone(),67
wav_path: wav_path.clone(),63
sdp_dump_dir: std::env::var("CALLING_SDP_DUMP").ok().map(PathBuf::from),68
sdp_dump_dir: std::env::var("CALLING_SDP_DUMP").ok().map(PathBuf::from),@@ -66,10 +71,32 @@ async fn test_call(session: &Session, poll_session: &Session, audio: AudioMode,66
};71
};67
println!(72
println!(68
"# Test call, audio {:?}, hang up after {:?} connected (hard limit {:?})",73
"# Test call, audio {:?}, hang up after {:?} connected (hard limit {:?})",69
options.audio, HOLD_AFTER_CONNECTED, HARD_LIMIT74
options.audio, options.hold_after_connected, options.hard_limit70
);75
);71
let (mut handle, control) = call_channel();76
let (mut handle, control) = call_channel();72
let drain = tokio::spawn(async move { while handle.updates.recv().await.is_some() {} });77
let commands = handle.commands.clone();78
let drain = tokio::spawn(async move {79
let mut hold_scheduled = !hold;80
while let Some(update) = handle.updates.recv().await {81
match update {82
CallUpdate::State(CallState::Connected { .. }) if !hold_scheduled => {83
hold_scheduled = true;84
let commands = commands.clone();85
tokio::spawn(async move {86
tokio::time::sleep(HOLD_START).await;87
println!("# hold");88
let _ = commands.send(CallCommand::Hold(true));89
tokio::time::sleep(HOLD_LENGTH).await;90
println!("# resume");91
let _ = commands.send(CallCommand::Hold(false));92
});93
}94
CallUpdate::Hold(state) => println!("# hold state {state:?}"),95
CallUpdate::Notice(text) => println!("# notice {text}"),96
_ => {}97
}98
}99
});73
let outcome = run_test_call(session, poll_session, options, control).await;100
let outcome = run_test_call(session, poll_session, options, control).await;74
drain.abort();101
drain.abort();75
match outcome {102
match outcome {@@ -35,7 +35,7 @@ use crate::end::EndKind;
35
35
use crate::engine::{CallEngine, EngineConfig, Inner};
36
36
use crate::error::{Error, Result};
37
37
use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
38
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};
38
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, keep_media_running, rewrite_directions};
39
39
use crate::mic_processing::MicSettings;
40
40
use crate::mute::{MuteCommand, MuteEffect};
41
41
use crate::push::CallNotification;
@@ -58,7 +58,8 @@ use crate::video_frame::VideoKey;
58
58
use crate::video_layout::{
59
59
CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, is_share_mid, offer_plan, one_to_one_plan,
60
60
};
61
use crate::video_send::{LocalVideo, VideoMode};
61
use crate::send_control::{RequestFilter, parse_request};
62
use crate::video_send::{LocalVideo, SendSource, VideoMode};
62
63
use crate::screen::{ShareKind, ShareSource, list_share_sources};
63
64
use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
64
65
use crate::trouter_events::{
@@ -839,6 +840,7 @@ async fn drive(
839
840
let mut local_hold = false;
840
841
let mut remote_hold = false;
841
842
let mut same_peer: Option<SamePeerOffer> = None;
843
let mut send_requests = RequestFilter::default();
842
844
let mut same_peer_deadline: Option<Instant> = None;
843
845
let mut meeting_chat = conversation.chat_thread.clone();
844
846
if let Some(thread) = &meeting_chat {
@@ -923,7 +925,10 @@ async fn drive(
923
925
&& let Some(pending) = same_peer.take()
924
926
{
925
927
same_peer_deadline = None;
926
let applied = apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await;
928
let applied = match pending.change {
929
Change::Hold(_) => apply_hold_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
930
Change::Camera(_) => apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
931
};
927
932
match applied {
928
933
Ok(()) => {
929
934
if let Some(url) = answer.links.get("mediaAcknowledgement") {
@@ -932,6 +937,7 @@ async fn drive(
932
937
match pending.change {
933
938
Change::Hold(hold) => {
934
939
local_hold = hold;
940
silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
935
941
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
936
942
}
937
943
Change::Camera(on) => control.send(CallUpdate::Camera(on)),
@@ -1151,6 +1157,18 @@ async fn drive(
1151
1157
control.send(CallUpdate::Progress(Progress::Ringing));
1152
1158
}
1153
1159
}
1160
Ok(CallEvent::ControlVideoStreaming(body)) => {
1161
replier.reply(request_id, 200, "");
1162
let Some(request) = parse_request(&body) else { continue };
1163
let Some(limit) = send_requests.admit(&request) else { continue };
1164
let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
1165
let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera };
1166
match local_video.apply_send_limit(source, &limit) {
1167
Ok(Some(applied)) => timeline.record("send limits", format!("{source:?} {applied:?} keyframe {}", limit.keyframe)),
1168
Ok(None) => {}
1169
Err(error) => timeline.record("send limits failed", error.to_string()),
1170
}
1171
}
1154
1172
Ok(CallEvent::Speakers(sources)) => {
1155
1173
replier.reply(request_id, 200, "");
1156
1174
let speakers = roster.mris_for_sources(&sources);
@@ -1280,6 +1298,7 @@ async fn drive(
1280
1298
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1281
1299
} else {
1282
1300
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
1301
silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
1283
1302
}
1284
1303
}
1285
1304
Some(CallCommand::DisableAudio) => {
@@ -2070,13 +2089,13 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
2070
2089
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2071
2090
.await
2072
2091
.map_err(|error| Error::Webrtc(error.to_string()))?;
2073
let text = directions_for(layout, hold, camera, &offer.to_string());
2092
let text = directions_for(layout, false, camera, &offer.to_string());
2074
2093
let description = parse_sdp(&text, SdpType::Offer)?;
2075
2094
peer.set_local_description(description)
2076
2095
.await
2077
2096
.map_err(|error| Error::Webrtc(error.to_string()))?;
2078
2097
let mut numbers = random_u32;
2079
let signaled = to_teams_offer(&text, plan, &mut numbers)?;
2098
let signaled = to_teams_offer(&directions_for(layout, hold, camera, &text), plan, &mut numbers)?;
2080
2099
Ok((text, signaled))
2081
2100
}
2082
2101
@@ -2323,6 +2342,16 @@ fn apply_mute(
2323
2342
effect.muted
2324
2343
}
2325
2344
2345
fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {
2346
let silent = on_hold || muted;
2347
if let Some(audio) = audio {
2348
audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);
2349
}
2350
if let Some(software_audio) = software_audio {
2351
software_audio.set_microphone_muted(silent);
2352
}
2353
}
2354
2326
2355
fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
2327
2356
let sender = peer
2328
2357
.senders()
@@ -2458,6 +2487,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2458
2487
CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2459
2488
CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2460
2489
CallEvent::Progress(status) => format!("{status:?}"),
2490
CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2461
2491
_ => String::new(),
2462
2492
};
2463
2493
timeline.record(format!("Trouter {}", event.name()), detail);
@@ -2473,7 +2503,17 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2473
2503
2474
2504
async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
2475
2505
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
2476
let description = parse_sdp(&answer, SdpType::Answer)?;
2506
set_browser_answer(peer, &answer).await
2507
}
2508
2509
/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
2510
async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
2511
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
2512
set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
2513
}
2514
2515
async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
2516
let description = parse_sdp(answer, SdpType::Answer)?;
2477
2517
peer.set_remote_description(description)
2478
2518
.await
2479
2519
.map_err(|error| Error::Webrtc(error.to_string()))
@@ -2744,6 +2784,15 @@ mod tests {
2744
2784
assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);
2745
2785
}
2746
2786
2787
#[test]
2788
fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
2789
let held = directions_for(Layout::Conference, true, false, BROWSER_OFFER);
2790
let mut numbers = || 7;
2791
let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
2792
assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
2793
assert_eq!(signaled.matches("a=candidate:").count(), 1);
2794
}
2795
2747
2796
#[test]
2748
2797
fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
2749
2798
let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
@@ -35,7 +35,7 @@ use crate::end::EndKind;35
use crate::engine::{CallEngine, EngineConfig, Inner};35
use crate::engine::{CallEngine, EngineConfig, Inner};36
use crate::error::{Error, Result};36
use crate::error::{Error, Result};37
use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};37
use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};38
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions};38
use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, keep_media_running, rewrite_directions};39
use crate::mic_processing::MicSettings;39
use crate::mic_processing::MicSettings;40
use crate::mute::{MuteCommand, MuteEffect};40
use crate::mute::{MuteCommand, MuteEffect};41
use crate::push::CallNotification;41
use crate::push::CallNotification;@@ -58,7 +58,8 @@ use crate::video_frame::VideoKey;58
use crate::video_layout::{58
use crate::video_layout::{59
CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, is_share_mid, offer_plan, one_to_one_plan,59
CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, is_share_mid, offer_plan, one_to_one_plan,60
};60
};61
use crate::video_send::{LocalVideo, VideoMode};61
use crate::send_control::{RequestFilter, parse_request};62
use crate::video_send::{LocalVideo, SendSource, VideoMode};62
use crate::screen::{ShareKind, ShareSource, list_share_sources};63
use crate::screen::{ShareKind, ShareSource, list_share_sources};63
use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};64
use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};64
use crate::trouter_events::{65
use crate::trouter_events::{@@ -839,6 +840,7 @@ async fn drive(839
let mut local_hold = false;840
let mut local_hold = false;840
let mut remote_hold = false;841
let mut remote_hold = false;841
let mut same_peer: Option<SamePeerOffer> = None;842
let mut same_peer: Option<SamePeerOffer> = None;843
let mut send_requests = RequestFilter::default();842
let mut same_peer_deadline: Option<Instant> = None;844
let mut same_peer_deadline: Option<Instant> = None;843
let mut meeting_chat = conversation.chat_thread.clone();845
let mut meeting_chat = conversation.chat_thread.clone();844
if let Some(thread) = &meeting_chat {846
if let Some(thread) = &meeting_chat {@@ -923,7 +925,10 @@ async fn drive(923
&& let Some(pending) = same_peer.take()925
&& let Some(pending) = same_peer.take()924
{926
{925
same_peer_deadline = None;927
same_peer_deadline = None;926
let applied = apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await;928
let applied = match pending.change {929
Change::Hold(_) => apply_hold_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,930
Change::Camera(_) => apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,931
};927
match applied {932
match applied {928
Ok(()) => {933
Ok(()) => {929
if let Some(url) = answer.links.get("mediaAcknowledgement") {934
if let Some(url) = answer.links.get("mediaAcknowledgement") {@@ -932,6 +937,7 @@ async fn drive(932
match pending.change {937
match pending.change {933
Change::Hold(hold) => {938
Change::Hold(hold) => {934
local_hold = hold;939
local_hold = hold;940
silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());935
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));941
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));936
}942
}937
Change::Camera(on) => control.send(CallUpdate::Camera(on)),943
Change::Camera(on) => control.send(CallUpdate::Camera(on)),@@ -1151,6 +1157,18 @@ async fn drive(1151
control.send(CallUpdate::Progress(Progress::Ringing));1157
control.send(CallUpdate::Progress(Progress::Ringing));1152
}1158
}1153
}1159
}1160
Ok(CallEvent::ControlVideoStreaming(body)) => {1161
replier.reply(request_id, 200, "");1162
let Some(request) = parse_request(&body) else { continue };1163
let Some(limit) = send_requests.admit(&request) else { continue };1164
let own_screen = roster.screen_source_of(&own_mri).map(i64::from);1165
let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera };1166
match local_video.apply_send_limit(source, &limit) {1167
Ok(Some(applied)) => timeline.record("send limits", format!("{source:?} {applied:?} keyframe {}", limit.keyframe)),1168
Ok(None) => {}1169
Err(error) => timeline.record("send limits failed", error.to_string()),1170
}1171
}1154
Ok(CallEvent::Speakers(sources)) => {1172
Ok(CallEvent::Speakers(sources)) => {1155
replier.reply(request_id, 200, "");1173
replier.reply(request_id, 200, "");1156
let speakers = roster.mris_for_sources(&sources);1174
let speakers = roster.mris_for_sources(&sources);@@ -1280,6 +1298,7 @@ async fn drive(1280
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));1298
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));1281
} else {1299
} else {1282
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);1300
muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);1301
silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());1283
}1302
}1284
}1303
}1285
Some(CallCommand::DisableAudio) => {1304
Some(CallCommand::DisableAudio) => {@@ -2070,13 +2089,13 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:2070
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })2089
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })2071
.await2090
.await2072
.map_err(|error| Error::Webrtc(error.to_string()))?;2091
.map_err(|error| Error::Webrtc(error.to_string()))?;2073
let text = directions_for(layout, hold, camera, &offer.to_string());2092
let text = directions_for(layout, false, camera, &offer.to_string());2074
let description = parse_sdp(&text, SdpType::Offer)?;2093
let description = parse_sdp(&text, SdpType::Offer)?;2075
peer.set_local_description(description)2094
peer.set_local_description(description)2076
.await2095
.await2077
.map_err(|error| Error::Webrtc(error.to_string()))?;2096
.map_err(|error| Error::Webrtc(error.to_string()))?;2078
let mut numbers = random_u32;2097
let mut numbers = random_u32;2079
let signaled = to_teams_offer(&text, plan, &mut numbers)?;2098
let signaled = to_teams_offer(&directions_for(layout, hold, camera, &text), plan, &mut numbers)?;2080
Ok((text, signaled))2099
Ok((text, signaled))2081
}2100
}2082
2101
@@ -2323,6 +2342,16 @@ fn apply_mute(2323
effect.muted2342
effect.muted2324
}2343
}2325
2344
2345
fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {2346
let silent = on_hold || muted;2347
if let Some(audio) = audio {2348
audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);2349
}2350
if let Some(software_audio) = software_audio {2351
software_audio.set_microphone_muted(silent);2352
}2353
}2354
2326
fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {2355
fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {2327
let sender = peer2356
let sender = peer2328
.senders()2357
.senders()@@ -2458,6 +2487,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca2458
CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),2487
CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),2459
CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),2488
CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),2460
CallEvent::Progress(status) => format!("{status:?}"),2489
CallEvent::Progress(status) => format!("{status:?}"),2490
CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),2461
_ => String::new(),2491
_ => String::new(),2462
};2492
};2463
timeline.record(format!("Trouter {}", event.name()), detail);2493
timeline.record(format!("Trouter {}", event.name()), detail);@@ -2473,7 +2503,17 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca2473
2503
2474
async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {2504
async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {2475
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;2505
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;2476
let description = parse_sdp(&answer, SdpType::Answer)?;2506
set_browser_answer(peer, &answer).await2507
}2508
2509
/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.2510
async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {2511
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;2512
set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await2513
}2514
2515
async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {2516
let description = parse_sdp(answer, SdpType::Answer)?;2477
peer.set_remote_description(description)2517
peer.set_remote_description(description)2478
.await2518
.await2479
.map_err(|error| Error::Webrtc(error.to_string()))2519
.map_err(|error| Error::Webrtc(error.to_string()))@@ -2744,6 +2784,15 @@ mod tests {2744
assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);2784
assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);2745
}2785
}2746
2786
2787
#[test]2788
fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {2789
let held = directions_for(Layout::Conference, true, false, BROWSER_OFFER);2790
let mut numbers = || 7;2791
let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;2792
assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);2793
assert_eq!(signaled.matches("a=candidate:").count(), 1);2794
}2795
2747
#[test]2796
#[test]2748
fn a_move_into_the_meeting_you_are_already_in_is_ignored() {2797
fn a_move_into_the_meeting_you_are_already_in_is_ignored() {2749
let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };2798
let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };@@ -2,7 +2,7 @@ use std::sync::Arc;
2
2
use std::time::Duration;
3
3
4
4
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};
5
use libwebrtc::video_frame::I420Buffer;
5
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};
6
6
use nokhwa::pixel_format::RgbAFormat;
7
7
use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};
8
8
use nokhwa::{Camera, query};
@@ -19,6 +19,9 @@ const BYTES_PER_PIXEL: u32 = 4;
19
19
const CAPTURE_WIDTH: u32 = 1280;
20
20
const CAPTURE_HEIGHT: u32 = 720;
21
21
const CAPTURE_FPS: u32 = 30;
22
const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080;
23
const ASPECT_WIDTH: u32 = 16;
24
const ASPECT_HEIGHT: u32 = 9;
22
25
const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];
23
26
24
27
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -74,13 +77,80 @@ fn format_rank(frame_format: FrameFormat) -> u8 {
74
77
}
75
78
}
76
79
80
fn is_widescreen(width: u32, height: u32) -> bool {
81
width * ASPECT_HEIGHT == height * ASPECT_WIDTH
82
}
83
84
fn widescreen_tier(format: &CameraFormat) -> u8 {
85
match (is_widescreen(format.width(), format.height()), format.height()) {
86
(true, CAPTURE_HEIGHT) => 3,
87
(true, height) if height > CAPTURE_HEIGHT => 2,
88
(true, _) => 1,
89
(false, _) => 0,
90
}
91
}
92
77
93
fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {
78
94
formats
79
95
.iter()
80
96
.copied()
81
97
.filter(|format| DIRECT_FORMATS.contains(&format.format()))
82
.filter(|format| format.frame_rate() >= CAPTURE_FPS && format.height() <= CAPTURE_HEIGHT)
83
.max_by_key(|format| (format.height(), format_rank(format.format()), std::cmp::Reverse(format.frame_rate())))
98
.filter(|format| format.frame_rate() >= CAPTURE_FPS)
99
.filter(|format| {
100
format.height() <= CAPTURE_HEIGHT
101
|| (is_widescreen(format.width(), format.height()) && format.height() <= LARGEST_DOWNSCALED_HEIGHT)
102
})
103
.max_by_key(|format| {
104
(
105
widescreen_tier(format),
106
std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)),
107
format_rank(format.format()),
108
std::cmp::Reverse(format.frame_rate()),
109
)
110
})
111
}
112
113
fn even(value: u32) -> u32 {
114
value & !1
115
}
116
117
fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32) -> I420Buffer {
118
let mut cropped = I420Buffer::new(width, height);
119
let (source_strides, source_planes) = (buffer.strides(), buffer.data());
120
let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());
121
let planes = [
122
(source_planes.0, source_strides.0, target_planes.0, target_strides.0, 1),
123
(source_planes.1, source_strides.1, target_planes.1, target_strides.1, 2),
124
(source_planes.2, source_strides.2, target_planes.2, target_strides.2, 2),
125
];
126
for (source, source_stride, target, target_stride, divisor) in planes {
127
let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);
128
let (plane_width, plane_height) = (width.div_ceil(divisor) as usize, height.div_ceil(divisor) as usize);
129
for row in 0..plane_height {
130
let from = (plane_top + row) * source_stride as usize + plane_left;
131
let to = row * target_stride as usize;
132
target[to..to + plane_width].copy_from_slice(&source[from..from + plane_width]);
133
}
134
}
135
cropped
136
}
137
138
pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {
139
let (width, height) = (buffer.width(), buffer.height());
140
let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {
141
(even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)
142
} else {
143
(width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))
144
};
145
if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {
146
buffer = crop_i420(&buffer, even((width - crop_width) / 2), even((height - crop_height) / 2), crop_width, crop_height);
147
}
148
let (width, height) = (buffer.width(), buffer.height());
149
if height > CAPTURE_HEIGHT {
150
let scaled_width = even(width * CAPTURE_HEIGHT / height);
151
return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32);
152
}
153
buffer
84
154
}
85
155
86
156
fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {
@@ -201,7 +271,7 @@ pub fn start_camera(
201
271
i420_from_rgba(&decoded.into_raw(), width, height)
202
272
}
203
273
};
204
deliver(stage.apply_i420(buffer));
274
deliver(stage.apply_i420(fit_widescreen(buffer)));
205
275
}
206
276
let _ = camera.stop_stream();
207
277
})
@@ -286,6 +356,58 @@ mod tests {
286
356
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));
287
357
}
288
358
359
#[test]
360
fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {
361
let formats = [format(960, 720, FrameFormat::NV12, 30), format(1280, 720, FrameFormat::YUYV, 30), format(640, 480, FrameFormat::NV12, 30)];
362
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::YUYV, 30)));
363
}
364
365
#[test]
366
fn without_720p_the_order_is_1080p_then_360p_then_4_3() {
367
let full_hd = format(1920, 1080, FrameFormat::NV12, 30);
368
let small = format(640, 360, FrameFormat::NV12, 30);
369
let classic = format(960, 720, FrameFormat::NV12, 30);
370
assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd));
371
assert_eq!(pick_format(&[classic, small]), Some(small));
372
assert_eq!(pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]), Some(classic));
373
}
374
375
fn gradient(width: u32, height: u32) -> I420Buffer {
376
let mut buffer = I420Buffer::new(width, height);
377
let (stride_y, stride_u, _) = buffer.strides();
378
let (plane_y, plane_u, _) = buffer.data_mut();
379
for row in 0..height as usize {
380
plane_y[row * stride_y as usize..][..width as usize].fill(row as u8);
381
}
382
for row in 0..height.div_ceil(2) as usize {
383
plane_u[row * stride_u as usize..][..width.div_ceil(2) as usize].fill(row as u8);
384
}
385
buffer
386
}
387
388
#[test]
389
fn a_4_3_frame_is_centre_cropped_to_16_9() {
390
let cropped = fit_widescreen(gradient(960, 720));
391
assert_eq!((cropped.width(), cropped.height()), (960, 540));
392
let (stride_y, stride_u, _) = cropped.strides();
393
let (plane_y, plane_u, _) = cropped.data();
394
assert_eq!(plane_y[0], 90);
395
assert_eq!(plane_y[539 * stride_y as usize], 629_u32 as u8);
396
assert_eq!(plane_u[0], 45);
397
assert_eq!(plane_u[269 * stride_u as usize], 314_u32 as u8);
398
}
399
400
#[test]
401
fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() {
402
assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280);
403
let scaled = fit_widescreen(gradient(1920, 1080));
404
assert_eq!((scaled.width(), scaled.height()), (1280, 720));
405
let wide = fit_widescreen(gradient(2560, 1080));
406
assert_eq!((wide.width(), wide.height()), (1280, 720));
407
let classic = fit_widescreen(gradient(640, 480));
408
assert_eq!((classic.width(), classic.height()), (640, 360));
409
}
410
289
411
#[test]
290
412
fn no_usable_format_picks_nothing() {
291
413
let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];
@@ -2,7 +2,7 @@ use std::sync::Arc;2
use std::time::Duration;2
use std::time::Duration;3
3
4
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};4
use libwebrtc::native::yuv_helper::{abgr_to_i420, nv12_to_i420};5
use libwebrtc::video_frame::I420Buffer;5
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _};6
use nokhwa::pixel_format::RgbAFormat;6
use nokhwa::pixel_format::RgbAFormat;7
use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};7
use nokhwa::utils::{ApiBackend, CameraFormat, CameraIndex, FrameFormat, RequestedFormat, RequestedFormatType, Resolution};8
use nokhwa::{Camera, query};8
use nokhwa::{Camera, query};@@ -19,6 +19,9 @@ const BYTES_PER_PIXEL: u32 = 4;19
const CAPTURE_WIDTH: u32 = 1280;19
const CAPTURE_WIDTH: u32 = 1280;20
const CAPTURE_HEIGHT: u32 = 720;20
const CAPTURE_HEIGHT: u32 = 720;21
const CAPTURE_FPS: u32 = 30;21
const CAPTURE_FPS: u32 = 30;22
const LARGEST_DOWNSCALED_HEIGHT: u32 = 1080;23
const ASPECT_WIDTH: u32 = 16;24
const ASPECT_HEIGHT: u32 = 9;22
const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];25
const DIRECT_FORMATS: [FrameFormat; 2] = [FrameFormat::NV12, FrameFormat::YUYV];23
26
24
#[derive(Debug, Clone, PartialEq, Eq)]27
#[derive(Debug, Clone, PartialEq, Eq)]@@ -74,13 +77,80 @@ fn format_rank(frame_format: FrameFormat) -> u8 {74
}77
}75
}78
}76
79
80
fn is_widescreen(width: u32, height: u32) -> bool {81
width * ASPECT_HEIGHT == height * ASPECT_WIDTH82
}83
84
fn widescreen_tier(format: &CameraFormat) -> u8 {85
match (is_widescreen(format.width(), format.height()), format.height()) {86
(true, CAPTURE_HEIGHT) => 3,87
(true, height) if height > CAPTURE_HEIGHT => 2,88
(true, _) => 1,89
(false, _) => 0,90
}91
}92
77
fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {93
fn pick_format(formats: &[CameraFormat]) -> Option<CameraFormat> {78
formats94
formats79
.iter()95
.iter()80
.copied()96
.copied()81
.filter(|format| DIRECT_FORMATS.contains(&format.format()))97
.filter(|format| DIRECT_FORMATS.contains(&format.format()))82
.filter(|format| format.frame_rate() >= CAPTURE_FPS && format.height() <= CAPTURE_HEIGHT)98
.filter(|format| format.frame_rate() >= CAPTURE_FPS)83
.max_by_key(|format| (format.height(), format_rank(format.format()), std::cmp::Reverse(format.frame_rate())))99
.filter(|format| {100
format.height() <= CAPTURE_HEIGHT101
|| (is_widescreen(format.width(), format.height()) && format.height() <= LARGEST_DOWNSCALED_HEIGHT)102
})103
.max_by_key(|format| {104
(105
widescreen_tier(format),106
std::cmp::Reverse(format.height().abs_diff(CAPTURE_HEIGHT)),107
format_rank(format.format()),108
std::cmp::Reverse(format.frame_rate()),109
)110
})111
}112
113
fn even(value: u32) -> u32 {114
value & !1115
}116
117
fn crop_i420(buffer: &I420Buffer, left: u32, top: u32, width: u32, height: u32) -> I420Buffer {118
let mut cropped = I420Buffer::new(width, height);119
let (source_strides, source_planes) = (buffer.strides(), buffer.data());120
let (target_strides, target_planes) = (cropped.strides(), cropped.data_mut());121
let planes = [122
(source_planes.0, source_strides.0, target_planes.0, target_strides.0, 1),123
(source_planes.1, source_strides.1, target_planes.1, target_strides.1, 2),124
(source_planes.2, source_strides.2, target_planes.2, target_strides.2, 2),125
];126
for (source, source_stride, target, target_stride, divisor) in planes {127
let (plane_left, plane_top) = ((left / divisor) as usize, (top / divisor) as usize);128
let (plane_width, plane_height) = (width.div_ceil(divisor) as usize, height.div_ceil(divisor) as usize);129
for row in 0..plane_height {130
let from = (plane_top + row) * source_stride as usize + plane_left;131
let to = row * target_stride as usize;132
target[to..to + plane_width].copy_from_slice(&source[from..from + plane_width]);133
}134
}135
cropped136
}137
138
pub(crate) fn fit_widescreen(mut buffer: I420Buffer) -> I420Buffer {139
let (width, height) = (buffer.width(), buffer.height());140
let (crop_width, crop_height) = if width * ASPECT_HEIGHT > height * ASPECT_WIDTH {141
(even(height * ASPECT_WIDTH / ASPECT_HEIGHT), height)142
} else {143
(width, even(width * ASPECT_HEIGHT / ASPECT_WIDTH))144
};145
if (crop_width, crop_height) != (width, height) && crop_width >= 2 && crop_height >= 2 {146
buffer = crop_i420(&buffer, even((width - crop_width) / 2), even((height - crop_height) / 2), crop_width, crop_height);147
}148
let (width, height) = (buffer.width(), buffer.height());149
if height > CAPTURE_HEIGHT {150
let scaled_width = even(width * CAPTURE_HEIGHT / height);151
return buffer.scale(scaled_width as i32, CAPTURE_HEIGHT as i32);152
}153
buffer84
}154
}85
155
86
fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {156
fn open_picked_format(index: CameraIndex) -> std::result::Result<Camera, nokhwa::NokhwaError> {@@ -201,7 +271,7 @@ pub fn start_camera(201
i420_from_rgba(&decoded.into_raw(), width, height)271
i420_from_rgba(&decoded.into_raw(), width, height)202
}272
}203
};273
};204
deliver(stage.apply_i420(buffer));274
deliver(stage.apply_i420(fit_widescreen(buffer)));205
}275
}206
let _ = camera.stop_stream();276
let _ = camera.stop_stream();207
})277
})@@ -286,6 +356,58 @@ mod tests {286
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));356
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::NV12, 30)));287
}357
}288
358
359
#[test]360
fn a_widescreen_format_beats_a_4_3_one_of_the_same_height() {361
let formats = [format(960, 720, FrameFormat::NV12, 30), format(1280, 720, FrameFormat::YUYV, 30), format(640, 480, FrameFormat::NV12, 30)];362
assert_eq!(pick_format(&formats), Some(format(1280, 720, FrameFormat::YUYV, 30)));363
}364
365
#[test]366
fn without_720p_the_order_is_1080p_then_360p_then_4_3() {367
let full_hd = format(1920, 1080, FrameFormat::NV12, 30);368
let small = format(640, 360, FrameFormat::NV12, 30);369
let classic = format(960, 720, FrameFormat::NV12, 30);370
assert_eq!(pick_format(&[classic, small, full_hd]), Some(full_hd));371
assert_eq!(pick_format(&[classic, small]), Some(small));372
assert_eq!(pick_format(&[classic, format(2560, 1440, FrameFormat::NV12, 30)]), Some(classic));373
}374
375
fn gradient(width: u32, height: u32) -> I420Buffer {376
let mut buffer = I420Buffer::new(width, height);377
let (stride_y, stride_u, _) = buffer.strides();378
let (plane_y, plane_u, _) = buffer.data_mut();379
for row in 0..height as usize {380
plane_y[row * stride_y as usize..][..width as usize].fill(row as u8);381
}382
for row in 0..height.div_ceil(2) as usize {383
plane_u[row * stride_u as usize..][..width.div_ceil(2) as usize].fill(row as u8);384
}385
buffer386
}387
388
#[test]389
fn a_4_3_frame_is_centre_cropped_to_16_9() {390
let cropped = fit_widescreen(gradient(960, 720));391
assert_eq!((cropped.width(), cropped.height()), (960, 540));392
let (stride_y, stride_u, _) = cropped.strides();393
let (plane_y, plane_u, _) = cropped.data();394
assert_eq!(plane_y[0], 90);395
assert_eq!(plane_y[539 * stride_y as usize], 629_u32 as u8);396
assert_eq!(plane_u[0], 45);397
assert_eq!(plane_u[269 * stride_u as usize], 314_u32 as u8);398
}399
400
#[test]401
fn a_widescreen_frame_passes_and_1080p_is_scaled_to_720p() {402
assert_eq!(fit_widescreen(gradient(1280, 720)).width(), 1280);403
let scaled = fit_widescreen(gradient(1920, 1080));404
assert_eq!((scaled.width(), scaled.height()), (1280, 720));405
let wide = fit_widescreen(gradient(2560, 1080));406
assert_eq!((wide.width(), wide.height()), (1280, 720));407
let classic = fit_widescreen(gradient(640, 480));408
assert_eq!((classic.width(), classic.height()), (640, 360));409
}410
289
#[test]411
#[test]290
fn no_usable_format_picks_nothing() {412
fn no_usable_format_picks_nothing() {291
let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];413
let formats = [format(1280, 720, FrameFormat::MJPEG, 30), format(1280, 720, FrameFormat::YUYV, 15)];@@ -80,11 +80,52 @@ pub fn shared_factory() -> PeerConnectionFactory {
80
80
FACTORY.get_or_init(PeerConnectionFactory::default).clone()
81
81
}
82
82
83
pub fn resolve_index(devices: &[AudioDevice], choice: &DeviceChoice) -> Option<u16> {
83
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
84
pub enum Flow {
85
Capture,
86
Render,
87
}
88
89
/// Endpoint id of the Windows default device (console role), which the ADM reports as the device guid.
90
#[cfg(windows)]
91
pub fn system_default_id(flow: Flow) -> Option<String> {
92
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};
93
let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();
94
let id = default_endpoint_id(flow);
95
if initialized {
96
unsafe { CoUninitialize() };
97
}
98
id
99
}
100
101
#[cfg(windows)]
102
fn default_endpoint_id(flow: Flow) -> Option<String> {
103
use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eConsole, eRender};
104
use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};
105
let data_flow = match flow {
106
Flow::Capture => eCapture,
107
Flow::Render => eRender,
108
};
109
unsafe {
110
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;
111
let device = enumerator.GetDefaultAudioEndpoint(data_flow, eConsole).ok()?;
112
let id = device.GetId().ok()?;
113
let text = id.to_string().ok();
114
CoTaskMemFree(Some(id.0 as *const _));
115
text
116
}
117
}
118
119
#[cfg(not(windows))]
120
pub fn system_default_id(_flow: Flow) -> Option<String> {
121
None
122
}
123
124
pub fn resolve_index(devices: &[AudioDevice], choice: &DeviceChoice, system_default: Option<&str>) -> Option<u16> {
84
125
match choice {
85
DeviceChoice::SystemDefault => devices
86
.iter()
87
.find(|device| device.is_system_alias())
126
DeviceChoice::SystemDefault => system_default
127
.and_then(|id| devices.iter().find(|device| device.guid.eq_ignore_ascii_case(id)))
128
.or_else(|| devices.iter().find(|device| device.is_system_alias()))
88
129
.or(devices.first())
89
130
.map(|device| device.index),
90
131
DeviceChoice::Device(key) => devices
@@ -121,8 +162,12 @@ pub fn list_devices(factory: &PeerConnectionFactory) -> DeviceLists {
121
162
lists
122
163
}
123
164
165
fn default_for(choice: &DeviceChoice, flow: Flow) -> Option<String> {
166
(*choice == DeviceChoice::SystemDefault).then(|| system_default_id(flow)).flatten()
167
}
168
124
169
pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
125
let Some(index) = resolve_index(&enumerate(factory).inputs, choice) else {
170
let Some(index) = resolve_index(&enumerate(factory).inputs, choice, default_for(choice, Flow::Capture).as_deref()) else {
126
171
return false;
127
172
};
128
173
factory.stop_recording();
@@ -133,7 +178,7 @@ pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> b
133
178
}
134
179
135
180
pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {
136
let Some(index) = resolve_index(&enumerate(factory).outputs, choice) else {
181
let Some(index) = resolve_index(&enumerate(factory).outputs, choice, default_for(choice, Flow::Render).as_deref()) else {
137
182
return false;
138
183
};
139
184
factory.stop_playout();
@@ -189,17 +234,29 @@ mod tests {
189
234
let devices = [device(0, "default: Speakers", ""), device(1, "Speakers", ""), device(2, "Headset", "")];
190
235
let entries = menu_entries(&devices);
191
236
assert_eq!(entries[1].choice, DeviceChoice::Device("Speakers".into()));
192
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Headset".into())), Some(2));
193
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Gone".into())), None);
237
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Headset".into()), None), Some(2));
238
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Gone".into()), None), None);
194
239
}
195
240
196
241
#[test]
197
242
fn the_system_default_resolves_to_the_alias_or_the_first_device() {
198
243
let with_alias = [device(0, "USB", "u"), device(1, "default: USB", "")];
199
assert_eq!(resolve_index(&with_alias, &DeviceChoice::SystemDefault), Some(1));
244
assert_eq!(resolve_index(&with_alias, &DeviceChoice::SystemDefault, None), Some(1));
200
245
let without_alias = [device(0, "Speakers", "s"), device(1, "Headset", "h")];
201
assert_eq!(resolve_index(&without_alias, &DeviceChoice::SystemDefault), Some(0));
202
assert_eq!(resolve_index(&[], &DeviceChoice::SystemDefault), None);
246
assert_eq!(resolve_index(&without_alias, &DeviceChoice::SystemDefault, None), Some(0));
247
assert_eq!(resolve_index(&[], &DeviceChoice::SystemDefault, None), None);
248
}
249
250
#[test]
251
fn the_system_default_follows_the_platform_default_endpoint() {
252
let devices = [
253
device(0, "Speakers (Realtek)", "{0.0.0.00000000}.{aaaa}"),
254
device(1, "Headset Earphone", "{0.0.0.00000000}.{BBBB}"),
255
];
256
let headset = Some("{0.0.0.00000000}.{bbbb}");
257
assert_eq!(resolve_index(&devices, &DeviceChoice::SystemDefault, headset), Some(1));
258
assert_eq!(resolve_index(&devices, &DeviceChoice::SystemDefault, Some("{0.0.0.00000000}.{gone}")), Some(0));
259
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()), headset), Some(0));
203
260
}
204
261
205
262
#[test]
@@ -80,11 +80,52 @@ pub fn shared_factory() -> PeerConnectionFactory {80
FACTORY.get_or_init(PeerConnectionFactory::default).clone()80
FACTORY.get_or_init(PeerConnectionFactory::default).clone()81
}81
}82
82
83
pub fn resolve_index(devices: &[AudioDevice], choice: &DeviceChoice) -> Option<u16> {83
#[derive(Debug, Clone, Copy, PartialEq, Eq)]84
pub enum Flow {85
Capture,86
Render,87
}88
89
/// Endpoint id of the Windows default device (console role), which the ADM reports as the device guid.90
#[cfg(windows)]91
pub fn system_default_id(flow: Flow) -> Option<String> {92
use windows::Win32::System::Com::{COINIT_MULTITHREADED, CoInitializeEx, CoUninitialize};93
let initialized = unsafe { CoInitializeEx(None, COINIT_MULTITHREADED) }.is_ok();94
let id = default_endpoint_id(flow);95
if initialized {96
unsafe { CoUninitialize() };97
}98
id99
}100
101
#[cfg(windows)]102
fn default_endpoint_id(flow: Flow) -> Option<String> {103
use windows::Win32::Media::Audio::{IMMDeviceEnumerator, MMDeviceEnumerator, eCapture, eConsole, eRender};104
use windows::Win32::System::Com::{CLSCTX_ALL, CoCreateInstance, CoTaskMemFree};105
let data_flow = match flow {106
Flow::Capture => eCapture,107
Flow::Render => eRender,108
};109
unsafe {110
let enumerator: IMMDeviceEnumerator = CoCreateInstance(&MMDeviceEnumerator, None, CLSCTX_ALL).ok()?;111
let device = enumerator.GetDefaultAudioEndpoint(data_flow, eConsole).ok()?;112
let id = device.GetId().ok()?;113
let text = id.to_string().ok();114
CoTaskMemFree(Some(id.0 as *const _));115
text116
}117
}118
119
#[cfg(not(windows))]120
pub fn system_default_id(_flow: Flow) -> Option<String> {121
None122
}123
124
pub fn resolve_index(devices: &[AudioDevice], choice: &DeviceChoice, system_default: Option<&str>) -> Option<u16> {84
match choice {125
match choice {85
DeviceChoice::SystemDefault => devices126
DeviceChoice::SystemDefault => system_default86
.iter()127
.and_then(|id| devices.iter().find(|device| device.guid.eq_ignore_ascii_case(id)))87
.find(|device| device.is_system_alias())128
.or_else(|| devices.iter().find(|device| device.is_system_alias()))88
.or(devices.first())129
.or(devices.first())89
.map(|device| device.index),130
.map(|device| device.index),90
DeviceChoice::Device(key) => devices131
DeviceChoice::Device(key) => devices@@ -121,8 +162,12 @@ pub fn list_devices(factory: &PeerConnectionFactory) -> DeviceLists {121
lists162
lists122
}163
}123
164
165
fn default_for(choice: &DeviceChoice, flow: Flow) -> Option<String> {166
(*choice == DeviceChoice::SystemDefault).then(|| system_default_id(flow)).flatten()167
}168
124
pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {169
pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {125
let Some(index) = resolve_index(&enumerate(factory).inputs, choice) else {170
let Some(index) = resolve_index(&enumerate(factory).inputs, choice, default_for(choice, Flow::Capture).as_deref()) else {126
return false;171
return false;127
};172
};128
factory.stop_recording();173
factory.stop_recording();@@ -133,7 +178,7 @@ pub fn select_input(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> b133
}178
}134
179
135
pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {180
pub fn select_output(factory: &PeerConnectionFactory, choice: &DeviceChoice) -> bool {136
let Some(index) = resolve_index(&enumerate(factory).outputs, choice) else {181
let Some(index) = resolve_index(&enumerate(factory).outputs, choice, default_for(choice, Flow::Render).as_deref()) else {137
return false;182
return false;138
};183
};139
factory.stop_playout();184
factory.stop_playout();@@ -189,17 +234,29 @@ mod tests {189
let devices = [device(0, "default: Speakers", ""), device(1, "Speakers", ""), device(2, "Headset", "")];234
let devices = [device(0, "default: Speakers", ""), device(1, "Speakers", ""), device(2, "Headset", "")];190
let entries = menu_entries(&devices);235
let entries = menu_entries(&devices);191
assert_eq!(entries[1].choice, DeviceChoice::Device("Speakers".into()));236
assert_eq!(entries[1].choice, DeviceChoice::Device("Speakers".into()));192
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Headset".into())), Some(2));237
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Headset".into()), None), Some(2));193
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Gone".into())), None);238
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("Gone".into()), None), None);194
}239
}195
240
196
#[test]241
#[test]197
fn the_system_default_resolves_to_the_alias_or_the_first_device() {242
fn the_system_default_resolves_to_the_alias_or_the_first_device() {198
let with_alias = [device(0, "USB", "u"), device(1, "default: USB", "")];243
let with_alias = [device(0, "USB", "u"), device(1, "default: USB", "")];199
assert_eq!(resolve_index(&with_alias, &DeviceChoice::SystemDefault), Some(1));244
assert_eq!(resolve_index(&with_alias, &DeviceChoice::SystemDefault, None), Some(1));200
let without_alias = [device(0, "Speakers", "s"), device(1, "Headset", "h")];245
let without_alias = [device(0, "Speakers", "s"), device(1, "Headset", "h")];201
assert_eq!(resolve_index(&without_alias, &DeviceChoice::SystemDefault), Some(0));246
assert_eq!(resolve_index(&without_alias, &DeviceChoice::SystemDefault, None), Some(0));202
assert_eq!(resolve_index(&[], &DeviceChoice::SystemDefault), None);247
assert_eq!(resolve_index(&[], &DeviceChoice::SystemDefault, None), None);248
}249
250
#[test]251
fn the_system_default_follows_the_platform_default_endpoint() {252
let devices = [253
device(0, "Speakers (Realtek)", "{0.0.0.00000000}.{aaaa}"),254
device(1, "Headset Earphone", "{0.0.0.00000000}.{BBBB}"),255
];256
let headset = Some("{0.0.0.00000000}.{bbbb}");257
assert_eq!(resolve_index(&devices, &DeviceChoice::SystemDefault, headset), Some(1));258
assert_eq!(resolve_index(&devices, &DeviceChoice::SystemDefault, Some("{0.0.0.00000000}.{gone}")), Some(0));259
assert_eq!(resolve_index(&devices, &DeviceChoice::Device("{0.0.0.00000000}.{aaaa}".into()), headset), Some(0));203
}260
}204
261
205
#[test]262
#[test]@@ -1,3 +1,5 @@
1
use std::collections::HashMap;
2
1
3
use crate::error::Result;
2
4
use crate::sdp::parse;
3
5
@@ -68,6 +70,27 @@ pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'st
68
70
lines.join(newline)
69
71
}
70
72
73
fn mirrored(direction: &str) -> &'static str {
74
match direction {
75
"sendonly" => "recvonly",
76
"recvonly" => "sendonly",
77
"inactive" => INACTIVE,
78
_ => "sendrecv",
79
}
80
}
81
82
pub fn keep_media_running(browser_answer: &str, browser_offer: &str) -> String {
83
let offer_lines: Vec<String> = browser_offer.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
84
let offered: HashMap<String, &'static str> = sections(&offer_lines)
85
.into_iter()
86
.filter_map(|section| {
87
let direction = offer_lines[section.direction_line?].strip_prefix("a=")?;
88
Some((section.mid, mirrored(direction)))
89
})
90
.collect();
91
rewrite_directions(browser_answer, |line| offered.get(line.mid).copied())
92
}
93
71
94
pub fn all_inactive(sdp: &str) -> String {
72
95
rewrite_directions(sdp, |_| Some(INACTIVE))
73
96
}
@@ -148,6 +171,14 @@ mod tests {
148
171
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
149
172
}
150
173
174
#[test]
175
fn a_hold_answer_mirrors_our_offer_so_nothing_stops_locally() {
176
let answer = all_inactive(&OFFER.replace("a=setup:actpass", "a=setup:passive"));
177
let kept = keep_media_running(&answer, OFFER);
178
assert_eq!(directions(&kept), vec!["sendrecv", "sendrecv", "sendonly"]);
179
assert_eq!(kept.lines().count(), answer.lines().count());
180
}
181
151
182
#[test]
152
183
fn a_hold_is_every_audio_and_video_line_inactive() {
153
184
assert!(is_hold(&all_inactive(OFFER)).unwrap());
@@ -1,3 +1,5 @@1
use std::collections::HashMap;2
1
use crate::error::Result;3
use crate::error::Result;2
use crate::sdp::parse;4
use crate::sdp::parse;3
5
@@ -68,6 +70,27 @@ pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'st68
lines.join(newline)70
lines.join(newline)69
}71
}70
72
73
fn mirrored(direction: &str) -> &'static str {74
match direction {75
"sendonly" => "recvonly",76
"recvonly" => "sendonly",77
"inactive" => INACTIVE,78
_ => "sendrecv",79
}80
}81
82
pub fn keep_media_running(browser_answer: &str, browser_offer: &str) -> String {83
let offer_lines: Vec<String> = browser_offer.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();84
let offered: HashMap<String, &'static str> = sections(&offer_lines)85
.into_iter()86
.filter_map(|section| {87
let direction = offer_lines[section.direction_line?].strip_prefix("a=")?;88
Some((section.mid, mirrored(direction)))89
})90
.collect();91
rewrite_directions(browser_answer, |line| offered.get(line.mid).copied())92
}93
71
pub fn all_inactive(sdp: &str) -> String {94
pub fn all_inactive(sdp: &str) -> String {72
rewrite_directions(sdp, |_| Some(INACTIVE))95
rewrite_directions(sdp, |_| Some(INACTIVE))73
}96
}@@ -148,6 +171,14 @@ mod tests {148
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);171
assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);149
}172
}150
173
174
#[test]175
fn a_hold_answer_mirrors_our_offer_so_nothing_stops_locally() {176
let answer = all_inactive(&OFFER.replace("a=setup:actpass", "a=setup:passive"));177
let kept = keep_media_running(&answer, OFFER);178
assert_eq!(directions(&kept), vec!["sendrecv", "sendrecv", "sendonly"]);179
assert_eq!(kept.lines().count(), answer.lines().count());180
}181
151
#[test]182
#[test]152
fn a_hold_is_every_audio_and_video_line_inactive() {183
fn a_hold_is_every_audio_and_video_line_inactive() {153
assert!(is_hold(&all_inactive(OFFER)).unwrap());184
assert!(is_hold(&all_inactive(OFFER)).unwrap());@@ -40,6 +40,7 @@ pub mod ring;
40
40
pub mod roster;
41
41
pub mod screen;
42
42
pub mod sdp;
43
pub mod send_control;
43
44
pub mod signaling;
44
45
pub mod software_audio;
45
46
pub mod sound_capture;
@@ -40,6 +40,7 @@ pub mod ring;40
pub mod roster;40
pub mod roster;41
pub mod screen;41
pub mod screen;42
pub mod sdp;42
pub mod sdp;43
pub mod send_control;43
pub mod signaling;44
pub mod signaling;44
pub mod software_audio;45
pub mod software_audio;45
pub mod sound_capture;46
pub mod sound_capture;@@ -201,6 +201,10 @@ impl Roster {
201
201
.unwrap_or_default()
202
202
}
203
203
204
pub fn screen_source_of(&self, mri: &str) -> Option<u32> {
205
self.members.iter().find(|member| member.mri == mri)?.screen_source
206
}
207
204
208
pub fn video_candidates(&self, own_mri: &str) -> Vec<(String, u32)> {
205
209
self.members
206
210
.iter()
@@ -201,6 +201,10 @@ impl Roster {201
.unwrap_or_default()201
.unwrap_or_default()202
}202
}203
203
204
pub fn screen_source_of(&self, mri: &str) -> Option<u32> {205
self.members.iter().find(|member| member.mri == mri)?.screen_source206
}207
204
pub fn video_candidates(&self, own_mri: &str) -> Vec<(String, u32)> {208
pub fn video_candidates(&self, own_mri: &str) -> Vec<(String, u32)> {205
self.members209
self.members206
.iter()210
.iter()@@ -436,7 +436,7 @@ fn signal_rtp_line(
436
436
for attribute in &source.attributes {
437
437
let value = attribute.value.as_deref().unwrap_or_default();
438
438
match attribute.name.as_str() {
439
"ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" => {}
439
"ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate" | "end-of-candidates" => {}
440
440
"rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
441
441
"fmtp" => {
442
442
let payload = value.split(' ').next().unwrap_or_default();
@@ -1070,6 +1070,17 @@ mod tests {
1070
1070
assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]);
1071
1071
}
1072
1072
1073
#[test]
1074
fn a_renegotiation_signals_only_the_placeholder_candidate() {
1075
let gathered = AUDIO_ONLY_OFFER.replace(
1076
"a=mid:0\r\n",
1077
"a=mid:0\r\na=candidate:1 1 udp 2121998079 192.0.2.1 45325 typ host generation 0 network-id 1\r\na=candidate:2 1 tcp 1518018303 2001:db8::1 47585 typ host tcptype passive generation 0 network-id 2\r\na=end-of-candidates\r\n",
1078
);
1079
let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter()).unwrap().sdp;
1080
let candidates: Vec<&str> = text.lines().filter(|line| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")).collect();
1081
assert_eq!(candidates, vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]);
1082
}
1083
1073
1084
#[test]
1074
1085
fn answer_candidates_lose_teams_extensions() {
1075
1086
assert_eq!(
@@ -436,7 +436,7 @@ fn signal_rtp_line(436
for attribute in &source.attributes {436
for attribute in &source.attributes {437
let value = attribute.value.as_deref().unwrap_or_default();437
let value = attribute.value.as_deref().unwrap_or_default();438
match attribute.name.as_str() {438
match attribute.name.as_str() {439
"ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" => {}439
"ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate" | "end-of-candidates" => {}440
"rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),440
"rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),441
"fmtp" => {441
"fmtp" => {442
let payload = value.split(' ').next().unwrap_or_default();442
let payload = value.split(' ').next().unwrap_or_default();@@ -1070,6 +1070,17 @@ mod tests {1070
assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]);1070
assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]);1071
}1071
}1072
1072
1073
#[test]1074
fn a_renegotiation_signals_only_the_placeholder_candidate() {1075
let gathered = AUDIO_ONLY_OFFER.replace(1076
"a=mid:0\r\n",1077
"a=mid:0\r\na=candidate:1 1 udp 2121998079 192.0.2.1 45325 typ host generation 0 network-id 1\r\na=candidate:2 1 tcp 1518018303 2001:db8::1 47585 typ host tcptype passive generation 0 network-id 2\r\na=end-of-candidates\r\n",1078
);1079
let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter()).unwrap().sdp;1080
let candidates: Vec<&str> = text.lines().filter(|line| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")).collect();1081
assert_eq!(candidates, vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]);1082
}1083
1073
#[test]1084
#[test]1074
fn answer_candidates_lose_teams_extensions() {1085
fn answer_candidates_lose_teams_extensions() {1075
assert_eq!(1086
assert_eq!(@@ -0,0 +1,243 @@
1
use std::collections::{BTreeMap, HashMap};
2
3
use serde_json::Value;
4
5
const MACROBLOCK: u32 = 16;
6
const FPS_UNIT: f64 = 100.0;
7
const BITRATE_UNIT: u64 = 1200;
8
const SCALE_STEP: f64 = 1.01;
9
const MAX_SCALE: f64 = 16.0;
10
pub const KEYFRAME_NUDGE: f64 = 1.1;
11
const KNOWN_KEYS: [&str; 10] =
12
["max-fs", "max-fps", "max-mbps", "max-br", "KeyFrame", "profile-level-id", "rid", "ssrc", "sequence-number", "packetization-mode"];
13
14
/// One layer of a mixer `controlVideoStreaming` request (VDCLC) for what we send.
15
#[derive(Debug, Clone, Default, PartialEq)]
16
pub struct SendLimit {
17
pub max_fs: Option<u32>,
18
pub max_mbps: Option<u32>,
19
pub max_fps: Option<f64>,
20
pub max_bitrate: Option<u64>,
21
pub keyframe: bool,
22
}
23
24
#[derive(Debug, Clone, Default, PartialEq)]
25
pub struct SendRequest {
26
pub source_id: Option<i64>,
27
pub sequence: Option<i64>,
28
pub limits: Vec<SendLimit>,
29
pub shape: String,
30
}
31
32
#[derive(Debug, Clone, Copy, PartialEq)]
33
pub struct EncoderLimits {
34
pub scale_down_by: f64,
35
pub max_framerate: Option<f64>,
36
pub max_bitrate: Option<u64>,
37
}
38
39
fn text_of(value: &Value) -> Option<String> {
40
match value {
41
Value::String(text) => Some(text.clone()),
42
Value::Number(number) => Some(number.to_string()),
43
Value::Bool(flag) => Some(u8::from(*flag).to_string()),
44
_ => None,
45
}
46
}
47
48
fn pairs(value: &Value) -> BTreeMap<String, String> {
49
match value {
50
Value::String(text) => text
51
.split(';')
52
.filter_map(|pair| pair.split_once('='))
53
.map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned()))
54
.collect(),
55
Value::Object(map) => map.iter().filter_map(|(key, value)| Some((key.clone(), text_of(value)?))).collect(),
56
_ => BTreeMap::new(),
57
}
58
}
59
60
fn limit_from(parameters: &BTreeMap<String, String>) -> SendLimit {
61
let number = |key: &str| parameters.get(key).and_then(|value| value.parse::<f64>().ok());
62
SendLimit {
63
max_fs: number("max-fs").map(|value| value as u32),
64
max_mbps: number("max-mbps").map(|value| value as u32),
65
max_fps: number("max-fps").map(|value| value / FPS_UNIT),
66
max_bitrate: number("max-br").map(|value| value as u64 * BITRATE_UNIT),
67
keyframe: number("KeyFrame").is_some_and(|value| value != 0.0),
68
}
69
}
70
71
fn describe(parameters: &BTreeMap<String, String>) -> String {
72
parameters
73
.iter()
74
.map(|(key, value)| if KNOWN_KEYS.contains(&key.as_str()) { format!("{key}={value}") } else { key.clone() })
75
.collect::<Vec<_>>()
76
.join(";")
77
}
78
79
pub fn parse_request(body: &Value) -> Option<SendRequest> {
80
let control = body.get("controlVideoStreaming").unwrap_or(body);
81
let info = match &control["controlInfo"] {
82
Value::Array(items) => items.first()?,
83
Value::Object(_) => &control["controlInfo"],
84
_ => return None,
85
};
86
let layers: Vec<BTreeMap<String, String>> = match (&info["fmtParamsList"], &info["fmtParams"]) {
87
(Value::Array(list), _) => list.iter().map(pairs).collect(),
88
(_, Value::Array(list)) => list.iter().map(pairs).collect(),
89
(_, single) if !single.is_null() => vec![pairs(single)],
90
_ => Vec::new(),
91
};
92
let mut fields: Vec<&str> = info.as_object().map(|map| map.keys().map(String::as_str).collect()).unwrap_or_default();
93
fields.sort_unstable();
94
let shape = format!(
95
"seq {} source {} control {} fields [{}] layers [{}]",
96
control["sequenceNumber"],
97
info["sourceId"],
98
info["control"].as_str().unwrap_or("-"),
99
fields.join(","),
100
layers.iter().map(describe).collect::<Vec<_>>().join(" | ")
101
);
102
let layer_sequence = layers.iter().find_map(|layer| layer.get("sequence-number")?.parse().ok());
103
Some(SendRequest {
104
source_id: info["sourceId"].as_i64(),
105
sequence: layer_sequence.or_else(|| control["sequenceNumber"].as_i64()),
106
limits: layers.iter().map(limit_from).collect(),
107
shape,
108
})
109
}
110
111
/// Drops requests older than the last one per source and repeats that change nothing and ask for no keyframe.
112
#[derive(Debug, Default)]
113
pub struct RequestFilter {
114
last_sequence: HashMap<Option<i64>, i64>,
115
last_limit: HashMap<Option<i64>, SendLimit>,
116
}
117
118
impl RequestFilter {
119
pub fn admit(&mut self, request: &SendRequest) -> Option<SendLimit> {
120
let limit = request.limits.first()?.clone();
121
if let Some(sequence) = request.sequence {
122
let last = self.last_sequence.entry(request.source_id).or_insert(i64::MIN);
123
if sequence < *last {
124
return None;
125
}
126
*last = sequence;
127
}
128
let unchanged = self.last_limit.get(&request.source_id) == Some(&limit);
129
self.last_limit.insert(request.source_id, limit.clone());
130
(!unchanged || limit.keyframe).then_some(limit)
131
}
132
}
133
134
fn macroblocks(width: f64, height: f64) -> u32 {
135
((width / f64::from(MACROBLOCK)).ceil() * (height / f64::from(MACROBLOCK)).ceil()) as u32
136
}
137
138
pub fn scale_for(width: u32, height: u32, max_fs: u32) -> f64 {
139
let (width, height) = (f64::from(width), f64::from(height));
140
if max_fs == 0 || macroblocks(width, height) <= max_fs {
141
return 1.0;
142
}
143
let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt();
144
while macroblocks(width / scale, height / scale) > max_fs && scale < MAX_SCALE {
145
scale *= SCALE_STEP;
146
}
147
scale
148
}
149
150
pub fn encoder_limits(limit: &SendLimit, frame: Option<(u32, u32)>) -> EncoderLimits {
151
let scale_down_by = match (limit.max_fs, frame) {
152
(Some(max_fs), Some((width, height))) => scale_for(width, height, max_fs),
153
_ => 1.0,
154
};
155
let rate_by_mbps = match (limit.max_mbps, frame) {
156
(Some(max_mbps), Some((width, height))) if max_mbps > 0 => {
157
let blocks = macroblocks(f64::from(width) / scale_down_by, f64::from(height) / scale_down_by).max(1);
158
Some(f64::from(max_mbps) / f64::from(blocks))
159
}
160
_ => None,
161
};
162
let max_framerate = match (limit.max_fps, rate_by_mbps) {
163
(Some(fps), Some(by_mbps)) => Some(fps.min(by_mbps)),
164
(fps, by_mbps) => fps.or(by_mbps),
165
}
166
.filter(|fps| *fps > 0.0)
167
.map(|fps| fps.max(1.0));
168
EncoderLimits { scale_down_by, max_framerate, max_bitrate: limit.max_bitrate.filter(|bitrate| *bitrate > 0) }
169
}
170
171
#[cfg(test)]
172
mod tests {
173
use serde_json::json;
174
175
use super::*;
176
177
#[test]
178
fn a_signaling_request_with_a_string_fmtp_is_read() {
179
let body = json!({"controlVideoStreaming": {"sequenceNumber": 12, "controlInfo": [
180
{"control": "start", "sourceId": 405, "streamMsid": 3, "fmtParams": "max-fs=920;max-mbps=27600;max-fps=3000;KeyFrame=1;x-secret=abc"}
181
]}});
182
let request = parse_request(&body).unwrap();
183
assert_eq!(request.source_id, Some(405));
184
assert_eq!(request.sequence, Some(12));
185
assert_eq!(request.limits, vec![SendLimit { max_fs: Some(920), max_mbps: Some(27600), max_fps: Some(30.0), max_bitrate: None, keyframe: true }]);
186
assert_eq!(
187
request.shape,
188
"seq 12 source 405 control start fields [control,fmtParams,sourceId,streamMsid] layers [KeyFrame=1;max-fps=3000;max-fs=920;max-mbps=27600;x-secret]"
189
);
190
}
191
192
#[test]
193
fn lists_objects_and_a_bare_control_info_are_read_too() {
194
let listed = json!({"controlVideoStreaming": {"sequenceNumber": 1, "controlInfo": [
195
{"sourceId": 405, "fmtParamsList": ["max-fs=3600;max-br=1500", "max-fs=920"]}
196
]}});
197
let request = parse_request(&listed).unwrap();
198
assert_eq!(request.limits.len(), 2);
199
assert_eq!(request.limits[0].max_bitrate, Some(1_800_000));
200
let objects = json!({"sequenceNumber": 2, "controlInfo": {"sourceId": 415, "fmtParams": [{"max-fs": 8160, "max-fps": 1500}]}});
201
let request = parse_request(&objects).unwrap();
202
assert_eq!(request.source_id, Some(415));
203
assert_eq!(request.limits[0].max_fs, Some(8160));
204
assert_eq!(request.limits[0].max_fps, Some(15.0));
205
assert!(parse_request(&json!({"other": 1})).is_none());
206
}
207
208
#[test]
209
fn stale_and_repeated_requests_are_dropped_unless_a_keyframe_is_asked() {
210
let request = |sequence: i64, fmtp: &str| {
211
parse_request(&json!({"sequenceNumber": sequence, "controlInfo": [{"sourceId": 405, "fmtParams": fmtp}]})).unwrap()
212
};
213
let mut filter = RequestFilter::default();
214
assert!(filter.admit(&request(5, "max-fs=920")).is_some());
215
assert!(filter.admit(&request(6, "max-fs=920")).is_none());
216
assert!(filter.admit(&request(4, "max-fs=3600")).is_none());
217
assert!(filter.admit(&request(7, "max-fs=920;KeyFrame=1")).is_some());
218
assert_eq!(filter.admit(&request(8, "max-fs=3600")).unwrap().max_fs, Some(3600));
219
}
220
221
#[test]
222
fn the_scale_fits_the_frame_into_max_fs() {
223
assert_eq!(scale_for(1280, 720, 3600), 1.0);
224
let scale = scale_for(1280, 720, 920);
225
assert!(macroblocks(1280.0 / scale, 720.0 / scale) <= 920);
226
assert!(scale < 2.2, "{scale}");
227
let scale = scale_for(960, 720, 920);
228
assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920);
229
assert_eq!(scale_for(1280, 720, 0), 1.0);
230
}
231
232
#[test]
233
fn frame_rate_follows_max_fps_and_max_mbps() {
234
let limit = SendLimit { max_fs: Some(920), max_mbps: Some(13_800), max_fps: Some(30.0), max_bitrate: Some(600_000), keyframe: false };
235
let limits = encoder_limits(&limit, Some((1280, 720)));
236
assert!(limits.scale_down_by > 1.0);
237
assert!(limits.max_framerate.unwrap() <= 30.0 && limits.max_framerate.unwrap() >= 14.0);
238
assert_eq!(limits.max_bitrate, Some(600_000));
239
let unknown_frame = encoder_limits(&limit, None);
240
assert_eq!(unknown_frame.scale_down_by, 1.0);
241
assert_eq!(unknown_frame.max_framerate, Some(30.0));
242
}
243
}
@@ -0,0 +1,243 @@1
use std::collections::{BTreeMap, HashMap};2
3
use serde_json::Value;4
5
const MACROBLOCK: u32 = 16;6
const FPS_UNIT: f64 = 100.0;7
const BITRATE_UNIT: u64 = 1200;8
const SCALE_STEP: f64 = 1.01;9
const MAX_SCALE: f64 = 16.0;10
pub const KEYFRAME_NUDGE: f64 = 1.1;11
const KNOWN_KEYS: [&str; 10] =12
["max-fs", "max-fps", "max-mbps", "max-br", "KeyFrame", "profile-level-id", "rid", "ssrc", "sequence-number", "packetization-mode"];13
14
/// One layer of a mixer `controlVideoStreaming` request (VDCLC) for what we send.15
#[derive(Debug, Clone, Default, PartialEq)]16
pub struct SendLimit {17
pub max_fs: Option<u32>,18
pub max_mbps: Option<u32>,19
pub max_fps: Option<f64>,20
pub max_bitrate: Option<u64>,21
pub keyframe: bool,22
}23
24
#[derive(Debug, Clone, Default, PartialEq)]25
pub struct SendRequest {26
pub source_id: Option<i64>,27
pub sequence: Option<i64>,28
pub limits: Vec<SendLimit>,29
pub shape: String,30
}31
32
#[derive(Debug, Clone, Copy, PartialEq)]33
pub struct EncoderLimits {34
pub scale_down_by: f64,35
pub max_framerate: Option<f64>,36
pub max_bitrate: Option<u64>,37
}38
39
fn text_of(value: &Value) -> Option<String> {40
match value {41
Value::String(text) => Some(text.clone()),42
Value::Number(number) => Some(number.to_string()),43
Value::Bool(flag) => Some(u8::from(*flag).to_string()),44
_ => None,45
}46
}47
48
fn pairs(value: &Value) -> BTreeMap<String, String> {49
match value {50
Value::String(text) => text51
.split(';')52
.filter_map(|pair| pair.split_once('='))53
.map(|(key, value)| (key.trim().to_owned(), value.trim().to_owned()))54
.collect(),55
Value::Object(map) => map.iter().filter_map(|(key, value)| Some((key.clone(), text_of(value)?))).collect(),56
_ => BTreeMap::new(),57
}58
}59
60
fn limit_from(parameters: &BTreeMap<String, String>) -> SendLimit {61
let number = |key: &str| parameters.get(key).and_then(|value| value.parse::<f64>().ok());62
SendLimit {63
max_fs: number("max-fs").map(|value| value as u32),64
max_mbps: number("max-mbps").map(|value| value as u32),65
max_fps: number("max-fps").map(|value| value / FPS_UNIT),66
max_bitrate: number("max-br").map(|value| value as u64 * BITRATE_UNIT),67
keyframe: number("KeyFrame").is_some_and(|value| value != 0.0),68
}69
}70
71
fn describe(parameters: &BTreeMap<String, String>) -> String {72
parameters73
.iter()74
.map(|(key, value)| if KNOWN_KEYS.contains(&key.as_str()) { format!("{key}={value}") } else { key.clone() })75
.collect::<Vec<_>>()76
.join(";")77
}78
79
pub fn parse_request(body: &Value) -> Option<SendRequest> {80
let control = body.get("controlVideoStreaming").unwrap_or(body);81
let info = match &control["controlInfo"] {82
Value::Array(items) => items.first()?,83
Value::Object(_) => &control["controlInfo"],84
_ => return None,85
};86
let layers: Vec<BTreeMap<String, String>> = match (&info["fmtParamsList"], &info["fmtParams"]) {87
(Value::Array(list), _) => list.iter().map(pairs).collect(),88
(_, Value::Array(list)) => list.iter().map(pairs).collect(),89
(_, single) if !single.is_null() => vec![pairs(single)],90
_ => Vec::new(),91
};92
let mut fields: Vec<&str> = info.as_object().map(|map| map.keys().map(String::as_str).collect()).unwrap_or_default();93
fields.sort_unstable();94
let shape = format!(95
"seq {} source {} control {} fields [{}] layers [{}]",96
control["sequenceNumber"],97
info["sourceId"],98
info["control"].as_str().unwrap_or("-"),99
fields.join(","),100
layers.iter().map(describe).collect::<Vec<_>>().join(" | ")101
);102
let layer_sequence = layers.iter().find_map(|layer| layer.get("sequence-number")?.parse().ok());103
Some(SendRequest {104
source_id: info["sourceId"].as_i64(),105
sequence: layer_sequence.or_else(|| control["sequenceNumber"].as_i64()),106
limits: layers.iter().map(limit_from).collect(),107
shape,108
})109
}110
111
/// Drops requests older than the last one per source and repeats that change nothing and ask for no keyframe.112
#[derive(Debug, Default)]113
pub struct RequestFilter {114
last_sequence: HashMap<Option<i64>, i64>,115
last_limit: HashMap<Option<i64>, SendLimit>,116
}117
118
impl RequestFilter {119
pub fn admit(&mut self, request: &SendRequest) -> Option<SendLimit> {120
let limit = request.limits.first()?.clone();121
if let Some(sequence) = request.sequence {122
let last = self.last_sequence.entry(request.source_id).or_insert(i64::MIN);123
if sequence < *last {124
return None;125
}126
*last = sequence;127
}128
let unchanged = self.last_limit.get(&request.source_id) == Some(&limit);129
self.last_limit.insert(request.source_id, limit.clone());130
(!unchanged || limit.keyframe).then_some(limit)131
}132
}133
134
fn macroblocks(width: f64, height: f64) -> u32 {135
((width / f64::from(MACROBLOCK)).ceil() * (height / f64::from(MACROBLOCK)).ceil()) as u32136
}137
138
pub fn scale_for(width: u32, height: u32, max_fs: u32) -> f64 {139
let (width, height) = (f64::from(width), f64::from(height));140
if max_fs == 0 || macroblocks(width, height) <= max_fs {141
return 1.0;142
}143
let mut scale = (f64::from(macroblocks(width, height)) / f64::from(max_fs)).sqrt();144
while macroblocks(width / scale, height / scale) > max_fs && scale < MAX_SCALE {145
scale *= SCALE_STEP;146
}147
scale148
}149
150
pub fn encoder_limits(limit: &SendLimit, frame: Option<(u32, u32)>) -> EncoderLimits {151
let scale_down_by = match (limit.max_fs, frame) {152
(Some(max_fs), Some((width, height))) => scale_for(width, height, max_fs),153
_ => 1.0,154
};155
let rate_by_mbps = match (limit.max_mbps, frame) {156
(Some(max_mbps), Some((width, height))) if max_mbps > 0 => {157
let blocks = macroblocks(f64::from(width) / scale_down_by, f64::from(height) / scale_down_by).max(1);158
Some(f64::from(max_mbps) / f64::from(blocks))159
}160
_ => None,161
};162
let max_framerate = match (limit.max_fps, rate_by_mbps) {163
(Some(fps), Some(by_mbps)) => Some(fps.min(by_mbps)),164
(fps, by_mbps) => fps.or(by_mbps),165
}166
.filter(|fps| *fps > 0.0)167
.map(|fps| fps.max(1.0));168
EncoderLimits { scale_down_by, max_framerate, max_bitrate: limit.max_bitrate.filter(|bitrate| *bitrate > 0) }169
}170
171
#[cfg(test)]172
mod tests {173
use serde_json::json;174
175
use super::*;176
177
#[test]178
fn a_signaling_request_with_a_string_fmtp_is_read() {179
let body = json!({"controlVideoStreaming": {"sequenceNumber": 12, "controlInfo": [180
{"control": "start", "sourceId": 405, "streamMsid": 3, "fmtParams": "max-fs=920;max-mbps=27600;max-fps=3000;KeyFrame=1;x-secret=abc"}181
]}});182
let request = parse_request(&body).unwrap();183
assert_eq!(request.source_id, Some(405));184
assert_eq!(request.sequence, Some(12));185
assert_eq!(request.limits, vec![SendLimit { max_fs: Some(920), max_mbps: Some(27600), max_fps: Some(30.0), max_bitrate: None, keyframe: true }]);186
assert_eq!(187
request.shape,188
"seq 12 source 405 control start fields [control,fmtParams,sourceId,streamMsid] layers [KeyFrame=1;max-fps=3000;max-fs=920;max-mbps=27600;x-secret]"189
);190
}191
192
#[test]193
fn lists_objects_and_a_bare_control_info_are_read_too() {194
let listed = json!({"controlVideoStreaming": {"sequenceNumber": 1, "controlInfo": [195
{"sourceId": 405, "fmtParamsList": ["max-fs=3600;max-br=1500", "max-fs=920"]}196
]}});197
let request = parse_request(&listed).unwrap();198
assert_eq!(request.limits.len(), 2);199
assert_eq!(request.limits[0].max_bitrate, Some(1_800_000));200
let objects = json!({"sequenceNumber": 2, "controlInfo": {"sourceId": 415, "fmtParams": [{"max-fs": 8160, "max-fps": 1500}]}});201
let request = parse_request(&objects).unwrap();202
assert_eq!(request.source_id, Some(415));203
assert_eq!(request.limits[0].max_fs, Some(8160));204
assert_eq!(request.limits[0].max_fps, Some(15.0));205
assert!(parse_request(&json!({"other": 1})).is_none());206
}207
208
#[test]209
fn stale_and_repeated_requests_are_dropped_unless_a_keyframe_is_asked() {210
let request = |sequence: i64, fmtp: &str| {211
parse_request(&json!({"sequenceNumber": sequence, "controlInfo": [{"sourceId": 405, "fmtParams": fmtp}]})).unwrap()212
};213
let mut filter = RequestFilter::default();214
assert!(filter.admit(&request(5, "max-fs=920")).is_some());215
assert!(filter.admit(&request(6, "max-fs=920")).is_none());216
assert!(filter.admit(&request(4, "max-fs=3600")).is_none());217
assert!(filter.admit(&request(7, "max-fs=920;KeyFrame=1")).is_some());218
assert_eq!(filter.admit(&request(8, "max-fs=3600")).unwrap().max_fs, Some(3600));219
}220
221
#[test]222
fn the_scale_fits_the_frame_into_max_fs() {223
assert_eq!(scale_for(1280, 720, 3600), 1.0);224
let scale = scale_for(1280, 720, 920);225
assert!(macroblocks(1280.0 / scale, 720.0 / scale) <= 920);226
assert!(scale < 2.2, "{scale}");227
let scale = scale_for(960, 720, 920);228
assert!(macroblocks(960.0 / scale, 720.0 / scale) <= 920);229
assert_eq!(scale_for(1280, 720, 0), 1.0);230
}231
232
#[test]233
fn frame_rate_follows_max_fps_and_max_mbps() {234
let limit = SendLimit { max_fs: Some(920), max_mbps: Some(13_800), max_fps: Some(30.0), max_bitrate: Some(600_000), keyframe: false };235
let limits = encoder_limits(&limit, Some((1280, 720)));236
assert!(limits.scale_down_by > 1.0);237
assert!(limits.max_framerate.unwrap() <= 30.0 && limits.max_framerate.unwrap() >= 14.0);238
assert_eq!(limits.max_bitrate, Some(600_000));239
let unknown_frame = encoder_limits(&limit, None);240
assert_eq!(unknown_frame.scale_down_by, 1.0);241
assert_eq!(unknown_frame.max_framerate, Some(30.0));242
}243
}@@ -132,6 +132,7 @@ pub enum CallEvent {
132
132
MediaAnswer(MediaAnswer),
133
133
MediaRenegotiation(Renegotiation),
134
134
Speakers(Vec<u32>),
135
ControlVideoStreaming(Value),
135
136
AddParticipantSuccess(Value),
136
137
AddParticipantFailure(Value),
137
138
Reactions(Vec<ReactionEvent>),
@@ -154,6 +155,7 @@ impl CallEvent {
154
155
CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
155
156
CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
156
157
CallEvent::Speakers(_) => "call/speakers".into(),
158
CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
157
159
CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),
158
160
CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
159
161
CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
@@ -188,6 +190,7 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
188
190
("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
189
191
("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
190
192
("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
193
("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body),
191
194
("call", "end") => CallEvent::End(call_end(&body)),
192
195
(scope, event) => CallEvent::Other {
193
196
scope: scope.to_owned(),
@@ -451,6 +454,8 @@ mod tests {
451
454
assert!(matches!(share, CallEvent::ContentShareUpdate(_)));
452
455
let (_, ended) = classify("callAgent/abc/1/conversation/contentSharingEnd/", Value::Null).unwrap();
453
456
assert!(matches!(ended, CallEvent::ContentShareEnd(_)));
457
let (_, control) = classify("callAgent/abc/1/call/controlVideoStreaming/", json!({"controlVideoStreaming": {}})).unwrap();
458
assert_eq!(control.name(), "call/controlVideoStreaming");
454
459
let (_, accepted) = classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap();
455
460
assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted));
456
461
let (_, completed) = classify("callAgent/abc/1/call/transferCompletion/", json!({"transferCompletion": {"code": 0}})).unwrap();
@@ -132,6 +132,7 @@ pub enum CallEvent {132
MediaAnswer(MediaAnswer),132
MediaAnswer(MediaAnswer),133
MediaRenegotiation(Renegotiation),133
MediaRenegotiation(Renegotiation),134
Speakers(Vec<u32>),134
Speakers(Vec<u32>),135
ControlVideoStreaming(Value),135
AddParticipantSuccess(Value),136
AddParticipantSuccess(Value),136
AddParticipantFailure(Value),137
AddParticipantFailure(Value),137
Reactions(Vec<ReactionEvent>),138
Reactions(Vec<ReactionEvent>),@@ -154,6 +155,7 @@ impl CallEvent {154
CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),155
CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),155
CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),156
CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),156
CallEvent::Speakers(_) => "call/speakers".into(),157
CallEvent::Speakers(_) => "call/speakers".into(),158
CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),157
CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),159
CallEvent::AddParticipantSuccess(_) => "conversation/addParticipantSuccess".into(),158
CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),160
CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),159
CallEvent::Reactions(_) => "conversation/receiveMessage".into(),161
CallEvent::Reactions(_) => "conversation/receiveMessage".into(),@@ -188,6 +190,7 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {188
("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),190
("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),189
("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),191
("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),190
("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),192
("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),193
("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body),191
("call", "end") => CallEvent::End(call_end(&body)),194
("call", "end") => CallEvent::End(call_end(&body)),192
(scope, event) => CallEvent::Other {195
(scope, event) => CallEvent::Other {193
scope: scope.to_owned(),196
scope: scope.to_owned(),@@ -451,6 +454,8 @@ mod tests {451
assert!(matches!(share, CallEvent::ContentShareUpdate(_)));454
assert!(matches!(share, CallEvent::ContentShareUpdate(_)));452
let (_, ended) = classify("callAgent/abc/1/conversation/contentSharingEnd/", Value::Null).unwrap();455
let (_, ended) = classify("callAgent/abc/1/conversation/contentSharingEnd/", Value::Null).unwrap();453
assert!(matches!(ended, CallEvent::ContentShareEnd(_)));456
assert!(matches!(ended, CallEvent::ContentShareEnd(_)));457
let (_, control) = classify("callAgent/abc/1/call/controlVideoStreaming/", json!({"controlVideoStreaming": {}})).unwrap();458
assert_eq!(control.name(), "call/controlVideoStreaming");454
let (_, accepted) = classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap();459
let (_, accepted) = classify("callAgent/abc/1/call/transferAcceptance/", Value::Null).unwrap();455
assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted));460
assert_eq!(accepted, CallEvent::Transfer(TransferEvent::Accepted));456
let (_, completed) = classify("callAgent/abc/1/call/transferCompletion/", json!({"transferCompletion": {"code": 0}})).unwrap();461
let (_, completed) = classify("callAgent/abc/1/call/transferCompletion/", json!({"transferCompletion": {"code": 0}})).unwrap();@@ -1,5 +1,5 @@
1
1
use std::sync::Arc;
2
use std::sync::atomic::{AtomicU32, Ordering};
2
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};
3
3
use std::time::{Instant, SystemTime, UNIX_EPOCH};
4
4
5
5
use libwebrtc::media_stream_track::MediaStreamTrack;
@@ -7,7 +7,7 @@ use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7
7
use libwebrtc::rtp_parameters::DegradationPreference;
8
8
use libwebrtc::rtp_sender::RtpSender;
9
9
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
10
use libwebrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};
10
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
11
11
use libwebrtc::video_source::VideoResolution;
12
12
use libwebrtc::video_source::native::NativeVideoSource;
13
13
use libwebrtc::video_track::RtcVideoTrack;
@@ -22,6 +22,7 @@ use crate::control::CallUpdate;
22
22
use crate::devices::DeviceChoice;
23
23
use crate::error::{Error, Result};
24
24
use crate::screen::{ShareSource, start_screen_capture};
25
use crate::send_control::{EncoderLimits, KEYFRAME_NUDGE, SendLimit, encoder_limits};
25
26
use crate::standout::StandoutOverlay;
26
27
use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};
27
28
use crate::video_layout::VideoLines;
@@ -61,6 +62,7 @@ pub struct LocalSink {
61
62
self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,
62
63
mirror: Option<Arc<BlurSettings>>,
63
64
standout: Option<StandoutOverlay>,
65
frame_size: Option<Arc<AtomicU64>>,
64
66
}
65
67
66
68
impl LocalSink {
@@ -69,7 +71,12 @@ impl LocalSink {
69
71
let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };
70
72
(hub, key, FrameGate::new(fps))
71
73
});
72
LocalSink { source, self_view, mirror: None, standout: None }
74
LocalSink { source, self_view, mirror: None, standout: None, frame_size: None }
75
}
76
77
pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {
78
self.frame_size = Some(frame_size);
79
self
73
80
}
74
81
75
82
pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {
@@ -87,6 +94,9 @@ impl LocalSink {
87
94
Some(overlay) => overlay.apply(buffer),
88
95
None => buffer,
89
96
};
97
if let Some(frame_size) = &self.frame_size {
98
frame_size.store(pack_size(buffer.width(), buffer.height()), Ordering::Relaxed);
99
}
90
100
let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);
91
101
frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);
92
102
self.source.capture_frame(&frame);
@@ -102,10 +112,27 @@ impl LocalSink {
102
112
}
103
113
}
104
114
115
fn pack_size(width: u32, height: u32) -> u64 {
116
(u64::from(width) << 32) | u64::from(height)
117
}
118
119
fn unpack_size(packed: u64) -> Option<(u32, u32)> {
120
let (width, height) = ((packed >> 32) as u32, packed as u32);
121
(width > 0 && height > 0).then_some((width, height))
122
}
123
124
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125
pub enum SendSource {
126
Camera,
127
Screen,
128
}
129
105
130
struct Outgoing {
106
131
source: NativeVideoSource,
107
132
track: RtcVideoTrack,
108
133
capture: Option<Capture>,
134
frame_size: Arc<AtomicU64>,
135
limits: Option<EncoderLimits>,
109
136
}
110
137
111
138
impl Outgoing {
@@ -113,7 +140,7 @@ impl Outgoing {
113
140
let (width, height) = kind.size();
114
141
let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);
115
142
let track = factory.create_video_track(label, source.clone());
116
Outgoing { source, track, capture: None }
143
Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), limits: None }
117
144
}
118
145
}
119
146
@@ -171,6 +198,45 @@ impl LocalVideo {
171
198
sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
172
199
}
173
200
201
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {
202
let lines = self.lines.as_ref()?;
203
match source {
204
SendSource::Camera => Some(lines.camera.sender()),
205
SendSource::Screen => lines.share.as_ref().map(|share| share.sender()),
206
}
207
}
208
209
pub fn apply_send_limit(&mut self, source: SendSource, limit: &SendLimit) -> Result<Option<EncoderLimits>> {
210
let sending = match source {
211
SendSource::Camera => self.camera_on(),
212
SendSource::Screen => self.sharing(),
213
};
214
let Some(sender) = self.sender_of(source).filter(|_| sending) else { return Ok(None) };
215
let outgoing = match source {
216
SendSource::Camera => &mut self.camera,
217
SendSource::Screen => &mut self.screen,
218
};
219
let limits = encoder_limits(limit, unpack_size(outgoing.frame_size.load(Ordering::Relaxed)));
220
outgoing.limits = Some(limits);
221
if limit.keyframe {
222
Self::set_limits(&sender, &limits, KEYFRAME_NUDGE)?;
223
}
224
Self::set_limits(&sender, &limits, 1.0)?;
225
Ok(Some(limits))
226
}
227
228
fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {
229
let mut parameters = sender.parameters();
230
for encoding in &mut parameters.encodings {
231
encoding.scale_resolution_down_by = Some(limits.scale_down_by * nudge);
232
if let Some(framerate) = limits.max_framerate {
233
encoding.max_framerate = Some(framerate);
234
}
235
encoding.max_bitrate = limits.max_bitrate;
236
}
237
sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))
238
}
239
174
240
pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {
175
241
self.blur.set_picture(picture);
176
242
self.blur.set_enabled(enabled);
@@ -233,7 +299,9 @@ impl LocalVideo {
233
299
}
234
300
235
301
fn camera_sink(&self) -> LocalSink {
236
LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera))).mirrored_by(self.blur.clone())
302
LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))
303
.mirrored_by(self.blur.clone())
304
.reporting_size(self.camera.frame_size.clone())
237
305
}
238
306
239
307
fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {
@@ -275,7 +343,9 @@ impl LocalVideo {
275
343
return Err(Error::Webrtc("video is switched off".into()));
276
344
}
277
345
self.screen.capture = None;
278
let mut sink = LocalSink::new(self.screen.source.clone(), None).with_standout(self.blur.clone());
346
let mut sink = LocalSink::new(self.screen.source.clone(), None)
347
.with_standout(self.blur.clone())
348
.reporting_size(self.screen.frame_size.clone());
279
349
let capture = match self.mode {
280
350
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),
281
351
_ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,
@@ -303,6 +373,12 @@ impl LocalVideo {
303
373
mod tests {
304
374
use super::*;
305
375
376
#[test]
377
fn frame_sizes_survive_packing() {
378
assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));
379
assert_eq!(unpack_size(0), None);
380
}
381
306
382
#[test]
307
383
fn the_video_mode_follows_the_environment_value() {
308
384
assert_eq!(VideoMode::parse(None), VideoMode::Platform);
@@ -1,5 +1,5 @@1
use std::sync::Arc;1
use std::sync::Arc;2
use std::sync::atomic::{AtomicU32, Ordering};2
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};3
use std::time::{Instant, SystemTime, UNIX_EPOCH};3
use std::time::{Instant, SystemTime, UNIX_EPOCH};4
4
5
use libwebrtc::media_stream_track::MediaStreamTrack;5
use libwebrtc::media_stream_track::MediaStreamTrack;@@ -7,7 +7,7 @@ use libwebrtc::peer_connection_factory::PeerConnectionFactory;7
use libwebrtc::rtp_parameters::DegradationPreference;7
use libwebrtc::rtp_parameters::DegradationPreference;8
use libwebrtc::rtp_sender::RtpSender;8
use libwebrtc::rtp_sender::RtpSender;9
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;9
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;10
use libwebrtc::video_frame::{I420Buffer, VideoFrame, VideoRotation};10
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};11
use libwebrtc::video_source::VideoResolution;11
use libwebrtc::video_source::VideoResolution;12
use libwebrtc::video_source::native::NativeVideoSource;12
use libwebrtc::video_source::native::NativeVideoSource;13
use libwebrtc::video_track::RtcVideoTrack;13
use libwebrtc::video_track::RtcVideoTrack;@@ -22,6 +22,7 @@ use crate::control::CallUpdate;22
use crate::devices::DeviceChoice;22
use crate::devices::DeviceChoice;23
use crate::error::{Error, Result};23
use crate::error::{Error, Result};24
use crate::screen::{ShareSource, start_screen_capture};24
use crate::screen::{ShareSource, start_screen_capture};25
use crate::send_control::{EncoderLimits, KEYFRAME_NUDGE, SendLimit, encoder_limits};25
use crate::standout::StandoutOverlay;26
use crate::standout::StandoutOverlay;26
use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};27
use crate::video_frame::{FrameGate, PERSON_FPS, SCREEN_FPS, VideoHub, VideoKey, picture_from_i420};27
use crate::video_layout::VideoLines;28
use crate::video_layout::VideoLines;@@ -61,6 +62,7 @@ pub struct LocalSink {61
self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,62
self_view: Option<(Arc<VideoHub>, VideoKey, FrameGate)>,62
mirror: Option<Arc<BlurSettings>>,63
mirror: Option<Arc<BlurSettings>>,63
standout: Option<StandoutOverlay>,64
standout: Option<StandoutOverlay>,65
frame_size: Option<Arc<AtomicU64>>,64
}66
}65
67
66
impl LocalSink {68
impl LocalSink {@@ -69,7 +71,12 @@ impl LocalSink {69
let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };71
let fps = if matches!(key, VideoKey::LocalScreen) { SCREEN_FPS } else { PERSON_FPS };70
(hub, key, FrameGate::new(fps))72
(hub, key, FrameGate::new(fps))71
});73
});72
LocalSink { source, self_view, mirror: None, standout: None }74
LocalSink { source, self_view, mirror: None, standout: None, frame_size: None }75
}76
77
pub fn reporting_size(mut self, frame_size: Arc<AtomicU64>) -> Self {78
self.frame_size = Some(frame_size);79
self73
}80
}74
81
75
pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {82
pub fn mirrored_by(mut self, settings: Arc<BlurSettings>) -> Self {@@ -87,6 +94,9 @@ impl LocalSink {87
Some(overlay) => overlay.apply(buffer),94
Some(overlay) => overlay.apply(buffer),88
None => buffer,95
None => buffer,89
};96
};97
if let Some(frame_size) = &self.frame_size {98
frame_size.store(pack_size(buffer.width(), buffer.height()), Ordering::Relaxed);99
}90
let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);100
let mut frame = VideoFrame::new(VideoRotation::VideoRotation0, buffer);91
frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);101
frame.timestamp_us = SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_micros() as i64);92
self.source.capture_frame(&frame);102
self.source.capture_frame(&frame);@@ -102,10 +112,27 @@ impl LocalSink {102
}112
}103
}113
}104
114
115
fn pack_size(width: u32, height: u32) -> u64 {116
(u64::from(width) << 32) | u64::from(height)117
}118
119
fn unpack_size(packed: u64) -> Option<(u32, u32)> {120
let (width, height) = ((packed >> 32) as u32, packed as u32);121
(width > 0 && height > 0).then_some((width, height))122
}123
124
#[derive(Debug, Clone, Copy, PartialEq, Eq)]125
pub enum SendSource {126
Camera,127
Screen,128
}129
105
struct Outgoing {130
struct Outgoing {106
source: NativeVideoSource,131
source: NativeVideoSource,107
track: RtcVideoTrack,132
track: RtcVideoTrack,108
capture: Option<Capture>,133
capture: Option<Capture>,134
frame_size: Arc<AtomicU64>,135
limits: Option<EncoderLimits>,109
}136
}110
137
111
impl Outgoing {138
impl Outgoing {@@ -113,7 +140,7 @@ impl Outgoing {113
let (width, height) = kind.size();140
let (width, height) = kind.size();114
let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);141
let source = NativeVideoSource::new(VideoResolution { width, height }, screencast);115
let track = factory.create_video_track(label, source.clone());142
let track = factory.create_video_track(label, source.clone());116
Outgoing { source, track, capture: None }143
Outgoing { source, track, capture: None, frame_size: Arc::new(AtomicU64::new(0)), limits: None }117
}144
}118
}145
}119
146
@@ -171,6 +198,45 @@ impl LocalVideo {171
sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))198
sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))172
}199
}173
200
201
fn sender_of(&self, source: SendSource) -> Option<RtpSender> {202
let lines = self.lines.as_ref()?;203
match source {204
SendSource::Camera => Some(lines.camera.sender()),205
SendSource::Screen => lines.share.as_ref().map(|share| share.sender()),206
}207
}208
209
pub fn apply_send_limit(&mut self, source: SendSource, limit: &SendLimit) -> Result<Option<EncoderLimits>> {210
let sending = match source {211
SendSource::Camera => self.camera_on(),212
SendSource::Screen => self.sharing(),213
};214
let Some(sender) = self.sender_of(source).filter(|_| sending) else { return Ok(None) };215
let outgoing = match source {216
SendSource::Camera => &mut self.camera,217
SendSource::Screen => &mut self.screen,218
};219
let limits = encoder_limits(limit, unpack_size(outgoing.frame_size.load(Ordering::Relaxed)));220
outgoing.limits = Some(limits);221
if limit.keyframe {222
Self::set_limits(&sender, &limits, KEYFRAME_NUDGE)?;223
}224
Self::set_limits(&sender, &limits, 1.0)?;225
Ok(Some(limits))226
}227
228
fn set_limits(sender: &RtpSender, limits: &EncoderLimits, nudge: f64) -> Result<()> {229
let mut parameters = sender.parameters();230
for encoding in &mut parameters.encodings {231
encoding.scale_resolution_down_by = Some(limits.scale_down_by * nudge);232
if let Some(framerate) = limits.max_framerate {233
encoding.max_framerate = Some(framerate);234
}235
encoding.max_bitrate = limits.max_bitrate;236
}237
sender.set_parameters(parameters).map_err(|error| Error::Webrtc(error.to_string()))238
}239
174
pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {240
pub fn set_background(&self, enabled: bool, picture: Option<Arc<BackgroundPicture>>) {175
self.blur.set_picture(picture);241
self.blur.set_picture(picture);176
self.blur.set_enabled(enabled);242
self.blur.set_enabled(enabled);@@ -233,7 +299,9 @@ impl LocalVideo {233
}299
}234
300
235
fn camera_sink(&self) -> LocalSink {301
fn camera_sink(&self) -> LocalSink {236
LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera))).mirrored_by(self.blur.clone())302
LocalSink::new(self.camera.source.clone(), Some((self.hub.clone(), VideoKey::LocalCamera)))303
.mirrored_by(self.blur.clone())304
.reporting_size(self.camera.frame_size.clone())237
}305
}238
306
239
fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {307
fn report_failure(&self, what: &'static str) -> impl FnOnce(String) + Send + 'static {@@ -275,7 +343,9 @@ impl LocalVideo {275
return Err(Error::Webrtc("video is switched off".into()));343
return Err(Error::Webrtc("video is switched off".into()));276
}344
}277
self.screen.capture = None;345
self.screen.capture = None;278
let mut sink = LocalSink::new(self.screen.source.clone(), None).with_standout(self.blur.clone());346
let mut sink = LocalSink::new(self.screen.source.clone(), None)347
.with_standout(self.blur.clone())348
.reporting_size(self.screen.frame_size.clone());279
let capture = match self.mode {349
let capture = match self.mode {280
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),350
VideoMode::Pattern => Capture::Task(spawn_pattern(sink, PatternKind::Screen, None)),281
_ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,351
_ => start_screen_capture(source.clone(), self.share_fps.clone(), move |buffer| sink.push(buffer), self.report_failure("Screen share"))?,@@ -303,6 +373,12 @@ impl LocalVideo {303
mod tests {373
mod tests {304
use super::*;374
use super::*;305
375
376
#[test]377
fn frame_sizes_survive_packing() {378
assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));379
assert_eq!(unpack_size(0), None);380
}381
306
#[test]382
#[test]307
fn the_video_mode_follows_the_environment_value() {383
fn the_video_mode_follows_the_environment_value() {308
assert_eq!(VideoMode::parse(None), VideoMode::Platform);384
assert_eq!(VideoMode::parse(None), VideoMode::Platform);@@ -8,3 +8,4 @@ Upstream: crates.io `webrtc-sys 0.3.48` (livekit/rust-sdks). Wired in via `[patc
8
8
|---|---|---|
9
9
| `src/adm_proxy.cpp`, `include/livekit/adm_proxy.h` | `Init()` re-inits terminated sub ADMs; `EnsurePlatformAdmCreated()` re-inits a terminated platform ADM; `InitPlatformAdm()` replays transport, devices, observer, stereo; `Terminate()` stops synthetic playout and clears `playing_` / `recording_` | `WebRtcVoiceEngine::Terminate()` terminates the ADM after every call, `Init()` was a no-op: from the second call on 0 devices, no mic, no sound |
10
10
| `src/adm_proxy.cpp` | `BuiltInAECIsAvailable()` returns false on Windows | the voice capture DMO fails `StartRecording` ("Playout must be started before recording") when no remote audio plays yet - mic silent for the whole call (seen in the app log 2026-10-13) |
11
| `src/adm_proxy.cpp`, `include/livekit/adm_proxy.h` | `SetPlayoutDevice` / `SetRecordingDevice(WindowsDeviceType)` turn `kDefaultCommunicationDevice` into `kDefaultDevice` | `WebRtcVoiceEngine::Init` selects the communications default at every call start; the app's "Default device" means the Windows default device (seen 2026-10-14: speaker came up on the communications default, user picked the default device by hand every call) |
@@ -8,3 +8,4 @@ Upstream: crates.io `webrtc-sys 0.3.48` (livekit/rust-sdks). Wired in via `[patc8
|---|---|---|8
|---|---|---|9
| `src/adm_proxy.cpp`, `include/livekit/adm_proxy.h` | `Init()` re-inits terminated sub ADMs; `EnsurePlatformAdmCreated()` re-inits a terminated platform ADM; `InitPlatformAdm()` replays transport, devices, observer, stereo; `Terminate()` stops synthetic playout and clears `playing_` / `recording_` | `WebRtcVoiceEngine::Terminate()` terminates the ADM after every call, `Init()` was a no-op: from the second call on 0 devices, no mic, no sound |9
| `src/adm_proxy.cpp`, `include/livekit/adm_proxy.h` | `Init()` re-inits terminated sub ADMs; `EnsurePlatformAdmCreated()` re-inits a terminated platform ADM; `InitPlatformAdm()` replays transport, devices, observer, stereo; `Terminate()` stops synthetic playout and clears `playing_` / `recording_` | `WebRtcVoiceEngine::Terminate()` terminates the ADM after every call, `Init()` was a no-op: from the second call on 0 devices, no mic, no sound |10
| `src/adm_proxy.cpp` | `BuiltInAECIsAvailable()` returns false on Windows | the voice capture DMO fails `StartRecording` ("Playout must be started before recording") when no remote audio plays yet - mic silent for the whole call (seen in the app log 2026-10-13) |10
| `src/adm_proxy.cpp` | `BuiltInAECIsAvailable()` returns false on Windows | the voice capture DMO fails `StartRecording` ("Playout must be started before recording") when no remote audio plays yet - mic silent for the whole call (seen in the app log 2026-10-13) |11
| `src/adm_proxy.cpp`, `include/livekit/adm_proxy.h` | `SetPlayoutDevice` / `SetRecordingDevice(WindowsDeviceType)` turn `kDefaultCommunicationDevice` into `kDefaultDevice` | `WebRtcVoiceEngine::Init` selects the communications default at every call start; the app's "Default device" means the Windows default device (seen 2026-10-14: speaker came up on the communications default, user picked the default device by hand every call) |@@ -316,6 +316,7 @@ class AdmProxy : public webrtc::AudioDeviceModule {
316
316
// SetPlayoutDevice/SetRecordingDevice overloads, so an explicit index 0
317
317
// and a Windows default device type both survive the replay.
318
318
using DeviceSelection = std::variant<uint16_t, WindowsDeviceType>;
319
static WindowsDeviceType SystemDefaultFor(WindowsDeviceType requested);
319
320
std::optional<DeviceSelection> selected_playout_device_
320
321
RTC_GUARDED_BY(worker_thread_);
321
322
std::optional<DeviceSelection> selected_recording_device_
@@ -316,6 +316,7 @@ class AdmProxy : public webrtc::AudioDeviceModule {316
// SetPlayoutDevice/SetRecordingDevice overloads, so an explicit index 0316
// SetPlayoutDevice/SetRecordingDevice overloads, so an explicit index 0317
// and a Windows default device type both survive the replay.317
// and a Windows default device type both survive the replay.318
using DeviceSelection = std::variant<uint16_t, WindowsDeviceType>;318
using DeviceSelection = std::variant<uint16_t, WindowsDeviceType>;319
static WindowsDeviceType SystemDefaultFor(WindowsDeviceType requested);319
std::optional<DeviceSelection> selected_playout_device_320
std::optional<DeviceSelection> selected_playout_device_320
RTC_GUARDED_BY(worker_thread_);321
RTC_GUARDED_BY(worker_thread_);321
std::optional<DeviceSelection> selected_recording_device_322
std::optional<DeviceSelection> selected_recording_device_@@ -431,6 +431,13 @@ int32_t AdmProxy::RecordingDeviceName(uint16_t index,
431
431
});
432
432
}
433
433
434
// WebRtcVoiceEngine::Init asks for the communications default at every call start; the app's default is the Windows default device.
435
AdmProxy::WindowsDeviceType AdmProxy::SystemDefaultFor(WindowsDeviceType requested) {
436
return requested == WindowsDeviceType::kDefaultCommunicationDevice
437
? WindowsDeviceType::kDefaultDevice
438
: requested;
439
}
440
434
441
int32_t AdmProxy::SetPlayoutDevice(uint16_t index) {
435
442
return RunOnWorker([this, index] {
436
443
RTC_DCHECK_RUN_ON(worker_thread_);
@@ -442,7 +449,8 @@ int32_t AdmProxy::SetPlayoutDevice(uint16_t index) {
442
449
});
443
450
}
444
451
445
int32_t AdmProxy::SetPlayoutDevice(WindowsDeviceType device) {
452
int32_t AdmProxy::SetPlayoutDevice(WindowsDeviceType requested) {
453
const WindowsDeviceType device = SystemDefaultFor(requested);
446
454
return RunOnWorker([this, device] {
447
455
RTC_DCHECK_RUN_ON(worker_thread_);
448
456
selected_playout_device_ = DeviceSelection(device);
@@ -464,7 +472,8 @@ int32_t AdmProxy::SetRecordingDevice(uint16_t index) {
464
472
});
465
473
}
466
474
467
int32_t AdmProxy::SetRecordingDevice(WindowsDeviceType device) {
475
int32_t AdmProxy::SetRecordingDevice(WindowsDeviceType requested) {
476
const WindowsDeviceType device = SystemDefaultFor(requested);
468
477
return RunOnWorker([this, device] {
469
478
RTC_DCHECK_RUN_ON(worker_thread_);
470
479
selected_recording_device_ = DeviceSelection(device);
@@ -431,6 +431,13 @@ int32_t AdmProxy::RecordingDeviceName(uint16_t index,431
});431
});432
}432
}433
433
434
// WebRtcVoiceEngine::Init asks for the communications default at every call start; the app's default is the Windows default device.435
AdmProxy::WindowsDeviceType AdmProxy::SystemDefaultFor(WindowsDeviceType requested) {436
return requested == WindowsDeviceType::kDefaultCommunicationDevice437
? WindowsDeviceType::kDefaultDevice438
: requested;439
}440
434
int32_t AdmProxy::SetPlayoutDevice(uint16_t index) {441
int32_t AdmProxy::SetPlayoutDevice(uint16_t index) {435
return RunOnWorker([this, index] {442
return RunOnWorker([this, index] {436
RTC_DCHECK_RUN_ON(worker_thread_);443
RTC_DCHECK_RUN_ON(worker_thread_);@@ -442,7 +449,8 @@ int32_t AdmProxy::SetPlayoutDevice(uint16_t index) {442
});449
});443
}450
}444
451
445
int32_t AdmProxy::SetPlayoutDevice(WindowsDeviceType device) {452
int32_t AdmProxy::SetPlayoutDevice(WindowsDeviceType requested) {453
const WindowsDeviceType device = SystemDefaultFor(requested);446
return RunOnWorker([this, device] {454
return RunOnWorker([this, device] {447
RTC_DCHECK_RUN_ON(worker_thread_);455
RTC_DCHECK_RUN_ON(worker_thread_);448
selected_playout_device_ = DeviceSelection(device);456
selected_playout_device_ = DeviceSelection(device);@@ -464,7 +472,8 @@ int32_t AdmProxy::SetRecordingDevice(uint16_t index) {464
});472
});465
}473
}466
474
467
int32_t AdmProxy::SetRecordingDevice(WindowsDeviceType device) {475
int32_t AdmProxy::SetRecordingDevice(WindowsDeviceType requested) {476
const WindowsDeviceType device = SystemDefaultFor(requested);468
return RunOnWorker([this, device] {477
return RunOnWorker([this, device] {469
RTC_DCHECK_RUN_ON(worker_thread_);478
RTC_DCHECK_RUN_ON(worker_thread_);470
selected_recording_device_ = DeviceSelection(device);479
selected_recording_device_ = DeviceSelection(device);