fix(calls): a failing SDP parse no longer leaves the call stuck in Connecting
- libwebrtc panicked while decoding an SDP parse error; the call task died and the UI stayed on Connecting. SDP parsing now catches it and the call ends with an error. - A call whose task stops without an end state is ended as failed. - Every call writes masked SDPs and its timeline (incl. audio setup) to data/last-call/ for diagnosis. - Focus ring on buttons only after keyboard input, not after a mouse click. - No blinking avatar while ringing the other person. - Quitting no longer panics in the presence unregister (timeout built outside the runtime). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -2,7 +2,8 @@ use std::time::{Duration, Instant};
2
2
3
3
use calling::meeting::LiveMeeting;
4
4
use calling::{
5
AcceptMode, CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,
5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice, EndReason, EngineEvent, MuteCommand, Reaction, RingSignal,
6
ShareSource, VideoKey,
6
7
};
7
8
use gpui_kit::*;
8
9
@@ -199,6 +200,7 @@ impl AppState {
199
200
return;
200
201
}
201
202
}
203
let _ = this.update(cx, |state, cx| state.end_orphaned_call(call_id, cx));
202
204
})
203
205
.detach();
204
206
cx.spawn(async move |this, cx| {
@@ -224,6 +226,14 @@ impl AppState {
224
226
.detach();
225
227
}
226
228
229
fn end_orphaned_call(&mut self, call_id: u64, cx: &mut Context<Self>) {
230
let still_open = self.call.as_ref().is_some_and(|call| call.id == call_id && call.model.is_active());
231
if still_open {
232
let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());
233
self.apply_call_update(call_id, CallUpdate::State(CallState::Ended { reason }), cx);
234
}
235
}
236
227
237
pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {
228
238
let media = self.call_media.clone();
229
239
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {
@@ -2,7 +2,8 @@ use std::time::{Duration, Instant};2
2
3
use calling::meeting::LiveMeeting;3
use calling::meeting::LiveMeeting;4
use calling::{4
use calling::{5
AcceptMode, CallCommand, CallHandle, CallSpec, CallUpdate, Callee, DeviceChoice, EngineEvent, MuteCommand, Reaction, RingSignal, ShareSource, VideoKey,5
AcceptMode, CallCommand, CallHandle, CallSpec, CallState, CallUpdate, Callee, DeviceChoice, EndReason, EngineEvent, MuteCommand, Reaction, RingSignal,6
ShareSource, VideoKey,6
};7
};7
use gpui_kit::*;8
use gpui_kit::*;8
9
@@ -199,6 +200,7 @@ impl AppState {199
return;200
return;200
}201
}201
}202
}203
let _ = this.update(cx, |state, cx| state.end_orphaned_call(call_id, cx));202
})204
})203
.detach();205
.detach();204
cx.spawn(async move |this, cx| {206
cx.spawn(async move |this, cx| {@@ -224,6 +226,14 @@ impl AppState {224
.detach();226
.detach();225
}227
}226
228
229
fn end_orphaned_call(&mut self, call_id: u64, cx: &mut Context<Self>) {230
let still_open = self.call.as_ref().is_some_and(|call| call.id == call_id && call.model.is_active());231
if still_open {232
let reason = EndReason::Failed("The call stopped unexpectedly".to_owned());233
self.apply_call_update(call_id, CallUpdate::State(CallState::Ended { reason }), cx);234
}235
}236
227
pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {237
pub(super) fn apply_call_update(&mut self, call_id: u64, update: CallUpdate, cx: &mut Context<Self>) {228
let media = self.call_media.clone();238
let media = self.call_media.clone();229
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {239
let Some(call) = self.call.as_mut().filter(|call| call.id == call_id) else {@@ -11,6 +11,7 @@ use session::{Session, SessionConfig, Transport};
11
11
const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];
12
12
const START_RETRY_STEADY: Duration = Duration::from_secs(10);
13
13
const NOT_READY: &str = "Calls are not ready yet";
14
const LAST_CALL_DIR: &str = "last-call";
14
15
15
16
pub struct CallLauncher {
16
17
engine: Mutex<Option<CallEngine>>,
@@ -151,6 +152,7 @@ async fn start_engine(
151
152
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;
152
153
let config = EngineConfig {
153
154
ringable,
155
dump_dir: crate::diagnostics::directory().map(|directory| directory.join(LAST_CALL_DIR)),
154
156
..EngineConfig::default()
155
157
};
156
158
CallEngine::start(session, poll_session, config).await
@@ -11,6 +11,7 @@ use session::{Session, SessionConfig, Transport};11
const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];11
const START_RETRY_STEPS: [Duration; 3] = [Duration::from_secs(1), Duration::from_secs(2), Duration::from_secs(5)];12
const START_RETRY_STEADY: Duration = Duration::from_secs(10);12
const START_RETRY_STEADY: Duration = Duration::from_secs(10);13
const NOT_READY: &str = "Calls are not ready yet";13
const NOT_READY: &str = "Calls are not ready yet";14
const LAST_CALL_DIR: &str = "last-call";14
15
15
pub struct CallLauncher {16
pub struct CallLauncher {16
engine: Mutex<Option<CallEngine>>,17
engine: Mutex<Option<CallEngine>>,@@ -151,6 +152,7 @@ async fn start_engine(151
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;152
let poll_session = Session::with_transport(transport, SessionConfig::default()).await?;152
let config = EngineConfig {153
let config = EngineConfig {153
ringable,154
ringable,155
dump_dir: crate::diagnostics::directory().map(|directory| directory.join(LAST_CALL_DIR)),154
..EngineConfig::default()156
..EngineConfig::default()155
};157
};156
CallEngine::start(session, poll_session, config).await158
CallEngine::start(session, poll_session, config).await@@ -12,6 +12,10 @@ pub fn install(path: PathBuf) {
12
12
let _ = PATH.set(path);
13
13
}
14
14
15
pub fn directory() -> Option<PathBuf> {
16
PATH.get().and_then(|path| path.parent()).map(PathBuf::from)
17
}
18
15
19
pub fn record(message: impl AsRef<str>) {
16
20
let message = message.as_ref();
17
21
eprintln!("{message}");
@@ -12,6 +12,10 @@ pub fn install(path: PathBuf) {12
let _ = PATH.set(path);12
let _ = PATH.set(path);13
}13
}14
14
15
pub fn directory() -> Option<PathBuf> {16
PATH.get().and_then(|path| path.parent()).map(PathBuf::from)17
}18
15
pub fn record(message: impl AsRef<str>) {19
pub fn record(message: impl AsRef<str>) {16
let message = message.as_ref();20
let message = message.as_ref();17
eprintln!("{message}");21
eprintln!("{message}");@@ -59,7 +59,7 @@ pub fn unregister_on_exit(timeout: Duration) {
59
59
if unregister.send(done).is_err() {
60
60
return;
61
61
}
62
let _ = crate::runtime::handle().block_on(tokio::time::timeout(timeout, finished));
62
let _ = crate::runtime::handle().block_on(async move { tokio::time::timeout(timeout, finished).await });
63
63
}
64
64
65
65
#[derive(Default)]
@@ -59,7 +59,7 @@ pub fn unregister_on_exit(timeout: Duration) {59
if unregister.send(done).is_err() {59
if unregister.send(done).is_err() {60
return;60
return;61
}61
}62
let _ = crate::runtime::handle().block_on(tokio::time::timeout(timeout, finished));62
let _ = crate::runtime::handle().block_on(async move { tokio::time::timeout(timeout, finished).await });63
}63
}64
64
65
#[derive(Default)]65
#[derive(Default)]@@ -710,7 +710,6 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti
710
710
}
711
711
let waiting = remote.state == TileState::Invited;
712
712
let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);
713
let avatar = if waiting { blinking(avatar) } else { avatar };
714
713
let caption = model.tile_caption(remote).map(|text| {
715
714
let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);
716
715
if waiting { blinking(label) } else { label.into_any_element() }
@@ -710,7 +710,6 @@ fn person_tile_body(state: &AppState, model: &CallModel, remote: &Tile, size: Ti710
}710
}711
let waiting = remote.state == TileState::Invited;711
let waiting = remote.state == TileState::Invited;712
let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);712
let avatar = person_avatar(&state.directory, remote.user_id.as_deref(), &remote.name, size.avatar);713
let avatar = if waiting { blinking(avatar) } else { avatar };714
let caption = model.tile_caption(remote).map(|text| {713
let caption = model.tile_caption(remote).map(|text| {715
let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);714
let label = div().text_size(px(12.)).text_color(theme::text_muted()).child(text);716
if waiting { blinking(label) } else { label.into_any_element() }715
if waiting { blinking(label) } else { label.into_any_element() }@@ -335,6 +335,7 @@ pub async fn run_test_call(
335
335
routing: options.routing.clone(),
336
336
relay_host: options.relay_host.clone(),
337
337
trace: options.trace,
338
dump_dir: None,
338
339
instance: chatsvc::InstanceNames {
339
340
global: "__testCallTrouter".into(),
340
341
binding: "__testCallRealtime".into(),
@@ -352,6 +353,9 @@ impl CallEngine {
352
353
let inner = self.inner.as_ref();
353
354
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };
354
355
let timeline = Timeline::new(options.trace);
356
if let Some(directory) = options.sdp_dump_dir.as_ref().filter(|_| !options.concurrent) {
357
let _ = std::fs::remove_dir_all(directory);
358
}
355
359
let mut report = CallReport::default();
356
360
let mut state = CallState::Idle;
357
361
advance(&mut state, CallSignal::Dial, &control);
@@ -380,6 +384,7 @@ impl CallEngine {
380
384
Some(error)
381
385
}
382
386
};
387
dump_timeline(&options, &timeline, failure.as_ref());
383
388
let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
384
389
tear_down(live, inner, &timeline, &mut report, cancelled).await;
385
390
let recording = recording.lock().await;
@@ -470,7 +475,7 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
470
475
.await
471
476
.map_err(|error| Error::Webrtc(error.to_string()))?;
472
477
let browser_offer = directions_for(layout, false, false, &offer.to_string());
473
let description = SessionDescription::parse(&browser_offer, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
478
let description = parse_sdp(&browser_offer, SdpType::Offer)?;
474
479
peer.set_local_description(description)
475
480
.await
476
481
.map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -496,8 +501,7 @@ async fn answer_offer(
496
501
video: AnswerVideo<'_>,
497
502
) -> Result<AnsweredMedia> {
498
503
let remote = from_teams_offer(teams_offer)?;
499
let description =
500
SessionDescription::parse(&remote.browser_sdp, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
504
let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
501
505
peer.set_remote_description(description)
502
506
.await
503
507
.map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -598,7 +602,12 @@ async fn drive(
598
602
let mut output = options.output.clone();
599
603
let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
600
604
control.send(CallUpdate::ListenOnly(audio.listen_only));
601
control.send(CallUpdate::Devices(devices::list_devices(&factory)));
605
let device_lists = devices::list_devices(&factory);
606
timeline.record(
607
"audio setup",
608
format!("listen only {}, {} input(s), {} output(s)", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len()),
609
);
610
control.send(CallUpdate::Devices(device_lists));
602
611
control.send(CallUpdate::Selected {
603
612
input: input.clone(),
604
613
output: output.clone(),
@@ -709,11 +718,11 @@ async fn drive(
709
718
AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),
710
719
_ => AnswerVideo::Receive,
711
720
};
721
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
712
722
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer).await?;
713
723
layout_plan = answered.remote.plan();
714
724
direct_video_mid = answered.camera_mid.clone();
715
725
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
716
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
717
726
dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
718
727
let acceptance_url = attached
719
728
.links
@@ -1821,7 +1830,7 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
1821
1830
.await
1822
1831
.map_err(|error| Error::Webrtc(error.to_string()))?;
1823
1832
let text = directions_for(layout, hold, camera, &offer.to_string());
1824
let description = SessionDescription::parse(&text, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;
1833
let description = parse_sdp(&text, SdpType::Offer)?;
1825
1834
peer.set_local_description(description)
1826
1835
.await
1827
1836
.map_err(|error| Error::Webrtc(error.to_string()))?;
@@ -1830,8 +1839,17 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:
1830
1839
Ok((text, signaled))
1831
1840
}
1832
1841
1842
/// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
1843
fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
1844
match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
1845
Ok(Ok(description)) => Ok(description),
1846
Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),
1847
Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),
1848
}
1849
}
1850
1833
1851
async fn rollback_offer(peer: &PeerConnection) {
1834
if let Ok(rollback) = SessionDescription::parse("", SdpType::Rollback) {
1852
if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
1835
1853
let _ = peer.set_local_description(rollback).await;
1836
1854
}
1837
1855
}
@@ -2157,8 +2175,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2157
2175
2158
2176
async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
2159
2177
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
2160
let description =
2161
SessionDescription::parse(&answer, SdpType::Answer).map_err(|error| Error::Sdp(error.description))?;
2178
let description = parse_sdp(&answer, SdpType::Answer)?;
2162
2179
peer.set_remote_description(description)
2163
2180
.await
2164
2181
.map_err(|error| Error::Webrtc(error.to_string()))
@@ -2184,6 +2201,20 @@ fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
2184
2201
let _ = std::fs::write(directory.join(name), masked.join("\n"));
2185
2202
}
2186
2203
2204
fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {
2205
let Some(directory) = &options.sdp_dump_dir else {
2206
return;
2207
};
2208
let mut lines: Vec<String> =
2209
timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();
2210
lines.push(match failure {
2211
Some(error) => format!("failed: {error}"),
2212
None => "ended without error".to_owned(),
2213
});
2214
let _ = std::fs::create_dir_all(directory);
2215
let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));
2216
}
2217
2187
2218
fn mask_address(token: &str) -> String {
2188
2219
let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
2189
2220
let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
@@ -2334,6 +2365,25 @@ mod tests {
2334
2365
crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
2335
2366
}
2336
2367
2368
async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
2369
use libwebrtc::audio_source::native::NativeAudioSource;
2370
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2371
let factory = devices::shared_factory();
2372
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
2373
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
2374
let track = factory.create_audio_track("microphone", source);
2375
create_offer(&peer, &factory, &track, layout).await
2376
}
2377
2378
#[tokio::test]
2379
async fn libwebrtc_accepts_its_own_offer_after_the_direction_rewrite() {
2380
for layout in [Layout::OneToOne, Layout::Conference] {
2381
if let Err(error) = local_offer(layout).await {
2382
panic!("{layout:?}: {error}");
2383
}
2384
}
2385
}
2386
2337
2387
#[test]
2338
2388
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
2339
2389
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
@@ -335,6 +335,7 @@ pub async fn run_test_call(335
routing: options.routing.clone(),335
routing: options.routing.clone(),336
relay_host: options.relay_host.clone(),336
relay_host: options.relay_host.clone(),337
trace: options.trace,337
trace: options.trace,338
dump_dir: None,338
instance: chatsvc::InstanceNames {339
instance: chatsvc::InstanceNames {339
global: "__testCallTrouter".into(),340
global: "__testCallTrouter".into(),340
binding: "__testCallRealtime".into(),341
binding: "__testCallRealtime".into(),@@ -352,6 +353,9 @@ impl CallEngine {352
let inner = self.inner.as_ref();353
let inner = self.inner.as_ref();353
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };354
let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) };354
let timeline = Timeline::new(options.trace);355
let timeline = Timeline::new(options.trace);356
if let Some(directory) = options.sdp_dump_dir.as_ref().filter(|_| !options.concurrent) {357
let _ = std::fs::remove_dir_all(directory);358
}355
let mut report = CallReport::default();359
let mut report = CallReport::default();356
let mut state = CallState::Idle;360
let mut state = CallState::Idle;357
advance(&mut state, CallSignal::Dial, &control);361
advance(&mut state, CallSignal::Dial, &control);@@ -380,6 +384,7 @@ impl CallEngine {380
Some(error)384
Some(error)381
}385
}382
};386
};387
dump_timeline(&options, &timeline, failure.as_ref());383
let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });388
let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });384
tear_down(live, inner, &timeline, &mut report, cancelled).await;389
tear_down(live, inner, &timeline, &mut report, cancelled).await;385
let recording = recording.lock().await;390
let recording = recording.lock().await;@@ -470,7 +475,7 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr470
.await475
.await471
.map_err(|error| Error::Webrtc(error.to_string()))?;476
.map_err(|error| Error::Webrtc(error.to_string()))?;472
let browser_offer = directions_for(layout, false, false, &offer.to_string());477
let browser_offer = directions_for(layout, false, false, &offer.to_string());473
let description = SessionDescription::parse(&browser_offer, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;478
let description = parse_sdp(&browser_offer, SdpType::Offer)?;474
peer.set_local_description(description)479
peer.set_local_description(description)475
.await480
.await476
.map_err(|error| Error::Webrtc(error.to_string()))?;481
.map_err(|error| Error::Webrtc(error.to_string()))?;@@ -496,8 +501,7 @@ async fn answer_offer(496
video: AnswerVideo<'_>,501
video: AnswerVideo<'_>,497
) -> Result<AnsweredMedia> {502
) -> Result<AnsweredMedia> {498
let remote = from_teams_offer(teams_offer)?;503
let remote = from_teams_offer(teams_offer)?;499
let description =504
let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;500
SessionDescription::parse(&remote.browser_sdp, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;501
peer.set_remote_description(description)505
peer.set_remote_description(description)502
.await506
.await503
.map_err(|error| Error::Webrtc(error.to_string()))?;507
.map_err(|error| Error::Webrtc(error.to_string()))?;@@ -598,7 +602,12 @@ async fn drive(598
let mut output = options.output.clone();602
let mut output = options.output.clone();599
let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);603
let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);600
control.send(CallUpdate::ListenOnly(audio.listen_only));604
control.send(CallUpdate::ListenOnly(audio.listen_only));601
control.send(CallUpdate::Devices(devices::list_devices(&factory)));605
let device_lists = devices::list_devices(&factory);606
timeline.record(607
"audio setup",608
format!("listen only {}, {} input(s), {} output(s)", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len()),609
);610
control.send(CallUpdate::Devices(device_lists));602
control.send(CallUpdate::Selected {611
control.send(CallUpdate::Selected {603
input: input.clone(),612
input: input.clone(),604
output: output.clone(),613
output: output.clone(),@@ -709,11 +718,11 @@ async fn drive(709
AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),718
AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),710
_ => AnswerVideo::Receive,719
_ => AnswerVideo::Receive,711
};720
};721
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);712
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer).await?;722
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer).await?;713
layout_plan = answered.remote.plan();723
layout_plan = answered.remote.plan();714
direct_video_mid = answered.camera_mid.clone();724
direct_video_mid = answered.camera_mid.clone();715
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));725
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));716
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);717
dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);726
dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);718
let acceptance_url = attached727
let acceptance_url = attached719
.links728
.links@@ -1821,7 +1830,7 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:1821
.await1830
.await1822
.map_err(|error| Error::Webrtc(error.to_string()))?;1831
.map_err(|error| Error::Webrtc(error.to_string()))?;1823
let text = directions_for(layout, hold, camera, &offer.to_string());1832
let text = directions_for(layout, hold, camera, &offer.to_string());1824
let description = SessionDescription::parse(&text, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?;1833
let description = parse_sdp(&text, SdpType::Offer)?;1825
peer.set_local_description(description)1834
peer.set_local_description(description)1826
.await1835
.await1827
.map_err(|error| Error::Webrtc(error.to_string()))?;1836
.map_err(|error| Error::Webrtc(error.to_string()))?;@@ -1830,8 +1839,17 @@ async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout:1830
Ok((text, signaled))1839
Ok((text, signaled))1831
}1840
}1832
1841
1842
/// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.1843
fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {1844
match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {1845
Ok(Ok(description)) => Ok(description),1846
Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),1847
Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),1848
}1849
}1850
1833
async fn rollback_offer(peer: &PeerConnection) {1851
async fn rollback_offer(peer: &PeerConnection) {1834
if let Ok(rollback) = SessionDescription::parse("", SdpType::Rollback) {1852
if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {1835
let _ = peer.set_local_description(rollback).await;1853
let _ = peer.set_local_description(rollback).await;1836
}1854
}1837
}1855
}@@ -2157,8 +2175,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca2157
2175
2158
async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {2176
async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {2159
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;2177
let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;2160
let description =2178
let description = parse_sdp(&answer, SdpType::Answer)?;2161
SessionDescription::parse(&answer, SdpType::Answer).map_err(|error| Error::Sdp(error.description))?;2162
peer.set_remote_description(description)2179
peer.set_remote_description(description)2163
.await2180
.await2164
.map_err(|error| Error::Webrtc(error.to_string()))2181
.map_err(|error| Error::Webrtc(error.to_string()))@@ -2184,6 +2201,20 @@ fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {2184
let _ = std::fs::write(directory.join(name), masked.join("\n"));2201
let _ = std::fs::write(directory.join(name), masked.join("\n"));2185
}2202
}2186
2203
2204
fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {2205
let Some(directory) = &options.sdp_dump_dir else {2206
return;2207
};2208
let mut lines: Vec<String> =2209
timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();2210
lines.push(match failure {2211
Some(error) => format!("failed: {error}"),2212
None => "ended without error".to_owned(),2213
});2214
let _ = std::fs::create_dir_all(directory);2215
let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));2216
}2217
2187
fn mask_address(token: &str) -> String {2218
fn mask_address(token: &str) -> String {2188
let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());2219
let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());2189
let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");2220
let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");@@ -2334,6 +2365,25 @@ mod tests {2334
crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()2365
crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()2335
}2366
}2336
2367
2368
async fn local_offer(layout: Layout) -> Result<OfferedMedia> {2369
use libwebrtc::audio_source::native::NativeAudioSource;2370
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;2371
let factory = devices::shared_factory();2372
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();2373
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);2374
let track = factory.create_audio_track("microphone", source);2375
create_offer(&peer, &factory, &track, layout).await2376
}2377
2378
#[tokio::test]2379
async fn libwebrtc_accepts_its_own_offer_after_the_direction_rewrite() {2380
for layout in [Layout::OneToOne, Layout::Conference] {2381
if let Err(error) = local_offer(layout).await {2382
panic!("{layout:?}: {error}");2383
}2384
}2385
}2386
2337
#[test]2387
#[test]2338
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {2388
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {2339
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);2389
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);@@ -56,6 +56,7 @@ pub struct EngineConfig {
56
56
pub routing: TenantRouting,
57
57
pub relay_host: String,
58
58
pub trace: bool,
59
pub dump_dir: Option<std::path::PathBuf>,
59
60
/// Page globals of the Trouter client; a second engine in the same tab needs its own.
60
61
pub instance: InstanceNames,
61
62
}
@@ -67,6 +68,7 @@ impl Default for EngineConfig {
67
68
routing: TenantRouting::default(),
68
69
relay_host: DEFAULT_RELAY_HOST.to_owned(),
69
70
trace: std::env::var_os(TRACE_ENV).is_some(),
71
dump_dir: None,
70
72
instance: calling_instance_names(),
71
73
}
72
74
}
@@ -155,6 +157,7 @@ impl Inner {
155
157
relay_host: self.config.relay_host.clone(),
156
158
routing: self.config.routing.clone(),
157
159
trace: self.config.trace,
160
sdp_dump_dir: self.config.dump_dir.clone(),
158
161
camera: self.default_camera.lock().expect("default camera lock").clone(),
159
162
..CallOptions::default()
160
163
}
@@ -56,6 +56,7 @@ pub struct EngineConfig {56
pub routing: TenantRouting,56
pub routing: TenantRouting,57
pub relay_host: String,57
pub relay_host: String,58
pub trace: bool,58
pub trace: bool,59
pub dump_dir: Option<std::path::PathBuf>,59
/// Page globals of the Trouter client; a second engine in the same tab needs its own.60
/// Page globals of the Trouter client; a second engine in the same tab needs its own.60
pub instance: InstanceNames,61
pub instance: InstanceNames,61
}62
}@@ -67,6 +68,7 @@ impl Default for EngineConfig {67
routing: TenantRouting::default(),68
routing: TenantRouting::default(),68
relay_host: DEFAULT_RELAY_HOST.to_owned(),69
relay_host: DEFAULT_RELAY_HOST.to_owned(),69
trace: std::env::var_os(TRACE_ENV).is_some(),70
trace: std::env::var_os(TRACE_ENV).is_some(),71
dump_dir: None,70
instance: calling_instance_names(),72
instance: calling_instance_names(),71
}73
}72
}74
}@@ -155,6 +157,7 @@ impl Inner {155
relay_host: self.config.relay_host.clone(),157
relay_host: self.config.relay_host.clone(),156
routing: self.config.routing.clone(),158
routing: self.config.routing.clone(),157
trace: self.config.trace,159
trace: self.config.trace,160
sdp_dump_dir: self.config.dump_dir.clone(),158
camera: self.default_camera.lock().expect("default camera lock").clone(),161
camera: self.default_camera.lock().expect("default camera lock").clone(),159
..CallOptions::default()162
..CallOptions::default()160
}163
}@@ -872,7 +872,7 @@ impl RenderOnce for Button {
872
872
this
873
873
}
874
874
})
875
.when(is_focused && self.focus_ring_enabled, |this| {
875
.when(is_focused && self.focus_ring_enabled && window.last_input_was_keyboard(), |this| {
876
876
focus_style(this, focus_line, window, cx)
877
877
})
878
878
}
@@ -872,7 +872,7 @@ impl RenderOnce for Button {872
this872
this873
}873
}874
})874
})875
.when(is_focused && self.focus_ring_enabled, |this| {875
.when(is_focused && self.focus_ring_enabled && window.last_input_was_keyboard(), |this| {876
focus_style(this, focus_line, window, cx)876
focus_style(this, focus_line, window, cx)877
})877
})878
}878
}