BlueGit

ict rusty-teams

refactor(calling): split call.rs into submodules under call/

- Same cut as PR #43, redone on current main: peer_sdp, escalation, audio_switch, bots, teardown, stats; drive() and the tests stay in mod.rs
- Functions added since the PR placed next to their neighbours (leg media links and answer helpers in peer_sdp, video line binding in escalation, stop_local_publish in teardown)
- Pure move: items unchanged apart from pub(super)

Closes #43

Co-Authored-By: Joachim Mild <joe@root-files.net>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
29a73c84081d13f7ab5d65cbec197184fec0be93
Parent
dab84467
8 files changed +2415 −2383
crates/calling/src/call/audio_switch.rs added +288 −0
@@ -0,0 +1,288 @@
1 use super::*;
2
3 #[derive(Default)]
4 pub(super) struct Recording {
5 pub(super) samples: Vec<i16>,
6 pub(super) current_second: Vec<i16>,
7 pub(super) per_second: Vec<(f32, f32)>,
8 }
9
10 pub(super) fn withhold_media(
11 muted: &mut bool,
12 audio: &AudioSetup,
13 software_audio: Option<&SoftwareAudio>,
14 remote: &RemoteCall,
15 local_video: &mut LocalVideo,
16 control: &CallControl,
17 ) {
18 *muted = apply_mute(
19 MuteCommand::Mute,
20 *muted,
21 audio,
22 software_audio,
23 remote,
24 control,
25 );
26 if local_video.camera_on() {
27 local_video.stop_camera();
28 control.send(CallUpdate::Camera(false));
29 }
30 }
31
32 pub(super) fn record_audio_devices(
33 timeline: &Timeline,
34 lists: &devices::DeviceLists,
35 input: Option<&AppliedDevice>,
36 output: Option<&AppliedDevice>,
37 ) {
38 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
39 applied
40 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
41 .map_or("none", |device| device.name.as_str())
42 .to_owned()
43 };
44 timeline.record(
45 "audio devices",
46 format!(
47 "input={} output={}",
48 name(&lists.inputs, input),
49 name(&lists.outputs, output)
50 ),
51 );
52 }
53
54 pub(super) fn follow_device_change(
55 flow: Flow,
56 (previous, current): (&[AudioDevice], &[AudioDevice]),
57 choice: &DeviceChoice,
58 applied: &mut Option<AppliedDevice>,
59 select: impl Fn(u16) -> bool,
60 timeline: &Timeline,
61 control: &CallControl,
62 ) -> bool {
63 let system_default = devices::system_default_id(flow);
64 let (index, fell_back) =
65 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
66 Reselect::Keep => return false,
67 Reselect::Select(index) => (index, false),
68 Reselect::FallBack(index) => (index, true),
69 };
70 let selected = select(index);
71 timeline.record(
72 "device change",
73 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
74 );
75 if selected {
76 *applied = current
77 .iter()
78 .find(|device| device.index == index)
79 .map(|device| AppliedDevice {
80 index,
81 key: device.key(),
82 });
83 }
84 if fell_back {
85 let fallback = current.iter().find(|device| device.index == index);
86 control.send(CallUpdate::Notice(devices::disconnect_notice(
87 previous, choice, fallback,
88 )));
89 }
90 selected
91 }
92
93 pub(super) fn apply_mute(
94 command: MuteCommand,
95 currently_muted: bool,
96 audio: &AudioSetup,
97 software_audio: Option<&SoftwareAudio>,
98 remote: &RemoteCall,
99 control: &CallControl,
100 ) -> bool {
101 let effect = MuteEffect::for_muted(command.target(currently_muted));
102 audio.track.set_enabled(effect.track_enabled);
103 if let Some(software_audio) = software_audio {
104 software_audio.set_microphone_muted(effect.muted);
105 }
106 control.send(CallUpdate::Muted(effect.muted));
107 let remote = remote.clone();
108 tokio::spawn(async move {
109 let _ = remote
110 .signaling
111 .update_endpoint_state(
112 &remote.conversation,
113 &remote.participant,
114 effect.endpoint_is_muted,
115 )
116 .await;
117 });
118 effect.muted
119 }
120
121 pub(super) fn silence_for_hold(
122 on_hold: bool,
123 muted: bool,
124 audio: Option<&AudioSetup>,
125 software_audio: Option<&SoftwareAudio>,
126 ) {
127 let silent = on_hold || muted;
128 if let Some(audio) = audio {
129 audio
130 .track
131 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
132 }
133 if let Some(software_audio) = software_audio {
134 software_audio.set_microphone_muted(silent);
135 }
136 }
137
138 pub(super) fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
139 let sender = peer
140 .senders()
141 .into_iter()
142 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
143 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
144 sender
145 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
146 .map_err(|error| Error::Webrtc(error.to_string()))
147 }
148
149 pub(super) fn outgoing_track<'a>(
150 software_audio: Option<&'a SoftwareAudio>,
151 device_track: &'a RtcAudioTrack,
152 ) -> &'a RtcAudioTrack {
153 pick_track(software_audio.map(|audio| &audio.track), device_track)
154 }
155
156 pub(super) fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T {
157 software.unwrap_or(device)
158 }
159
160 pub(super) fn software_wanted(
161 mic_settings: MicSettings,
162 share_sound_wanted: bool,
163 local_video: &LocalVideo,
164 audio: Option<&AudioSetup>,
165 ) -> Option<SoftwareAudioPlan> {
166 let sharing_sound = share_sound_wanted && local_video.sharing();
167 SoftwareAudioPlan::wanted(
168 mic_settings,
169 sharing_sound,
170 audio.is_some_and(AudioSetup::uses_devices),
171 )
172 }
173
174 pub(super) fn restore_device_track(
175 factory: &PeerConnectionFactory,
176 input: &DeviceChoice,
177 peer: &PeerConnection,
178 device_track: &RtcAudioTrack,
179 timeline: &Timeline,
180 ) {
181 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
182 if !factory.adm_recording_enabled() {
183 factory.set_adm_recording_enabled(true);
184 devices::select_input(factory, input);
185 }
186 if let Err(error) = swap_audio_track(peer, device_track) {
187 timeline.record("microphone track not restored", error.to_string());
188 }
189 }
190
191 #[allow(clippy::too_many_arguments)]
192 pub(super) fn sync_software_audio(
193 factory: &PeerConnectionFactory,
194 options: &CallOptions,
195 input: &DeviceChoice,
196 muted: bool,
197 remote_audio: Option<RtcAudioTrack>,
198 peer: &PeerConnection,
199 device_track: &RtcAudioTrack,
200 wanted: Option<SoftwareAudioPlan>,
201 restart: bool,
202 software_audio: &mut Option<SoftwareAudio>,
203 mic_settings: MicSettings,
204 control: &CallControl,
205 timeline: &Timeline,
206 ) {
207 let running = software_audio.as_ref().map(|audio| audio.plan);
208 if running == wanted && !restart {
209 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
210 return;
211 }
212 if running.is_some() {
213 timeline.record("software audio", "stopping");
214 }
215 *software_audio = None;
216 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
217 let Some(plan) = wanted else {
218 restore_device_track(factory, input, peer, device_track, timeline);
219 control.send(CallUpdate::ShareSound(false));
220 crate::noise_stage::apply_for_outgoing(mic_settings, true);
221 return;
222 };
223 let started = SoftwareAudio::start(
224 factory,
225 options.audio,
226 options.tone_hz,
227 input,
228 plan,
229 muted,
230 remote_audio,
231 )
232 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
233 match started {
234 Ok(audio) => {
235 timeline.record(
236 "software audio",
237 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
238 );
239 if let Some(source) = &audio.microphone_source {
240 timeline.record("mic capture", source.clone());
241 }
242 if audio.microphone_source.is_some() {
243 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
244 factory.set_adm_recording_enabled(false);
245 }
246 if let Some(warning) = &audio.warning {
247 timeline.record("computer sound warning", warning.clone());
248 }
249 control.send(CallUpdate::ShareSound(plan.computer_sound));
250 if let Some(notice) = audio.microphone_notice {
251 control.send(CallUpdate::Notice(notice.into()));
252 }
253 *software_audio = Some(audio);
254 }
255 Err(error) => {
256 timeline.record("software audio failed", error.to_string());
257 restore_device_track(factory, input, peer, device_track, timeline);
258 if was_sharing_sound || plan.computer_sound {
259 control.send(CallUpdate::ShareSound(false));
260 }
261 let notice = if plan.computer_sound {
262 "Computer sound could not start, sharing without it"
263 } else {
264 "Microphone processing could not start, using the standard microphone"
265 };
266 control.send(CallUpdate::Notice(notice.into()));
267 }
268 }
269 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
270 }
271
272 pub(super) async fn record_track(
273 track: RtcAudioTrack,
274 recording: Arc<Mutex<Recording>>,
275 tone_hz: f32,
276 ) {
277 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
278 while let Some(frame) = stream.next().await {
279 let mut recording = recording.lock().await;
280 recording.samples.extend_from_slice(&frame.data);
281 recording.current_second.extend_from_slice(&frame.data);
282 if recording.current_second.len() >= SAMPLE_RATE as usize {
283 let second: Vec<i16> = std::mem::take(&mut recording.current_second);
284 let summary = (rms(&second), tone_ratio(&second, tone_hz));
285 recording.per_second.push(summary);
286 }
287 }
288 }
@@ -0,0 +1,288 @@
1use super::*;
2
3#[derive(Default)]
4pub(super) struct Recording {
5 pub(super) samples: Vec<i16>,
6 pub(super) current_second: Vec<i16>,
7 pub(super) per_second: Vec<(f32, f32)>,
8}
9
10pub(super) fn withhold_media(
11 muted: &mut bool,
12 audio: &AudioSetup,
13 software_audio: Option<&SoftwareAudio>,
14 remote: &RemoteCall,
15 local_video: &mut LocalVideo,
16 control: &CallControl,
17) {
18 *muted = apply_mute(
19 MuteCommand::Mute,
20 *muted,
21 audio,
22 software_audio,
23 remote,
24 control,
25 );
26 if local_video.camera_on() {
27 local_video.stop_camera();
28 control.send(CallUpdate::Camera(false));
29 }
30}
31
32pub(super) fn record_audio_devices(
33 timeline: &Timeline,
34 lists: &devices::DeviceLists,
35 input: Option<&AppliedDevice>,
36 output: Option<&AppliedDevice>,
37) {
38 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
39 applied
40 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
41 .map_or("none", |device| device.name.as_str())
42 .to_owned()
43 };
44 timeline.record(
45 "audio devices",
46 format!(
47 "input={} output={}",
48 name(&lists.inputs, input),
49 name(&lists.outputs, output)
50 ),
51 );
52}
53
54pub(super) fn follow_device_change(
55 flow: Flow,
56 (previous, current): (&[AudioDevice], &[AudioDevice]),
57 choice: &DeviceChoice,
58 applied: &mut Option<AppliedDevice>,
59 select: impl Fn(u16) -> bool,
60 timeline: &Timeline,
61 control: &CallControl,
62) -> bool {
63 let system_default = devices::system_default_id(flow);
64 let (index, fell_back) =
65 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
66 Reselect::Keep => return false,
67 Reselect::Select(index) => (index, false),
68 Reselect::FallBack(index) => (index, true),
69 };
70 let selected = select(index);
71 timeline.record(
72 "device change",
73 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
74 );
75 if selected {
76 *applied = current
77 .iter()
78 .find(|device| device.index == index)
79 .map(|device| AppliedDevice {
80 index,
81 key: device.key(),
82 });
83 }
84 if fell_back {
85 let fallback = current.iter().find(|device| device.index == index);
86 control.send(CallUpdate::Notice(devices::disconnect_notice(
87 previous, choice, fallback,
88 )));
89 }
90 selected
91}
92
93pub(super) fn apply_mute(
94 command: MuteCommand,
95 currently_muted: bool,
96 audio: &AudioSetup,
97 software_audio: Option<&SoftwareAudio>,
98 remote: &RemoteCall,
99 control: &CallControl,
100) -> bool {
101 let effect = MuteEffect::for_muted(command.target(currently_muted));
102 audio.track.set_enabled(effect.track_enabled);
103 if let Some(software_audio) = software_audio {
104 software_audio.set_microphone_muted(effect.muted);
105 }
106 control.send(CallUpdate::Muted(effect.muted));
107 let remote = remote.clone();
108 tokio::spawn(async move {
109 let _ = remote
110 .signaling
111 .update_endpoint_state(
112 &remote.conversation,
113 &remote.participant,
114 effect.endpoint_is_muted,
115 )
116 .await;
117 });
118 effect.muted
119}
120
121pub(super) fn silence_for_hold(
122 on_hold: bool,
123 muted: bool,
124 audio: Option<&AudioSetup>,
125 software_audio: Option<&SoftwareAudio>,
126) {
127 let silent = on_hold || muted;
128 if let Some(audio) = audio {
129 audio
130 .track
131 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
132 }
133 if let Some(software_audio) = software_audio {
134 software_audio.set_microphone_muted(silent);
135 }
136}
137
138pub(super) fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
139 let sender = peer
140 .senders()
141 .into_iter()
142 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
143 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
144 sender
145 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
146 .map_err(|error| Error::Webrtc(error.to_string()))
147}
148
149pub(super) fn outgoing_track<'a>(
150 software_audio: Option<&'a SoftwareAudio>,
151 device_track: &'a RtcAudioTrack,
152) -> &'a RtcAudioTrack {
153 pick_track(software_audio.map(|audio| &audio.track), device_track)
154}
155
156pub(super) fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T {
157 software.unwrap_or(device)
158}
159
160pub(super) fn software_wanted(
161 mic_settings: MicSettings,
162 share_sound_wanted: bool,
163 local_video: &LocalVideo,
164 audio: Option<&AudioSetup>,
165) -> Option<SoftwareAudioPlan> {
166 let sharing_sound = share_sound_wanted && local_video.sharing();
167 SoftwareAudioPlan::wanted(
168 mic_settings,
169 sharing_sound,
170 audio.is_some_and(AudioSetup::uses_devices),
171 )
172}
173
174pub(super) fn restore_device_track(
175 factory: &PeerConnectionFactory,
176 input: &DeviceChoice,
177 peer: &PeerConnection,
178 device_track: &RtcAudioTrack,
179 timeline: &Timeline,
180) {
181 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
182 if !factory.adm_recording_enabled() {
183 factory.set_adm_recording_enabled(true);
184 devices::select_input(factory, input);
185 }
186 if let Err(error) = swap_audio_track(peer, device_track) {
187 timeline.record("microphone track not restored", error.to_string());
188 }
189}
190
191#[allow(clippy::too_many_arguments)]
192pub(super) fn sync_software_audio(
193 factory: &PeerConnectionFactory,
194 options: &CallOptions,
195 input: &DeviceChoice,
196 muted: bool,
197 remote_audio: Option<RtcAudioTrack>,
198 peer: &PeerConnection,
199 device_track: &RtcAudioTrack,
200 wanted: Option<SoftwareAudioPlan>,
201 restart: bool,
202 software_audio: &mut Option<SoftwareAudio>,
203 mic_settings: MicSettings,
204 control: &CallControl,
205 timeline: &Timeline,
206) {
207 let running = software_audio.as_ref().map(|audio| audio.plan);
208 if running == wanted && !restart {
209 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
210 return;
211 }
212 if running.is_some() {
213 timeline.record("software audio", "stopping");
214 }
215 *software_audio = None;
216 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
217 let Some(plan) = wanted else {
218 restore_device_track(factory, input, peer, device_track, timeline);
219 control.send(CallUpdate::ShareSound(false));
220 crate::noise_stage::apply_for_outgoing(mic_settings, true);
221 return;
222 };
223 let started = SoftwareAudio::start(
224 factory,
225 options.audio,
226 options.tone_hz,
227 input,
228 plan,
229 muted,
230 remote_audio,
231 )
232 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
233 match started {
234 Ok(audio) => {
235 timeline.record(
236 "software audio",
237 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
238 );
239 if let Some(source) = &audio.microphone_source {
240 timeline.record("mic capture", source.clone());
241 }
242 if audio.microphone_source.is_some() {
243 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
244 factory.set_adm_recording_enabled(false);
245 }
246 if let Some(warning) = &audio.warning {
247 timeline.record("computer sound warning", warning.clone());
248 }
249 control.send(CallUpdate::ShareSound(plan.computer_sound));
250 if let Some(notice) = audio.microphone_notice {
251 control.send(CallUpdate::Notice(notice.into()));
252 }
253 *software_audio = Some(audio);
254 }
255 Err(error) => {
256 timeline.record("software audio failed", error.to_string());
257 restore_device_track(factory, input, peer, device_track, timeline);
258 if was_sharing_sound || plan.computer_sound {
259 control.send(CallUpdate::ShareSound(false));
260 }
261 let notice = if plan.computer_sound {
262 "Computer sound could not start, sharing without it"
263 } else {
264 "Microphone processing could not start, using the standard microphone"
265 };
266 control.send(CallUpdate::Notice(notice.into()));
267 }
268 }
269 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
270}
271
272pub(super) async fn record_track(
273 track: RtcAudioTrack,
274 recording: Arc<Mutex<Recording>>,
275 tone_hz: f32,
276) {
277 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
278 while let Some(frame) = stream.next().await {
279 let mut recording = recording.lock().await;
280 recording.samples.extend_from_slice(&frame.data);
281 recording.current_second.extend_from_slice(&frame.data);
282 if recording.current_second.len() >= SAMPLE_RATE as usize {
283 let second: Vec<i16> = std::mem::take(&mut recording.current_second);
284 let summary = (rms(&second), tone_ratio(&second, tone_hz));
285 recording.per_second.push(summary);
286 }
287 }
288}
crates/calling/src/call/bots.rs added +250 −0
@@ -0,0 +1,250 @@
1 use super::*;
2
3 pub(super) fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
4 own.is_some_and(|own| own.thread_id == target.thread_id)
5 }
6
7 pub(super) async fn save_meeting_options(
8 session: &session::Session,
9 target: &MeetingTarget,
10 writes: &[OptionWrite],
11 ) -> std::result::Result<meeting_options::MeetingOptions, String> {
12 for change in writes {
13 meeting_options::write(session, target, change)
14 .await
15 .map_err(|error| error.to_string())?;
16 }
17 meeting_options::fetch(session, target)
18 .await
19 .map_err(|error| error.to_string())
20 }
21
22 pub(super) fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
23 let display_name = roster
24 .members()
25 .iter()
26 .find(|member| member.mri == mri)
27 .map_or("", |member| member.display_name.as_str());
28 Target { mri, display_name }
29 }
30
31 pub(super) const RECORDING_STOP_RETRIES: usize = 6;
32
33 pub(super) const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5);
34
35 /// The recorder answers 409 to a stop sent while its start is still settling.
36 pub(super) fn recorder_busy(error: &Error) -> bool {
37 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
38 }
39
40 pub(super) fn report_organizer_result(
41 result: Result<u16>,
42 label: &str,
43 notice: &'static str,
44 control: &CallControl,
45 timeline: &Timeline,
46 ) {
47 if let Err(error) = &result {
48 timeline.record(format!("{label} failed"), error.to_string());
49 control.send(CallUpdate::Notice(notice.to_owned()));
50 }
51 control.send(CallUpdate::Organizer {
52 action: label.to_owned(),
53 outcome: result.map_err(|error| error.to_string()),
54 });
55 }
56
57 pub(super) fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
58 if entry.display_name.is_empty() {
59 entry.display_name = roster
60 .name_of(&entry.user_id)
61 .unwrap_or_default()
62 .to_owned();
63 }
64 entry
65 }
66
67 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
68 pub(super) enum BotJob {
69 Captions,
70 Recording,
71 }
72
73 #[allow(clippy::too_many_arguments)]
74 pub(super) async fn run_bot_steps(
75 job: BotJob,
76 flow: &mut CaptionFlow,
77 roster: &Roster,
78 remote: &RemoteCall,
79 links: &CallbackLinks,
80 meeting_chat: Option<&str>,
81 plan: &RecordingPlan,
82 bot_pending: &mut bool,
83 control: &CallControl,
84 timeline: &Timeline,
85 ) {
86 let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
87 BotJob::Captions => |bot| bot.active,
88 BotJob::Recording => |bot| bot.recording,
89 };
90 let fail = |flow: &mut CaptionFlow, reason: &str| {
91 flow.failed();
92 control.send(match job {
93 BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
94 BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
95 });
96 if job == BotJob::Recording {
97 control.send(CallUpdate::RecordingPending(false));
98 }
99 };
100 let (join_failure, start_failure) = match job {
101 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
102 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
103 };
104 loop {
105 match flow.next_for(roster.caption_bot(), is_active) {
106 CaptionStep::Wait => return,
107 CaptionStep::AddBot => {
108 if *bot_pending {
109 continue;
110 }
111 let Some(thread) = meeting_chat else {
112 return fail(
113 flow,
114 "This call has no chat for the captions and the recording",
115 );
116 };
117 *bot_pending = true;
118 let added = remote
119 .signaling
120 .add_caption_bot(
121 &remote.conversation,
122 &remote.participant,
123 thread,
124 links,
125 remote.threadless,
126 )
127 .await;
128 if job == BotJob::Recording {
129 report_organizer_result(
130 added
131 .as_ref()
132 .map(|status| *status)
133 .map_err(|error| Error::Signaling(error.to_string())),
134 "recording add bot",
135 join_failure,
136 control,
137 timeline,
138 );
139 }
140 if let Err(error) = added {
141 timeline.record("bot invitation failed", error.to_string());
142 *bot_pending = false;
143 return fail(flow, join_failure);
144 }
145 }
146 CaptionStep::Start => {
147 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
148 return;
149 };
150 match job {
151 BotJob::Captions => {
152 if let Err(error) = remote
153 .signaling
154 .caption_command(&url, BotAction::Start, &remote.participant)
155 .await
156 {
157 timeline.record("caption start failed", error.to_string());
158 return fail(flow, start_failure);
159 }
160 if let Err(error) = remote
161 .signaling
162 .set_caption_preference(&remote.conversation, &remote.participant, true)
163 .await
164 {
165 timeline.record("caption preference failed", error.to_string());
166 }
167 }
168 BotJob::Recording => {
169 let started = remote
170 .signaling
171 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
172 .await;
173 let failed = started.is_err();
174 report_organizer_result(
175 started,
176 "recording start",
177 start_failure,
178 control,
179 timeline,
180 );
181 if failed {
182 return fail(flow, start_failure);
183 }
184 }
185 }
186 }
187 CaptionStep::Stop => {
188 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
189 continue;
190 };
191 match job {
192 BotJob::Captions => {
193 if let Err(error) = remote
194 .signaling
195 .caption_command(&url, BotAction::Stop, &remote.participant)
196 .await
197 {
198 timeline.record("caption stop failed", error.to_string());
199 }
200 if let Err(error) = remote
201 .signaling
202 .set_caption_preference(
203 &remote.conversation,
204 &remote.participant,
205 false,
206 )
207 .await
208 {
209 timeline.record("caption preference failed", error.to_string());
210 }
211 }
212 BotJob::Recording => {
213 let remote = remote.clone();
214 let updates = control.updates();
215 let (command, title) = (plan.stop(), plan.title.clone());
216 tokio::spawn(async move {
217 let mut stopped = remote
218 .signaling
219 .recording_command(&url, command, &remote.participant, &title)
220 .await;
221 for _ in 0..RECORDING_STOP_RETRIES {
222 if !stopped.as_ref().is_err_and(recorder_busy) {
223 break;
224 }
225 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
226 stopped = remote
227 .signaling
228 .recording_command(&url, command, &remote.participant, &title)
229 .await;
230 }
231 if stopped.is_err() {
232 let _ = updates
233 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
234 }
235 let _ = updates.send(CallUpdate::Organizer {
236 action: "recording stop".into(),
237 outcome: stopped.map_err(|error| error.to_string()),
238 });
239 });
240 }
241 }
242 }
243 CaptionStep::ReportOn => {
244 if job == BotJob::Captions {
245 control.send(CallUpdate::Captions(CaptionState::On));
246 }
247 }
248 }
249 }
250 }
@@ -0,0 +1,250 @@
1use super::*;
2
3pub(super) fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
4 own.is_some_and(|own| own.thread_id == target.thread_id)
5}
6
7pub(super) async fn save_meeting_options(
8 session: &session::Session,
9 target: &MeetingTarget,
10 writes: &[OptionWrite],
11) -> std::result::Result<meeting_options::MeetingOptions, String> {
12 for change in writes {
13 meeting_options::write(session, target, change)
14 .await
15 .map_err(|error| error.to_string())?;
16 }
17 meeting_options::fetch(session, target)
18 .await
19 .map_err(|error| error.to_string())
20}
21
22pub(super) fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
23 let display_name = roster
24 .members()
25 .iter()
26 .find(|member| member.mri == mri)
27 .map_or("", |member| member.display_name.as_str());
28 Target { mri, display_name }
29}
30
31pub(super) const RECORDING_STOP_RETRIES: usize = 6;
32
33pub(super) const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5);
34
35/// The recorder answers 409 to a stop sent while its start is still settling.
36pub(super) fn recorder_busy(error: &Error) -> bool {
37 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
38}
39
40pub(super) fn report_organizer_result(
41 result: Result<u16>,
42 label: &str,
43 notice: &'static str,
44 control: &CallControl,
45 timeline: &Timeline,
46) {
47 if let Err(error) = &result {
48 timeline.record(format!("{label} failed"), error.to_string());
49 control.send(CallUpdate::Notice(notice.to_owned()));
50 }
51 control.send(CallUpdate::Organizer {
52 action: label.to_owned(),
53 outcome: result.map_err(|error| error.to_string()),
54 });
55}
56
57pub(super) fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
58 if entry.display_name.is_empty() {
59 entry.display_name = roster
60 .name_of(&entry.user_id)
61 .unwrap_or_default()
62 .to_owned();
63 }
64 entry
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq)]
68pub(super) enum BotJob {
69 Captions,
70 Recording,
71}
72
73#[allow(clippy::too_many_arguments)]
74pub(super) async fn run_bot_steps(
75 job: BotJob,
76 flow: &mut CaptionFlow,
77 roster: &Roster,
78 remote: &RemoteCall,
79 links: &CallbackLinks,
80 meeting_chat: Option<&str>,
81 plan: &RecordingPlan,
82 bot_pending: &mut bool,
83 control: &CallControl,
84 timeline: &Timeline,
85) {
86 let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
87 BotJob::Captions => |bot| bot.active,
88 BotJob::Recording => |bot| bot.recording,
89 };
90 let fail = |flow: &mut CaptionFlow, reason: &str| {
91 flow.failed();
92 control.send(match job {
93 BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
94 BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
95 });
96 if job == BotJob::Recording {
97 control.send(CallUpdate::RecordingPending(false));
98 }
99 };
100 let (join_failure, start_failure) = match job {
101 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
102 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
103 };
104 loop {
105 match flow.next_for(roster.caption_bot(), is_active) {
106 CaptionStep::Wait => return,
107 CaptionStep::AddBot => {
108 if *bot_pending {
109 continue;
110 }
111 let Some(thread) = meeting_chat else {
112 return fail(
113 flow,
114 "This call has no chat for the captions and the recording",
115 );
116 };
117 *bot_pending = true;
118 let added = remote
119 .signaling
120 .add_caption_bot(
121 &remote.conversation,
122 &remote.participant,
123 thread,
124 links,
125 remote.threadless,
126 )
127 .await;
128 if job == BotJob::Recording {
129 report_organizer_result(
130 added
131 .as_ref()
132 .map(|status| *status)
133 .map_err(|error| Error::Signaling(error.to_string())),
134 "recording add bot",
135 join_failure,
136 control,
137 timeline,
138 );
139 }
140 if let Err(error) = added {
141 timeline.record("bot invitation failed", error.to_string());
142 *bot_pending = false;
143 return fail(flow, join_failure);
144 }
145 }
146 CaptionStep::Start => {
147 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
148 return;
149 };
150 match job {
151 BotJob::Captions => {
152 if let Err(error) = remote
153 .signaling
154 .caption_command(&url, BotAction::Start, &remote.participant)
155 .await
156 {
157 timeline.record("caption start failed", error.to_string());
158 return fail(flow, start_failure);
159 }
160 if let Err(error) = remote
161 .signaling
162 .set_caption_preference(&remote.conversation, &remote.participant, true)
163 .await
164 {
165 timeline.record("caption preference failed", error.to_string());
166 }
167 }
168 BotJob::Recording => {
169 let started = remote
170 .signaling
171 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
172 .await;
173 let failed = started.is_err();
174 report_organizer_result(
175 started,
176 "recording start",
177 start_failure,
178 control,
179 timeline,
180 );
181 if failed {
182 return fail(flow, start_failure);
183 }
184 }
185 }
186 }
187 CaptionStep::Stop => {
188 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
189 continue;
190 };
191 match job {
192 BotJob::Captions => {
193 if let Err(error) = remote
194 .signaling
195 .caption_command(&url, BotAction::Stop, &remote.participant)
196 .await
197 {
198 timeline.record("caption stop failed", error.to_string());
199 }
200 if let Err(error) = remote
201 .signaling
202 .set_caption_preference(
203 &remote.conversation,
204 &remote.participant,
205 false,
206 )
207 .await
208 {
209 timeline.record("caption preference failed", error.to_string());
210 }
211 }
212 BotJob::Recording => {
213 let remote = remote.clone();
214 let updates = control.updates();
215 let (command, title) = (plan.stop(), plan.title.clone());
216 tokio::spawn(async move {
217 let mut stopped = remote
218 .signaling
219 .recording_command(&url, command, &remote.participant, &title)
220 .await;
221 for _ in 0..RECORDING_STOP_RETRIES {
222 if !stopped.as_ref().is_err_and(recorder_busy) {
223 break;
224 }
225 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
226 stopped = remote
227 .signaling
228 .recording_command(&url, command, &remote.participant, &title)
229 .await;
230 }
231 if stopped.is_err() {
232 let _ = updates
233 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
234 }
235 let _ = updates.send(CallUpdate::Organizer {
236 action: "recording stop".into(),
237 outcome: stopped.map_err(|error| error.to_string()),
238 });
239 });
240 }
241 }
242 }
243 CaptionStep::ReportOn => {
244 if job == BotJob::Captions {
245 control.send(CallUpdate::Captions(CaptionState::On));
246 }
247 }
248 }
249 }
250}
crates/calling/src/call/escalation.rs added +608 −0
@@ -0,0 +1,608 @@
1 use super::*;
2
3 pub(super) struct NextPeer {
4 pub(super) session: PeerSession,
5 pub(super) offered: Option<OfferedMedia>,
6 pub(super) answered: Option<AnsweredMedia>,
7 pub(super) leg_links: BTreeMap<String, String>,
8 pub(super) remote_audio: Option<RtcAudioTrack>,
9 pub(super) reply_tags: Vec<String>,
10 pub(super) deadline: Option<Instant>,
11 pub(super) connected: bool,
12 pub(super) retargeted: bool,
13 }
14
15 pub(super) async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
16 match next {
17 Some(next) => next.session.events.recv().await,
18 None => std::future::pending().await,
19 }
20 }
21
22 pub(super) fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
23 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
24 }
25
26 /// Re-queuing while `next` is set spins the call task (defer -> pending -> defer...).
27 pub(super) fn camera_may_start(pending: bool, next_is_some: bool, possible: bool) -> bool {
28 pending && !next_is_some && possible
29 }
30
31 #[allow(clippy::too_many_arguments)]
32 pub(super) async fn start_escalation(
33 factory: &PeerConnectionFactory,
34 grant: &RelayGrant,
35 options: &CallOptions,
36 track: &RtcAudioTrack,
37 remote: &RemoteCall,
38 links: &CallbackLinks,
39 media_leg_id: &str,
40 acceptance_links: &BTreeMap<String, String>,
41 ) -> Result<NextPeer> {
42 let url = acceptance_links
43 .get("mediaRenegotiation")
44 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
45 let session = open_peer(factory, grant, &options.relay_host, false)?;
46 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
47 let body = renegotiation_body(
48 &remote.participant,
49 links,
50 &media.signaled.sdp,
51 media_leg_id,
52 &media.modalities,
53 true,
54 false,
55 );
56 let reply_tags = offer_reply_tags(&body);
57 remote
58 .signaling
59 .post_json("POST mediaRenegotiation", url, body)
60 .await?;
61 Ok(NextPeer {
62 session,
63 offered: Some(media),
64 answered: None,
65 leg_links: acceptance_links.clone(),
66 remote_audio: None,
67 reply_tags,
68 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
69 connected: false,
70 retargeted: false,
71 })
72 }
73
74 #[allow(clippy::too_many_arguments)]
75 pub(super) async fn escalate(
76 factory: &PeerConnectionFactory,
77 grant: &RelayGrant,
78 options: &CallOptions,
79 track: &RtcAudioTrack,
80 remote: &RemoteCall,
81 links: &CallbackLinks,
82 media_leg_id: &str,
83 acceptance_links: &BTreeMap<String, String>,
84 negotiator: &mut MediaNegotiator,
85 live: &mut Live,
86 timeline: &Timeline,
87 ) -> Option<NextPeer> {
88 match start_escalation(
89 factory,
90 grant,
91 options,
92 track,
93 remote,
94 links,
95 media_leg_id,
96 acceptance_links,
97 )
98 .await
99 {
100 Ok(pending) => {
101 timeline.record("escalation", "new peer connection, new offer sent");
102 if let Some(media) = &pending.offered {
103 timeline.record_sdp("local offer", &media.signaled.sdp);
104 }
105 live.peers.push(pending.session.peer.clone());
106 Some(pending)
107 }
108 Err(error) => {
109 negotiator.escalation_failed();
110 timeline.record("escalation failed", error.to_string());
111 None
112 }
113 }
114 }
115
116 #[allow(clippy::too_many_arguments)]
117 pub(super) async fn answer_on_new_peer(
118 factory: &PeerConnectionFactory,
119 grant: &RelayGrant,
120 options: &CallOptions,
121 track: &RtcAudioTrack,
122 teams_offer: &str,
123 camera_on: bool,
124 camera: Option<&RtcVideoTrack>,
125 share: Option<&RtcVideoTrack>,
126 ) -> Result<(PeerSession, AnsweredMedia)> {
127 let session = open_peer(factory, grant, &options.relay_host, false)?;
128 // Keep every video mid from the mixer offer (camera, gallery, share).
129 // Reject would stop them and leave set_track InvalidState after the new
130 // peer replaces the old one. When the camera is already on, answer sendrecv
131 // so the remote keeps receiving across the escalation.
132 let video = match (camera_on, camera) {
133 (true, Some(camera)) => AnswerVideo::Send(camera),
134 _ => AnswerVideo::Receive,
135 };
136 let answered = answer_offer_with(
137 &session.peer,
138 Some(track),
139 teams_offer,
140 video,
141 None,
142 share,
143 camera_on,
144 None,
145 true,
146 true,
147 )
148 .await?;
149 Ok((session, answered))
150 }
151
152 pub(super) fn video_lines_from_answer(
153 peer: &PeerConnection,
154 answered: &AnsweredMedia,
155 ) -> Option<VideoLines> {
156 let camera_mid = answered.camera_mid.as_deref()?;
157 let camera = peer_transceiver(peer, camera_mid)?;
158 let share = share_carrier_mid(&answered.remote).and_then(|mid| peer_transceiver(peer, &mid));
159 Some(VideoLines { camera, share })
160 }
161
162 pub(super) async fn send_media_answer(
163 remote: &RemoteCall,
164 links: &CallbackLinks,
165 reply_links: &BTreeMap<String, String>,
166 answered: &AnsweredMedia,
167 media_leg_id: &str,
168 ) -> Result<(BTreeMap<String, String>, String)> {
169 let url = reply_links
170 .get("mediaAnswer")
171 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
172 let body = escalation_answer_body(
173 &remote.participant,
174 links,
175 &answered.answer_sdp,
176 media_leg_id,
177 );
178 let response = remote
179 .signaling
180 .post_json_body("POST mediaAnswer", url, body)
181 .await?;
182 Ok((nested_links(&response), object_keys(&response)))
183 }
184
185 pub(super) fn absorb_answered_links(
186 into: &mut BTreeMap<String, String>,
187 extra: &BTreeMap<String, String>,
188 timeline: &Timeline,
189 response_keys: &str,
190 ) {
191 if extra.is_empty() {
192 if !response_keys.is_empty() {
193 timeline.record(
194 "media answer links",
195 format!("none, body keys {response_keys}"),
196 );
197 }
198 return;
199 }
200 let names = extra.keys().cloned().collect::<Vec<_>>().join(",");
201 timeline.record("media answer links", names);
202 into.extend(extra.clone());
203 }
204
205 #[allow(clippy::too_many_arguments)]
206 pub(super) fn negotiate_video(
207 video: &mut VideoReceive,
208 signaling: &Arc<Signaling>,
209 control: &CallControl,
210 timeline: &Timeline,
211 answer_sdp: &str,
212 media: &OfferedMedia,
213 from_mixer: bool,
214 links: &BTreeMap<String, String>,
215 roster: &Roster,
216 ) {
217 negotiate_video_lines(
218 video,
219 signaling,
220 control,
221 timeline,
222 answer_sdp,
223 &media.signaled.lines,
224 from_mixer,
225 links,
226 roster,
227 );
228 }
229
230 #[allow(clippy::too_many_arguments)]
231 pub(super) fn negotiate_video_lines(
232 video: &mut VideoReceive,
233 signaling: &Arc<Signaling>,
234 control: &CallControl,
235 timeline: &Timeline,
236 teams_sdp: &str,
237 lines: &[crate::sdp::SignaledLine],
238 from_mixer: bool,
239 links: &BTreeMap<String, String>,
240 roster: &Roster,
241 ) {
242 let streams = match stream_lines(teams_sdp, lines) {
243 Ok(streams) => streams,
244 Err(error) => {
245 timeline.record("video slots unknown", error.to_string());
246 return;
247 }
248 };
249 let table = SlotTable::from_streams(&streams);
250 let link = links
251 .get("applyChannelParameters")
252 .or_else(|| links.get("controlVideoStreaming"));
253 timeline.record(
254 "video slots",
255 format!(
256 "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}",
257 table.people.len(),
258 table.screen.is_some(),
259 link.is_some()
260 ),
261 );
262 let requester = link.filter(|_| from_mixer).map(|url| {
263 SourceRequester::start(
264 signaling.clone(),
265 url.clone(),
266 video.router().clone(),
267 control.video.clone(),
268 timeline.clone(),
269 )
270 });
271 video.negotiated(table, requester);
272 send_receive_change(control, video.reselect(roster));
273 }
274
275 pub(super) fn tell_bound_camera(
276 remote: &RemoteCall,
277 links: &BTreeMap<String, String>,
278 local_video: &LocalVideo,
279 request_id: &mut u32,
280 timeline: &Timeline,
281 ) {
282 let mid = local_video
283 .camera_mid()
284 .unwrap_or_else(|| CAMERA_MID.to_owned());
285 tell_media_descriptions(
286 remote,
287 links,
288 MediaDescription::camera_line(mid, local_video.camera_on()),
289 request_id,
290 timeline,
291 );
292 }
293
294 pub(super) fn tell_bound_share(
295 remote: &RemoteCall,
296 links: &BTreeMap<String, String>,
297 local_video: &LocalVideo,
298 request_id: &mut u32,
299 timeline: &Timeline,
300 ) {
301 if !local_video.sharing() {
302 return;
303 }
304 let mid = local_video
305 .share_mid()
306 .unwrap_or_else(|| SHARE_MID.to_owned());
307 tell_media_descriptions(
308 remote,
309 links,
310 MediaDescription::share_line(mid, true),
311 request_id,
312 timeline,
313 );
314 }
315
316 pub(super) async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
317 match mode {
318 VideoMode::Pattern => vec![CameraDevice {
319 key: "pattern".into(),
320 name: "Test pattern".into(),
321 }],
322 VideoMode::Off => Vec::new(),
323 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
324 .await
325 .unwrap_or_default(),
326 }
327 }
328
329 pub(super) fn refresh_cameras(
330 updates: mpsc::UnboundedSender<CallUpdate>,
331 mode: VideoMode,
332 timeline: Timeline,
333 ) {
334 tokio::spawn(async move {
335 let started = Instant::now();
336 let cameras = camera_devices(mode).await;
337 timeline.record(
338 "camera list",
339 format!(
340 "{} camera(s) in {} ms",
341 cameras.len(),
342 started.elapsed().as_millis()
343 ),
344 );
345 let _ = updates.send(CallUpdate::Cameras(cameras));
346 });
347 }
348
349 pub(super) const SHARE_THUMBNAIL_WINDOWS: usize = 12;
350
351 pub(super) const SHARE_THUMBNAIL_WIDTH: u32 = 320;
352
353 pub(super) const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
354
355 pub(super) fn announce_share(control: &CallControl, source: &ShareSource) {
356 control.send(CallUpdate::ShareKind(Some(source.kind)));
357 control.send(CallUpdate::LocalShare(Some(source.label())));
358 }
359
360 pub(super) fn clear_share(control: &CallControl) {
361 control.send(CallUpdate::ShareKind(None));
362 control.send(CallUpdate::LocalShare(None));
363 }
364
365 pub(super) fn refresh_share_sources(
366 updates: mpsc::UnboundedSender<CallUpdate>,
367 mode: VideoMode,
368 with_thumbnails: bool,
369 ) {
370 tokio::spawn(async move {
371 let picker = current_share_picker();
372 let sources = match mode {
373 VideoMode::Pattern => vec![
374 ShareSource {
375 id: 1,
376 kind: ShareKind::Screen,
377 title: "Test screen".into(),
378 },
379 ShareSource {
380 id: 2,
381 kind: ShareKind::Window,
382 title: "Test window".into(),
383 },
384 ],
385 VideoMode::Off => Vec::new(),
386 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
387 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
388 .await
389 .unwrap_or_default(),
390 };
391 let sources = share_sources_for_menu(picker, sources);
392 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
393 if picker == SharePicker::Portal || !with_thumbnails {
394 return;
395 }
396 let wanted: Vec<ShareSource> = sources
397 .iter()
398 .filter(|source| source.kind == ShareKind::Screen)
399 .chain(
400 sources
401 .iter()
402 .filter(|source| source.kind == ShareKind::Window)
403 .take(SHARE_THUMBNAIL_WINDOWS),
404 )
405 .cloned()
406 .collect();
407 for source in wanted {
408 let picture = match mode {
409 VideoMode::Platform => {
410 let wanted = source.clone();
411 tokio::task::spawn_blocking(move || {
412 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
413 })
414 .await
415 .ok()
416 .flatten()
417 }
418 VideoMode::Pattern => Some(VideoPicture::solid(
419 SHARE_THUMBNAIL_WIDTH,
420 SHARE_THUMBNAIL_HEIGHT,
421 120,
422 80,
423 40,
424 )),
425 VideoMode::Off => None,
426 };
427 if let Some(picture) = picture
428 && updates
429 .send(CallUpdate::ShareThumbnail {
430 source,
431 picture: Arc::new(picture),
432 })
433 .is_err()
434 {
435 return;
436 }
437 }
438 });
439 }
440
441 pub(super) fn tell_media_descriptions(
442 remote: &RemoteCall,
443 links: &BTreeMap<String, String>,
444 description: MediaDescription,
445 request_id: &mut u32,
446 timeline: &Timeline,
447 ) {
448 let Some(url) = links.get("updateMediaDescriptions").cloned() else {
449 timeline.record("updateMediaDescriptions skipped", "no link from the mixer");
450 return;
451 };
452 *request_id += 1;
453 let request_id = *request_id;
454 let signaling = remote.signaling.clone();
455 let timeline = timeline.clone();
456 tokio::spawn(async move {
457 let sent = format!(
458 "{} {} request {request_id}",
459 description.mid, description.direction
460 );
461 if let Err(error) = signaling
462 .update_media_descriptions(&url, &[description], request_id)
463 .await
464 {
465 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
466 }
467 });
468 }
469
470 pub(super) fn attach_share_line(
471 peer: &PeerConnection,
472 factory: &PeerConnectionFactory,
473 local_video: &mut LocalVideo,
474 camera_mid: Option<&str>,
475 ) -> Result<()> {
476 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
477 if !local_video.has_lines() && camera.is_none() {
478 return Err(Error::Webrtc("no video line negotiated".into()));
479 }
480 let share = add_share_line(peer, factory)?;
481 local_video
482 .add_share_line(share.clone(), camera)
483 .inspect_err(|_| {
484 let _ = share.stop();
485 })
486 }
487
488 pub(super) fn start_camera_line(
489 local_video: &mut LocalVideo,
490 peer: &PeerConnection,
491 direct_mid: Option<&str>,
492 choice: &DeviceChoice,
493 ) -> Result<()> {
494 if !local_video.has_lines() {
495 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
496 let camera = peer_transceiver(peer, mid)
497 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
498 if !matches!(
499 camera.direction(),
500 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
501 ) {
502 peer.add_track(
503 MediaStreamTrack::Video(local_video.camera_track()),
504 &[CAMERA_STREAM],
505 )
506 .map_err(|error| Error::Webrtc(error.to_string()))?;
507 }
508 local_video.set_lines(VideoLines {
509 camera,
510 share: None,
511 })?;
512 }
513 local_video.start_camera(choice)
514 }
515
516 pub(super) fn defer_to_new_peer(
517 change: Change,
518 deferred: &mut Vec<Change>,
519 local_video: &mut LocalVideo,
520 control: &CallControl,
521 ) {
522 match change {
523 Change::Camera(true) => {
524 control.send(CallUpdate::Camera(true));
525 deferred.push(change);
526 }
527 Change::Share(true) => deferred.push(change),
528 change => undo_change(change, local_video, control),
529 }
530 }
531
532 /// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
533 pub(super) fn settle_failed_escalation(
534 server: bool,
535 layout: Layout,
536 negotiator: &mut MediaNegotiator,
537 deferred: &mut Vec<Change>,
538 local_video: &mut LocalVideo,
539 control: &CallControl,
540 ) {
541 if server {
542 negotiator.server_escalation_failed();
543 for change in deferred.drain(..) {
544 undo_change(change, local_video, control);
545 }
546 } else if layout == Layout::OneToOne {
547 drop_local_media(local_video, control);
548 }
549 }
550
551 pub(super) fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
552 if local_video.sharing() {
553 local_video.stop_share();
554 clear_share(control);
555 }
556 if local_video.camera_on() {
557 local_video.stop_camera();
558 control.send(CallUpdate::Camera(false));
559 }
560 }
561
562 pub(super) fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
563 match change {
564 Change::Camera(true) => {
565 local_video.stop_camera();
566 control.send(CallUpdate::Camera(false));
567 }
568 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
569 Change::Share(true) => {
570 local_video.stop_share();
571 clear_share(control);
572 control.send(CallUpdate::Notice(notice_with_detail(
573 SHARING_START_NOTICE,
574 "",
575 )));
576 }
577 Change::Share(false) => {}
578 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
579 }
580 }
581
582 pub(super) async fn apply_background(
583 choice: BackgroundChoice,
584 local_video: &LocalVideo,
585 control: &CallControl,
586 timeline: &Timeline,
587 ) {
588 match choice {
589 BackgroundChoice::None => local_video.set_background(false, None),
590 BackgroundChoice::Blur => local_video.set_background(true, None),
591 BackgroundChoice::Image(path) => {
592 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
593 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
594 Ok(Err(error)) => {
595 timeline.record("background image failed", error.to_string());
596 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
597 }
598 Err(_) => {}
599 }
600 }
601 }
602 }
603
604 pub(super) fn send_receive_change(control: &CallControl, change: ReceiveChange) {
605 if let Some(sharer) = change.screen_sharer {
606 control.send(CallUpdate::ScreenShare(sharer));
607 }
608 }
@@ -0,0 +1,608 @@
1use super::*;
2
3pub(super) struct NextPeer {
4 pub(super) session: PeerSession,
5 pub(super) offered: Option<OfferedMedia>,
6 pub(super) answered: Option<AnsweredMedia>,
7 pub(super) leg_links: BTreeMap<String, String>,
8 pub(super) remote_audio: Option<RtcAudioTrack>,
9 pub(super) reply_tags: Vec<String>,
10 pub(super) deadline: Option<Instant>,
11 pub(super) connected: bool,
12 pub(super) retargeted: bool,
13}
14
15pub(super) async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
16 match next {
17 Some(next) => next.session.events.recv().await,
18 None => std::future::pending().await,
19 }
20}
21
22pub(super) fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
23 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
24}
25
26/// Re-queuing while `next` is set spins the call task (defer -> pending -> defer...).
27pub(super) fn camera_may_start(pending: bool, next_is_some: bool, possible: bool) -> bool {
28 pending && !next_is_some && possible
29}
30
31#[allow(clippy::too_many_arguments)]
32pub(super) async fn start_escalation(
33 factory: &PeerConnectionFactory,
34 grant: &RelayGrant,
35 options: &CallOptions,
36 track: &RtcAudioTrack,
37 remote: &RemoteCall,
38 links: &CallbackLinks,
39 media_leg_id: &str,
40 acceptance_links: &BTreeMap<String, String>,
41) -> Result<NextPeer> {
42 let url = acceptance_links
43 .get("mediaRenegotiation")
44 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
45 let session = open_peer(factory, grant, &options.relay_host, false)?;
46 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
47 let body = renegotiation_body(
48 &remote.participant,
49 links,
50 &media.signaled.sdp,
51 media_leg_id,
52 &media.modalities,
53 true,
54 false,
55 );
56 let reply_tags = offer_reply_tags(&body);
57 remote
58 .signaling
59 .post_json("POST mediaRenegotiation", url, body)
60 .await?;
61 Ok(NextPeer {
62 session,
63 offered: Some(media),
64 answered: None,
65 leg_links: acceptance_links.clone(),
66 remote_audio: None,
67 reply_tags,
68 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
69 connected: false,
70 retargeted: false,
71 })
72}
73
74#[allow(clippy::too_many_arguments)]
75pub(super) async fn escalate(
76 factory: &PeerConnectionFactory,
77 grant: &RelayGrant,
78 options: &CallOptions,
79 track: &RtcAudioTrack,
80 remote: &RemoteCall,
81 links: &CallbackLinks,
82 media_leg_id: &str,
83 acceptance_links: &BTreeMap<String, String>,
84 negotiator: &mut MediaNegotiator,
85 live: &mut Live,
86 timeline: &Timeline,
87) -> Option<NextPeer> {
88 match start_escalation(
89 factory,
90 grant,
91 options,
92 track,
93 remote,
94 links,
95 media_leg_id,
96 acceptance_links,
97 )
98 .await
99 {
100 Ok(pending) => {
101 timeline.record("escalation", "new peer connection, new offer sent");
102 if let Some(media) = &pending.offered {
103 timeline.record_sdp("local offer", &media.signaled.sdp);
104 }
105 live.peers.push(pending.session.peer.clone());
106 Some(pending)
107 }
108 Err(error) => {
109 negotiator.escalation_failed();
110 timeline.record("escalation failed", error.to_string());
111 None
112 }
113 }
114}
115
116#[allow(clippy::too_many_arguments)]
117pub(super) async fn answer_on_new_peer(
118 factory: &PeerConnectionFactory,
119 grant: &RelayGrant,
120 options: &CallOptions,
121 track: &RtcAudioTrack,
122 teams_offer: &str,
123 camera_on: bool,
124 camera: Option<&RtcVideoTrack>,
125 share: Option<&RtcVideoTrack>,
126) -> Result<(PeerSession, AnsweredMedia)> {
127 let session = open_peer(factory, grant, &options.relay_host, false)?;
128 // Keep every video mid from the mixer offer (camera, gallery, share).
129 // Reject would stop them and leave set_track InvalidState after the new
130 // peer replaces the old one. When the camera is already on, answer sendrecv
131 // so the remote keeps receiving across the escalation.
132 let video = match (camera_on, camera) {
133 (true, Some(camera)) => AnswerVideo::Send(camera),
134 _ => AnswerVideo::Receive,
135 };
136 let answered = answer_offer_with(
137 &session.peer,
138 Some(track),
139 teams_offer,
140 video,
141 None,
142 share,
143 camera_on,
144 None,
145 true,
146 true,
147 )
148 .await?;
149 Ok((session, answered))
150}
151
152pub(super) fn video_lines_from_answer(
153 peer: &PeerConnection,
154 answered: &AnsweredMedia,
155) -> Option<VideoLines> {
156 let camera_mid = answered.camera_mid.as_deref()?;
157 let camera = peer_transceiver(peer, camera_mid)?;
158 let share = share_carrier_mid(&answered.remote).and_then(|mid| peer_transceiver(peer, &mid));
159 Some(VideoLines { camera, share })
160}
161
162pub(super) async fn send_media_answer(
163 remote: &RemoteCall,
164 links: &CallbackLinks,
165 reply_links: &BTreeMap<String, String>,
166 answered: &AnsweredMedia,
167 media_leg_id: &str,
168) -> Result<(BTreeMap<String, String>, String)> {
169 let url = reply_links
170 .get("mediaAnswer")
171 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
172 let body = escalation_answer_body(
173 &remote.participant,
174 links,
175 &answered.answer_sdp,
176 media_leg_id,
177 );
178 let response = remote
179 .signaling
180 .post_json_body("POST mediaAnswer", url, body)
181 .await?;
182 Ok((nested_links(&response), object_keys(&response)))
183}
184
185pub(super) fn absorb_answered_links(
186 into: &mut BTreeMap<String, String>,
187 extra: &BTreeMap<String, String>,
188 timeline: &Timeline,
189 response_keys: &str,
190) {
191 if extra.is_empty() {
192 if !response_keys.is_empty() {
193 timeline.record(
194 "media answer links",
195 format!("none, body keys {response_keys}"),
196 );
197 }
198 return;
199 }
200 let names = extra.keys().cloned().collect::<Vec<_>>().join(",");
201 timeline.record("media answer links", names);
202 into.extend(extra.clone());
203}
204
205#[allow(clippy::too_many_arguments)]
206pub(super) fn negotiate_video(
207 video: &mut VideoReceive,
208 signaling: &Arc<Signaling>,
209 control: &CallControl,
210 timeline: &Timeline,
211 answer_sdp: &str,
212 media: &OfferedMedia,
213 from_mixer: bool,
214 links: &BTreeMap<String, String>,
215 roster: &Roster,
216) {
217 negotiate_video_lines(
218 video,
219 signaling,
220 control,
221 timeline,
222 answer_sdp,
223 &media.signaled.lines,
224 from_mixer,
225 links,
226 roster,
227 );
228}
229
230#[allow(clippy::too_many_arguments)]
231pub(super) fn negotiate_video_lines(
232 video: &mut VideoReceive,
233 signaling: &Arc<Signaling>,
234 control: &CallControl,
235 timeline: &Timeline,
236 teams_sdp: &str,
237 lines: &[crate::sdp::SignaledLine],
238 from_mixer: bool,
239 links: &BTreeMap<String, String>,
240 roster: &Roster,
241) {
242 let streams = match stream_lines(teams_sdp, lines) {
243 Ok(streams) => streams,
244 Err(error) => {
245 timeline.record("video slots unknown", error.to_string());
246 return;
247 }
248 };
249 let table = SlotTable::from_streams(&streams);
250 let link = links
251 .get("applyChannelParameters")
252 .or_else(|| links.get("controlVideoStreaming"));
253 timeline.record(
254 "video slots",
255 format!(
256 "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}",
257 table.people.len(),
258 table.screen.is_some(),
259 link.is_some()
260 ),
261 );
262 let requester = link.filter(|_| from_mixer).map(|url| {
263 SourceRequester::start(
264 signaling.clone(),
265 url.clone(),
266 video.router().clone(),
267 control.video.clone(),
268 timeline.clone(),
269 )
270 });
271 video.negotiated(table, requester);
272 send_receive_change(control, video.reselect(roster));
273}
274
275pub(super) fn tell_bound_camera(
276 remote: &RemoteCall,
277 links: &BTreeMap<String, String>,
278 local_video: &LocalVideo,
279 request_id: &mut u32,
280 timeline: &Timeline,
281) {
282 let mid = local_video
283 .camera_mid()
284 .unwrap_or_else(|| CAMERA_MID.to_owned());
285 tell_media_descriptions(
286 remote,
287 links,
288 MediaDescription::camera_line(mid, local_video.camera_on()),
289 request_id,
290 timeline,
291 );
292}
293
294pub(super) fn tell_bound_share(
295 remote: &RemoteCall,
296 links: &BTreeMap<String, String>,
297 local_video: &LocalVideo,
298 request_id: &mut u32,
299 timeline: &Timeline,
300) {
301 if !local_video.sharing() {
302 return;
303 }
304 let mid = local_video
305 .share_mid()
306 .unwrap_or_else(|| SHARE_MID.to_owned());
307 tell_media_descriptions(
308 remote,
309 links,
310 MediaDescription::share_line(mid, true),
311 request_id,
312 timeline,
313 );
314}
315
316pub(super) async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
317 match mode {
318 VideoMode::Pattern => vec![CameraDevice {
319 key: "pattern".into(),
320 name: "Test pattern".into(),
321 }],
322 VideoMode::Off => Vec::new(),
323 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
324 .await
325 .unwrap_or_default(),
326 }
327}
328
329pub(super) fn refresh_cameras(
330 updates: mpsc::UnboundedSender<CallUpdate>,
331 mode: VideoMode,
332 timeline: Timeline,
333) {
334 tokio::spawn(async move {
335 let started = Instant::now();
336 let cameras = camera_devices(mode).await;
337 timeline.record(
338 "camera list",
339 format!(
340 "{} camera(s) in {} ms",
341 cameras.len(),
342 started.elapsed().as_millis()
343 ),
344 );
345 let _ = updates.send(CallUpdate::Cameras(cameras));
346 });
347}
348
349pub(super) const SHARE_THUMBNAIL_WINDOWS: usize = 12;
350
351pub(super) const SHARE_THUMBNAIL_WIDTH: u32 = 320;
352
353pub(super) const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
354
355pub(super) fn announce_share(control: &CallControl, source: &ShareSource) {
356 control.send(CallUpdate::ShareKind(Some(source.kind)));
357 control.send(CallUpdate::LocalShare(Some(source.label())));
358}
359
360pub(super) fn clear_share(control: &CallControl) {
361 control.send(CallUpdate::ShareKind(None));
362 control.send(CallUpdate::LocalShare(None));
363}
364
365pub(super) fn refresh_share_sources(
366 updates: mpsc::UnboundedSender<CallUpdate>,
367 mode: VideoMode,
368 with_thumbnails: bool,
369) {
370 tokio::spawn(async move {
371 let picker = current_share_picker();
372 let sources = match mode {
373 VideoMode::Pattern => vec![
374 ShareSource {
375 id: 1,
376 kind: ShareKind::Screen,
377 title: "Test screen".into(),
378 },
379 ShareSource {
380 id: 2,
381 kind: ShareKind::Window,
382 title: "Test window".into(),
383 },
384 ],
385 VideoMode::Off => Vec::new(),
386 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
387 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
388 .await
389 .unwrap_or_default(),
390 };
391 let sources = share_sources_for_menu(picker, sources);
392 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
393 if picker == SharePicker::Portal || !with_thumbnails {
394 return;
395 }
396 let wanted: Vec<ShareSource> = sources
397 .iter()
398 .filter(|source| source.kind == ShareKind::Screen)
399 .chain(
400 sources
401 .iter()
402 .filter(|source| source.kind == ShareKind::Window)
403 .take(SHARE_THUMBNAIL_WINDOWS),
404 )
405 .cloned()
406 .collect();
407 for source in wanted {
408 let picture = match mode {
409 VideoMode::Platform => {
410 let wanted = source.clone();
411 tokio::task::spawn_blocking(move || {
412 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
413 })
414 .await
415 .ok()
416 .flatten()
417 }
418 VideoMode::Pattern => Some(VideoPicture::solid(
419 SHARE_THUMBNAIL_WIDTH,
420 SHARE_THUMBNAIL_HEIGHT,
421 120,
422 80,
423 40,
424 )),
425 VideoMode::Off => None,
426 };
427 if let Some(picture) = picture
428 && updates
429 .send(CallUpdate::ShareThumbnail {
430 source,
431 picture: Arc::new(picture),
432 })
433 .is_err()
434 {
435 return;
436 }
437 }
438 });
439}
440
441pub(super) fn tell_media_descriptions(
442 remote: &RemoteCall,
443 links: &BTreeMap<String, String>,
444 description: MediaDescription,
445 request_id: &mut u32,
446 timeline: &Timeline,
447) {
448 let Some(url) = links.get("updateMediaDescriptions").cloned() else {
449 timeline.record("updateMediaDescriptions skipped", "no link from the mixer");
450 return;
451 };
452 *request_id += 1;
453 let request_id = *request_id;
454 let signaling = remote.signaling.clone();
455 let timeline = timeline.clone();
456 tokio::spawn(async move {
457 let sent = format!(
458 "{} {} request {request_id}",
459 description.mid, description.direction
460 );
461 if let Err(error) = signaling
462 .update_media_descriptions(&url, &[description], request_id)
463 .await
464 {
465 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
466 }
467 });
468}
469
470pub(super) fn attach_share_line(
471 peer: &PeerConnection,
472 factory: &PeerConnectionFactory,
473 local_video: &mut LocalVideo,
474 camera_mid: Option<&str>,
475) -> Result<()> {
476 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
477 if !local_video.has_lines() && camera.is_none() {
478 return Err(Error::Webrtc("no video line negotiated".into()));
479 }
480 let share = add_share_line(peer, factory)?;
481 local_video
482 .add_share_line(share.clone(), camera)
483 .inspect_err(|_| {
484 let _ = share.stop();
485 })
486}
487
488pub(super) fn start_camera_line(
489 local_video: &mut LocalVideo,
490 peer: &PeerConnection,
491 direct_mid: Option<&str>,
492 choice: &DeviceChoice,
493) -> Result<()> {
494 if !local_video.has_lines() {
495 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
496 let camera = peer_transceiver(peer, mid)
497 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
498 if !matches!(
499 camera.direction(),
500 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
501 ) {
502 peer.add_track(
503 MediaStreamTrack::Video(local_video.camera_track()),
504 &[CAMERA_STREAM],
505 )
506 .map_err(|error| Error::Webrtc(error.to_string()))?;
507 }
508 local_video.set_lines(VideoLines {
509 camera,
510 share: None,
511 })?;
512 }
513 local_video.start_camera(choice)
514}
515
516pub(super) fn defer_to_new_peer(
517 change: Change,
518 deferred: &mut Vec<Change>,
519 local_video: &mut LocalVideo,
520 control: &CallControl,
521) {
522 match change {
523 Change::Camera(true) => {
524 control.send(CallUpdate::Camera(true));
525 deferred.push(change);
526 }
527 Change::Share(true) => deferred.push(change),
528 change => undo_change(change, local_video, control),
529 }
530}
531
532/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
533pub(super) fn settle_failed_escalation(
534 server: bool,
535 layout: Layout,
536 negotiator: &mut MediaNegotiator,
537 deferred: &mut Vec<Change>,
538 local_video: &mut LocalVideo,
539 control: &CallControl,
540) {
541 if server {
542 negotiator.server_escalation_failed();
543 for change in deferred.drain(..) {
544 undo_change(change, local_video, control);
545 }
546 } else if layout == Layout::OneToOne {
547 drop_local_media(local_video, control);
548 }
549}
550
551pub(super) fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
552 if local_video.sharing() {
553 local_video.stop_share();
554 clear_share(control);
555 }
556 if local_video.camera_on() {
557 local_video.stop_camera();
558 control.send(CallUpdate::Camera(false));
559 }
560}
561
562pub(super) fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
563 match change {
564 Change::Camera(true) => {
565 local_video.stop_camera();
566 control.send(CallUpdate::Camera(false));
567 }
568 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
569 Change::Share(true) => {
570 local_video.stop_share();
571 clear_share(control);
572 control.send(CallUpdate::Notice(notice_with_detail(
573 SHARING_START_NOTICE,
574 "",
575 )));
576 }
577 Change::Share(false) => {}
578 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
579 }
580}
581
582pub(super) async fn apply_background(
583 choice: BackgroundChoice,
584 local_video: &LocalVideo,
585 control: &CallControl,
586 timeline: &Timeline,
587) {
588 match choice {
589 BackgroundChoice::None => local_video.set_background(false, None),
590 BackgroundChoice::Blur => local_video.set_background(true, None),
591 BackgroundChoice::Image(path) => {
592 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
593 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
594 Ok(Err(error)) => {
595 timeline.record("background image failed", error.to_string());
596 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
597 }
598 Err(_) => {}
599 }
600 }
601 }
602}
603
604pub(super) fn send_receive_change(control: &CallControl, change: ReceiveChange) {
605 if let Some(sharer) = change.screen_sharer {
606 control.send(CallUpdate::ScreenShare(sharer));
607 }
608}
crates/calling/src/call.rs crates/calling/src/call/mod.rs renamed +10 −2382
@@ -1,9 +1,18 @@
1 mod audio_switch;
2 mod bots;
3 mod escalation;
4 mod peer_sdp;
5 mod stats;
6 mod teardown;
7
1 8 use std::collections::BTreeMap;
2 9 use std::path::PathBuf;
3 10 use std::sync::Arc;
4 11 use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5 12 use std::time::Duration;
6 13
14 use self::{audio_switch::*, bots::*, escalation::*, peer_sdp::*, stats::*, teardown::*};
15
7 16 use chatsvc::TrouterCallback;
8 17 use futures_util::StreamExt;
9 18 use libwebrtc::audio_stream::native::NativeAudioStream;
@@ -308,86 +317,6 @@ fn random_u32() -> u32 {
308 317 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
309 318 }
310 319
311 #[derive(Default)]
312 struct Recording {
313 samples: Vec<i16>,
314 current_second: Vec<i16>,
315 per_second: Vec<(f32, f32)>,
316 }
317
318 enum PeerEvent {
319 Ice(IceConnectionState),
320 Connection(PeerConnectionState),
321 Track(RtcAudioTrack),
322 VideoTrack { mid: String, track: RtcVideoTrack },
323 Data(Vec<u8>),
324 }
325
326 struct PeerSession {
327 peer: PeerConnection,
328 events: mpsc::UnboundedReceiver<PeerEvent>,
329 _data_channel: Option<DataChannel>,
330 gathered: Gathered,
331 }
332
333 #[derive(Clone, Default)]
334 struct Gathered {
335 candidates: Arc<std::sync::Mutex<Vec<String>>>,
336 complete: Arc<AtomicBool>,
337 relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
338 waited_ms: Arc<AtomicU64>,
339 }
340
341 /// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
342 fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
343 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
344 }
345
346 impl Gathered {
347 fn settled(&self) -> bool {
348 let since_udp_relay = self
349 .relay_seen_at
350 .lock()
351 .expect("relay time lock")
352 .map(|at| at.elapsed());
353 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
354 }
355
356 async fn candidates(&self) -> Vec<String> {
357 let waited = Instant::now();
358 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
359 tokio::time::sleep(GATHERING_POLL).await;
360 }
361 self.complete.store(true, Ordering::SeqCst);
362 self.waited_ms
363 .store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
364 self.candidates.lock().expect("candidates lock").clone()
365 }
366
367 fn summary(&self) -> String {
368 let count = self.candidates.lock().expect("candidates lock").len();
369 format!(
370 "{count} candidate(s) after {} ms",
371 self.waited_ms.load(Ordering::SeqCst)
372 )
373 }
374 }
375
376 async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
377 match gathered {
378 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
379 None => Ok(teams_sdp.to_owned()),
380 }
381 }
382
383 struct OfferedMedia {
384 browser_offer: String,
385 signaled: SignaledOffer,
386 video: VideoLines,
387 plan: OfferPlan,
388 modalities: Vec<String>,
389 }
390
391 320 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
392 321 enum Layout {
393 322 Conference,
@@ -400,84 +329,6 @@ pub enum AcceptMode {
400 329 Video,
401 330 }
402 331
403 #[derive(Clone, Copy)]
404 enum AnswerVideo<'a> {
405 Reject,
406 Receive,
407 Send(&'a RtcVideoTrack),
408 }
409
410 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
411 enum Change {
412 Hold(bool),
413 Camera(bool),
414 Share(bool),
415 }
416
417 struct SamePeerOffer {
418 browser_offer: String,
419 signaled: SignaledOffer,
420 change: Change,
421 reply_tags: Vec<String>,
422 }
423
424 struct GlareResend {
425 change: Change,
426 reply_tags: Vec<String>,
427 at: Instant,
428 }
429
430 struct NextPeer {
431 session: PeerSession,
432 offered: Option<OfferedMedia>,
433 answered: Option<AnsweredMedia>,
434 leg_links: BTreeMap<String, String>,
435 remote_audio: Option<RtcAudioTrack>,
436 reply_tags: Vec<String>,
437 deadline: Option<Instant>,
438 connected: bool,
439 retargeted: bool,
440 }
441
442 /// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced.
443 fn replace_leg_media_links(
444 media_links: &mut BTreeMap<String, String>,
445 leg_links: &BTreeMap<String, String>,
446 ) {
447 media_links.extend(leg_links.clone());
448 }
449
450 fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
451 match callback_tag(callback_path) {
452 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
453 _ => true,
454 }
455 }
456
457 #[derive(Clone)]
458 struct RemoteCall {
459 signaling: Arc<Signaling>,
460 conversation: Conversation,
461 participant: Participant,
462 threadless: bool,
463 }
464
465 #[derive(Default)]
466 struct Live {
467 peers: Vec<PeerConnection>,
468 audio: Option<AudioSetup>,
469 remote: Option<RemoteCall>,
470 broker: Option<JoinHandle<()>>,
471 broker_running: Arc<AtomicBool>,
472 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
473 route_id: Option<String>,
474 call_legs: Vec<String>,
475 skip_leave: bool,
476 cancel_leave: bool,
477 video_tasks: Vec<JoinHandle<()>>,
478 video_counters: Arc<VideoCounters>,
479 }
480
481 332 fn remember_call_leg(live: &mut Live, url: Option<&str>) {
482 333 let Some(url) = url.filter(|url| !url.is_empty()) else {
483 334 return;
@@ -618,383 +469,6 @@ impl CallEngine {
618 469 }
619 470 }
620 471
621 fn open_peer(
622 factory: &PeerConnectionFactory,
623 grant: &RelayGrant,
624 relay_host: &str,
625 with_data_channel: bool,
626 ) -> Result<PeerSession> {
627 let mut configuration = RtcConfiguration::default();
628 configuration.ice_servers = vec![grant.ice_server(relay_host)];
629 let peer = factory
630 .create_peer_connection(configuration)
631 .map_err(|error| Error::Webrtc(error.to_string()))?;
632 let (sender, events) = mpsc::unbounded_channel();
633 let data_channel = with_data_channel
634 .then(|| open_data_channel(&peer, sender.clone()))
635 .transpose()?;
636 let gathered = Gathered::default();
637 let candidate_sink = gathered.candidates.clone();
638 let relay_seen_at = gathered.relay_seen_at.clone();
639 peer.on_ice_candidate(Some(Box::new(move |candidate| {
640 if candidate.sdp_mline_index() == 0 {
641 let text = candidate.candidate();
642 if is_udp_relay(&text) {
643 relay_seen_at
644 .lock()
645 .expect("relay time lock")
646 .get_or_insert_with(Instant::now);
647 }
648 candidate_sink.lock().expect("candidates lock").push(text);
649 }
650 })));
651 let gathering_done = gathered.complete.clone();
652 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
653 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
654 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
655 IceGatheringState::New => {}
656 })));
657 let ice_sender = sender.clone();
658 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
659 let _ = ice_sender.send(PeerEvent::Ice(state));
660 })));
661 let connection_sender = sender.clone();
662 peer.on_connection_state_change(Some(Box::new(move |state| {
663 let _ = connection_sender.send(PeerEvent::Connection(state));
664 })));
665 peer.on_track(Some(Box::new(move |event| match event.track {
666 MediaStreamTrack::Audio(track) => {
667 let _ = sender.send(PeerEvent::Track(track));
668 }
669 MediaStreamTrack::Video(track) => {
670 let mid = event.transceiver.mid().unwrap_or_default();
671 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
672 }
673 })));
674 Ok(PeerSession {
675 peer,
676 events,
677 _data_channel: data_channel,
678 gathered,
679 })
680 }
681
682 fn open_data_channel(
683 peer: &PeerConnection,
684 sender: mpsc::UnboundedSender<PeerEvent>,
685 ) -> Result<DataChannel> {
686 let channel = peer
687 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
688 .map_err(|error| Error::Webrtc(error.to_string()))?;
689 channel.on_message(Some(Box::new(move |buffer| {
690 let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));
691 })));
692 Ok(channel)
693 }
694
695 fn one_to_one_directions<'a>(
696 camera: bool,
697 share: bool,
698 camera_mid: &'a str,
699 share_mid: Option<&'a str>,
700 remote_shares: bool,
701 ) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
702 move |line| match line.kind {
703 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
704 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
705 (true, true) => "sendrecv",
706 (true, false) => "sendonly",
707 (false, true) => "recvonly",
708 (false, false) => INACTIVE,
709 }),
710 _ => None,
711 }
712 }
713
714 fn share_mid_in(offer_text: &str) -> Option<String> {
715 let mut mid = None;
716 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
717 if line.starts_with("m=") {
718 mid = None;
719 } else if let Some(value) = line.strip_prefix("a=mid:") {
720 mid = Some(value.to_owned());
721 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
722 return mid;
723 }
724 }
725 None
726 }
727
728 #[allow(clippy::too_many_arguments)]
729 fn directions_for(
730 layout: Layout,
731 hold: bool,
732 camera: bool,
733 share: bool,
734 camera_mid: &str,
735 share_mid: Option<&str>,
736 remote_shares: bool,
737 text: &str,
738 ) -> String {
739 match (hold, layout) {
740 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
741 (false, Layout::OneToOne) => rewrite_directions(
742 text,
743 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
744 ),
745 (false, Layout::Conference) => text.to_owned(),
746 }
747 }
748
749 async fn create_offer(
750 peer: &PeerConnection,
751 factory: &PeerConnectionFactory,
752 track: &RtcAudioTrack,
753 layout: Layout,
754 gathered: Option<&Gathered>,
755 ) -> Result<OfferedMedia> {
756 let transceiver_init = RtpTransceiverInit {
757 direction: RtpTransceiverDirection::SendRecv,
758 stream_ids: vec![MIC_STREAM.into()],
759 send_encodings: Vec::new(),
760 };
761 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
762 .map_err(|error| Error::Webrtc(error.to_string()))?;
763 let (video, plan) = match layout {
764 Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),
765 Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),
766 };
767 let offer = peer
768 .create_offer(OfferOptions {
769 offer_to_receive_audio: true,
770 offer_to_receive_video: true,
771 ..OfferOptions::default()
772 })
773 .await
774 .map_err(|error| Error::Webrtc(error.to_string()))?;
775 let browser_offer = directions_for(
776 layout,
777 false,
778 false,
779 false,
780 CAMERA_MID,
781 Some(ONE_TO_ONE_SHARE_MID),
782 false,
783 &offer.to_string(),
784 );
785 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
786 peer.set_local_description(description)
787 .await
788 .map_err(|error| Error::Webrtc(error.to_string()))?;
789 let mut numbers = random_u32;
790 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
791 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
792 Ok(OfferedMedia {
793 browser_offer,
794 signaled,
795 video,
796 plan,
797 modalities: accepted_modalities(false),
798 })
799 }
800
801 struct AnsweredMedia {
802 remote: RemoteOffer,
803 offer_sdp: String,
804 answer_sdp: String,
805 camera_mid: Option<String>,
806 receiving_share_mid: Option<String>,
807 }
808
809 fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
810 let main: Vec<_> = remote
811 .lines
812 .iter()
813 .filter(|line| line.role == LineRole::MainVideo)
814 .filter_map(|line| line.browser_mids.first().cloned())
815 .collect();
816 main.iter()
817 .find(|mid| {
818 matches!(
819 direction_of(&remote.browser_sdp, mid).as_deref(),
820 Some("sendrecv" | "recvonly")
821 )
822 })
823 .cloned()
824 .or_else(|| main.into_iter().next())
825 }
826
827 fn share_mids(remote: &RemoteOffer) -> Vec<String> {
828 remote
829 .lines
830 .iter()
831 .filter(|line| line.role == LineRole::ScreenShare)
832 .flat_map(|line| line.browser_mids.iter().cloned())
833 .collect()
834 }
835
836 fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> {
837 remote
838 .lines
839 .iter()
840 .find(|line| line.role == LineRole::ScreenShare)
841 .and_then(|line| line.browser_mids.last().cloned())
842 }
843
844 async fn answer_offer(
845 peer: &PeerConnection,
846 track: Option<&RtcAudioTrack>,
847 teams_offer: &str,
848 video: AnswerVideo<'_>,
849 sending_share_mid: Option<String>,
850 camera_on: bool,
851 gathered: Option<&Gathered>,
852 ) -> Result<AnsweredMedia> {
853 answer_offer_with(
854 peer,
855 track,
856 teams_offer,
857 video,
858 sending_share_mid,
859 None,
860 camera_on,
861 gathered,
862 false,
863 false,
864 )
865 .await
866 }
867
868 #[allow(clippy::too_many_arguments)]
869 async fn answer_offer_with(
870 peer: &PeerConnection,
871 track: Option<&RtcAudioTrack>,
872 teams_offer: &str,
873 video: AnswerVideo<'_>,
874 sending_share_mid: Option<String>,
875 share_track: Option<&RtcVideoTrack>,
876 camera_on: bool,
877 gathered: Option<&Gathered>,
878 keep_receive_slots: bool,
879 mixer: bool,
880 ) -> Result<AnsweredMedia> {
881 let remote = from_teams_offer(teams_offer)?;
882 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
883 peer.set_remote_description(description)
884 .await
885 .map_err(|error| {
886 let lines: Vec<String> = remote
887 .lines
888 .iter()
889 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
890 .collect();
891 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
892 })?;
893 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
894 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
895 Vec::new()
896 } else {
897 share_mids(&remote)
898 };
899 if !keep_receive_slots {
900 for transceiver in peer.transceivers() {
901 let is_video = matches!(
902 transceiver.receiver().track(),
903 Some(MediaStreamTrack::Video(_))
904 );
905 let unused = transceiver.mid().is_some_and(|mid| {
906 Some(&mid) != camera_mid.as_ref()
907 && !kept_share_mids.contains(&mid)
908 && Some(&mid) != sending_share_mid.as_ref()
909 });
910 if is_video && unused {
911 let _ = transceiver.stop();
912 }
913 }
914 }
915 if let Some(track) = track {
916 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
917 .map_err(|error| Error::Webrtc(error.to_string()))?;
918 }
919 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
920 if mixer {
921 // Keep camera sendrecv so a later set_track / updateMediaDescriptions
922 // can start sending without renegotiation. Do NOT force folded
923 // x-multi-stream share lines to sendrecv: Teams rejects that answer
924 // with SdpParsingFailure (301000); starting share upgrades the peer.
925 if let Some(mid) = camera_mid.as_deref()
926 && let Some(camera) = peer_transceiver(peer, mid)
927 {
928 let _ = camera.set_direction(RtpTransceiverDirection::SendRecv);
929 if let AnswerVideo::Send(track) = video {
930 let _ = camera
931 .sender()
932 .set_track(Some(MediaStreamTrack::Video(track.clone())));
933 }
934 }
935 if let Some(mid) = sending_share_mid.as_deref()
936 && let Some(share) = peer_transceiver(peer, mid)
937 {
938 let _ = share.set_direction(RtpTransceiverDirection::SendRecv);
939 if let Some(track) = share_track {
940 let _ = share
941 .sender()
942 .set_track(Some(MediaStreamTrack::Video(track.clone())));
943 }
944 }
945 } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
946 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
947 .map_err(|error| Error::Webrtc(error.to_string()))?;
948 }
949 let answer = peer
950 .create_answer(AnswerOptions::default())
951 .await
952 .map_err(|error| Error::Webrtc(error.to_string()))?;
953 let mut answer_text = answer.to_string();
954 for mid in kept_share_mids
955 .iter()
956 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
957 {
958 answer_text = stop_sending_on(&answer_text, mid);
959 }
960 if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
961 answer_text = stop_sending_on(&answer_text, mid);
962 }
963 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
964 .await
965 .map_err(|error| Error::Webrtc(error.to_string()))?;
966 if mixer
967 && !sends_camera
968 && let Some(mid) = camera_mid.as_deref()
969 && let Some(camera) = peer_transceiver(peer, mid)
970 {
971 let _ = LocalVideo::set_sender_active(&camera.sender(), false);
972 }
973 let receiving_share_mid = share_carrier_mid(&remote)
974 .into_iter()
975 .chain(kept_share_mids)
976 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
977 .find(|mid| {
978 matches!(
979 direction_of(&answer_text, mid).as_deref(),
980 Some("recvonly" | "sendrecv")
981 )
982 });
983 let mut numbers = random_u32;
984 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
985 Ok(AnsweredMedia {
986 remote,
987 offer_sdp: teams_offer.to_owned(),
988 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
989 camera_mid,
990 receiving_share_mid,
991 })
992 }
993
994 fn new_media_leg_id() -> String {
995 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
996 }
997
998 472 async fn setup_step<T, E>(
999 473 control: &mut CallControl,
1000 474 step: impl std::future::Future<Output = std::result::Result<T, E>>,
@@ -1019,22 +493,6 @@ where
1019 493 }
1020 494 }
1021 495
1022 async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
1023 match next {
1024 Some(next) => next.session.events.recv().await,
1025 None => std::future::pending().await,
1026 }
1027 }
1028
1029 fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
1030 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
1031 }
1032
1033 /// Re-queuing while `next` is set spins the call task (defer -> pending -> defer...).
1034 fn camera_may_start(pending: bool, next_is_some: bool, possible: bool) -> bool {
1035 pending && !next_is_some && possible
1036 }
1037
1038 496 #[allow(clippy::too_many_arguments)]
1039 497 async fn drive(
1040 498 inner: &Inner,
@@ -3542,1840 +3000,10 @@ async fn drive(
3542 3000 Ok(())
3543 3001 }
3544 3002
3545 #[allow(clippy::too_many_arguments)]
3546 async fn start_escalation(
3547 factory: &PeerConnectionFactory,
3548 grant: &RelayGrant,
3549 options: &CallOptions,
3550 track: &RtcAudioTrack,
3551 remote: &RemoteCall,
3552 links: &CallbackLinks,
3553 media_leg_id: &str,
3554 acceptance_links: &BTreeMap<String, String>,
3555 ) -> Result<NextPeer> {
3556 let url = acceptance_links
3557 .get("mediaRenegotiation")
3558 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
3559 let session = open_peer(factory, grant, &options.relay_host, false)?;
3560 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
3561 let body = renegotiation_body(
3562 &remote.participant,
3563 links,
3564 &media.signaled.sdp,
3565 media_leg_id,
3566 &media.modalities,
3567 true,
3568 false,
3569 );
3570 let reply_tags = offer_reply_tags(&body);
3571 remote
3572 .signaling
3573 .post_json("POST mediaRenegotiation", url, body)
3574 .await?;
3575 Ok(NextPeer {
3576 session,
3577 offered: Some(media),
3578 answered: None,
3579 leg_links: acceptance_links.clone(),
3580 remote_audio: None,
3581 reply_tags,
3582 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
3583 connected: false,
3584 retargeted: false,
3585 })
3586 }
3587
3588 #[allow(clippy::too_many_arguments)]
3589 async fn escalate(
3590 factory: &PeerConnectionFactory,
3591 grant: &RelayGrant,
3592 options: &CallOptions,
3593 track: &RtcAudioTrack,
3594 remote: &RemoteCall,
3595 links: &CallbackLinks,
3596 media_leg_id: &str,
3597 acceptance_links: &BTreeMap<String, String>,
3598 negotiator: &mut MediaNegotiator,
3599 live: &mut Live,
3600 timeline: &Timeline,
3601 ) -> Option<NextPeer> {
3602 match start_escalation(
3603 factory,
3604 grant,
3605 options,
3606 track,
3607 remote,
3608 links,
3609 media_leg_id,
3610 acceptance_links,
3611 )
3612 .await
3613 {
3614 Ok(pending) => {
3615 timeline.record("escalation", "new peer connection, new offer sent");
3616 if let Some(media) = &pending.offered {
3617 timeline.record_sdp("local offer", &media.signaled.sdp);
3618 }
3619 live.peers.push(pending.session.peer.clone());
3620 Some(pending)
3621 }
3622 Err(error) => {
3623 negotiator.escalation_failed();
3624 timeline.record("escalation failed", error.to_string());
3625 None
3626 }
3627 }
3628 }
3629
3630 #[allow(clippy::too_many_arguments)]
3631 async fn answer_on_new_peer(
3632 factory: &PeerConnectionFactory,
3633 grant: &RelayGrant,
3634 options: &CallOptions,
3635 track: &RtcAudioTrack,
3636 teams_offer: &str,
3637 camera_on: bool,
3638 camera: Option<&RtcVideoTrack>,
3639 share: Option<&RtcVideoTrack>,
3640 ) -> Result<(PeerSession, AnsweredMedia)> {
3641 let session = open_peer(factory, grant, &options.relay_host, false)?;
3642 // Keep every video mid from the mixer offer (camera, gallery, share).
3643 // Reject would stop them and leave set_track InvalidState after the new
3644 // peer replaces the old one. When the camera is already on, answer sendrecv
3645 // so the remote keeps receiving across the escalation.
3646 let video = match (camera_on, camera) {
3647 (true, Some(camera)) => AnswerVideo::Send(camera),
3648 _ => AnswerVideo::Receive,
3649 };
3650 let answered = answer_offer_with(
3651 &session.peer,
3652 Some(track),
3653 teams_offer,
3654 video,
3655 None,
3656 share,
3657 camera_on,
3658 None,
3659 true,
3660 true,
3661 )
3662 .await?;
3663 Ok((session, answered))
3664 }
3665
3666 fn video_lines_from_answer(peer: &PeerConnection, answered: &AnsweredMedia) -> Option<VideoLines> {
3667 let camera_mid = answered.camera_mid.as_deref()?;
3668 let camera = peer_transceiver(peer, camera_mid)?;
3669 let share = share_carrier_mid(&answered.remote).and_then(|mid| peer_transceiver(peer, &mid));
3670 Some(VideoLines { camera, share })
3671 }
3672
3673 async fn send_media_answer(
3674 remote: &RemoteCall,
3675 links: &CallbackLinks,
3676 reply_links: &BTreeMap<String, String>,
3677 answered: &AnsweredMedia,
3678 media_leg_id: &str,
3679 ) -> Result<(BTreeMap<String, String>, String)> {
3680 let url = reply_links
3681 .get("mediaAnswer")
3682 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
3683 let body = escalation_answer_body(
3684 &remote.participant,
3685 links,
3686 &answered.answer_sdp,
3687 media_leg_id,
3688 );
3689 let response = remote
3690 .signaling
3691 .post_json_body("POST mediaAnswer", url, body)
3692 .await?;
3693 Ok((nested_links(&response), object_keys(&response)))
3694 }
3695
3696 fn absorb_answered_links(
3697 into: &mut BTreeMap<String, String>,
3698 extra: &BTreeMap<String, String>,
3699 timeline: &Timeline,
3700 response_keys: &str,
3701 ) {
3702 if extra.is_empty() {
3703 if !response_keys.is_empty() {
3704 timeline.record(
3705 "media answer links",
3706 format!("none, body keys {response_keys}"),
3707 );
3708 }
3709 return;
3710 }
3711 let names = extra.keys().cloned().collect::<Vec<_>>().join(",");
3712 timeline.record("media answer links", names);
3713 into.extend(extra.clone());
3714 }
3715
3716 #[allow(clippy::too_many_arguments)]
3717 fn negotiate_video(
3718 video: &mut VideoReceive,
3719 signaling: &Arc<Signaling>,
3720 control: &CallControl,
3721 timeline: &Timeline,
3722 answer_sdp: &str,
3723 media: &OfferedMedia,
3724 from_mixer: bool,
3725 links: &BTreeMap<String, String>,
3726 roster: &Roster,
3727 ) {
3728 negotiate_video_lines(
3729 video,
3730 signaling,
3731 control,
3732 timeline,
3733 answer_sdp,
3734 &media.signaled.lines,
3735 from_mixer,
3736 links,
3737 roster,
3738 );
3739 }
3740
3741 #[allow(clippy::too_many_arguments)]
3742 fn negotiate_video_lines(
3743 video: &mut VideoReceive,
3744 signaling: &Arc<Signaling>,
3745 control: &CallControl,
3746 timeline: &Timeline,
3747 teams_sdp: &str,
3748 lines: &[crate::sdp::SignaledLine],
3749 from_mixer: bool,
3750 links: &BTreeMap<String, String>,
3751 roster: &Roster,
3752 ) {
3753 let streams = match stream_lines(teams_sdp, lines) {
3754 Ok(streams) => streams,
3755 Err(error) => {
3756 timeline.record("video slots unknown", error.to_string());
3757 return;
3758 }
3759 };
3760 let table = SlotTable::from_streams(&streams);
3761 let link = links
3762 .get("applyChannelParameters")
3763 .or_else(|| links.get("controlVideoStreaming"));
3764 timeline.record(
3765 "video slots",
3766 format!(
3767 "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}",
3768 table.people.len(),
3769 table.screen.is_some(),
3770 link.is_some()
3771 ),
3772 );
3773 let requester = link.filter(|_| from_mixer).map(|url| {
3774 SourceRequester::start(
3775 signaling.clone(),
3776 url.clone(),
3777 video.router().clone(),
3778 control.video.clone(),
3779 timeline.clone(),
3780 )
3781 });
3782 video.negotiated(table, requester);
3783 send_receive_change(control, video.reselect(roster));
3784 }
3785
3786 fn tell_bound_camera(
3787 remote: &RemoteCall,
3788 links: &BTreeMap<String, String>,
3789 local_video: &LocalVideo,
3790 request_id: &mut u32,
3791 timeline: &Timeline,
3792 ) {
3793 let mid = local_video
3794 .camera_mid()
3795 .unwrap_or_else(|| CAMERA_MID.to_owned());
3796 tell_media_descriptions(
3797 remote,
3798 links,
3799 MediaDescription::camera_line(mid, local_video.camera_on()),
3800 request_id,
3801 timeline,
3802 );
3803 }
3804
3805 fn tell_bound_share(
3806 remote: &RemoteCall,
3807 links: &BTreeMap<String, String>,
3808 local_video: &LocalVideo,
3809 request_id: &mut u32,
3810 timeline: &Timeline,
3811 ) {
3812 if !local_video.sharing() {
3813 return;
3814 }
3815 let mid = local_video
3816 .share_mid()
3817 .unwrap_or_else(|| SHARE_MID.to_owned());
3818 tell_media_descriptions(
3819 remote,
3820 links,
3821 MediaDescription::share_line(mid, true),
3822 request_id,
3823 timeline,
3824 );
3825 }
3826
3827 async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3828 match mode {
3829 VideoMode::Pattern => vec![CameraDevice {
3830 key: "pattern".into(),
3831 name: "Test pattern".into(),
3832 }],
3833 VideoMode::Off => Vec::new(),
3834 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3835 .await
3836 .unwrap_or_default(),
3837 }
3838 }
3839
3840 fn refresh_cameras(
3841 updates: mpsc::UnboundedSender<CallUpdate>,
3842 mode: VideoMode,
3843 timeline: Timeline,
3844 ) {
3845 tokio::spawn(async move {
3846 let started = Instant::now();
3847 let cameras = camera_devices(mode).await;
3848 timeline.record(
3849 "camera list",
3850 format!(
3851 "{} camera(s) in {} ms",
3852 cameras.len(),
3853 started.elapsed().as_millis()
3854 ),
3855 );
3856 let _ = updates.send(CallUpdate::Cameras(cameras));
3857 });
3858 }
3859
3860 const SHARE_THUMBNAIL_WINDOWS: usize = 12;
3861 const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3862 const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3863
3864 fn announce_share(control: &CallControl, source: &ShareSource) {
3865 control.send(CallUpdate::ShareKind(Some(source.kind)));
3866 control.send(CallUpdate::LocalShare(Some(source.label())));
3867 }
3868
3869 fn clear_share(control: &CallControl) {
3870 control.send(CallUpdate::ShareKind(None));
3871 control.send(CallUpdate::LocalShare(None));
3872 }
3873
3874 fn refresh_share_sources(
3875 updates: mpsc::UnboundedSender<CallUpdate>,
3876 mode: VideoMode,
3877 with_thumbnails: bool,
3878 ) {
3879 tokio::spawn(async move {
3880 let picker = current_share_picker();
3881 let sources = match mode {
3882 VideoMode::Pattern => vec![
3883 ShareSource {
3884 id: 1,
3885 kind: ShareKind::Screen,
3886 title: "Test screen".into(),
3887 },
3888 ShareSource {
3889 id: 2,
3890 kind: ShareKind::Window,
3891 title: "Test window".into(),
3892 },
3893 ],
3894 VideoMode::Off => Vec::new(),
3895 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3896 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3897 .await
3898 .unwrap_or_default(),
3899 };
3900 let sources = share_sources_for_menu(picker, sources);
3901 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3902 if picker == SharePicker::Portal || !with_thumbnails {
3903 return;
3904 }
3905 let wanted: Vec<ShareSource> = sources
3906 .iter()
3907 .filter(|source| source.kind == ShareKind::Screen)
3908 .chain(
3909 sources
3910 .iter()
3911 .filter(|source| source.kind == ShareKind::Window)
3912 .take(SHARE_THUMBNAIL_WINDOWS),
3913 )
3914 .cloned()
3915 .collect();
3916 for source in wanted {
3917 let picture = match mode {
3918 VideoMode::Platform => {
3919 let wanted = source.clone();
3920 tokio::task::spawn_blocking(move || {
3921 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3922 })
3923 .await
3924 .ok()
3925 .flatten()
3926 }
3927 VideoMode::Pattern => Some(VideoPicture::solid(
3928 SHARE_THUMBNAIL_WIDTH,
3929 SHARE_THUMBNAIL_HEIGHT,
3930 120,
3931 80,
3932 40,
3933 )),
3934 VideoMode::Off => None,
3935 };
3936 if let Some(picture) = picture
3937 && updates
3938 .send(CallUpdate::ShareThumbnail {
3939 source,
3940 picture: Arc::new(picture),
3941 })
3942 .is_err()
3943 {
3944 return;
3945 }
3946 }
3947 });
3948 }
3949
3950 fn tell_media_descriptions(
3951 remote: &RemoteCall,
3952 links: &BTreeMap<String, String>,
3953 description: MediaDescription,
3954 request_id: &mut u32,
3955 timeline: &Timeline,
3956 ) {
3957 let Some(url) = links.get("updateMediaDescriptions").cloned() else {
3958 timeline.record("updateMediaDescriptions skipped", "no link from the mixer");
3959 return;
3960 };
3961 *request_id += 1;
3962 let request_id = *request_id;
3963 let signaling = remote.signaling.clone();
3964 let timeline = timeline.clone();
3965 tokio::spawn(async move {
3966 let sent = format!(
3967 "{} {} request {request_id}",
3968 description.mid, description.direction
3969 );
3970 if let Err(error) = signaling
3971 .update_media_descriptions(&url, &[description], request_id)
3972 .await
3973 {
3974 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
3975 }
3976 });
3977 }
3978
3979 fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
3980 own.is_some_and(|own| own.thread_id == target.thread_id)
3981 }
3982
3983 fn attach_share_line(
3984 peer: &PeerConnection,
3985 factory: &PeerConnectionFactory,
3986 local_video: &mut LocalVideo,
3987 camera_mid: Option<&str>,
3988 ) -> Result<()> {
3989 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
3990 if !local_video.has_lines() && camera.is_none() {
3991 return Err(Error::Webrtc("no video line negotiated".into()));
3992 }
3993 let share = add_share_line(peer, factory)?;
3994 local_video
3995 .add_share_line(share.clone(), camera)
3996 .inspect_err(|_| {
3997 let _ = share.stop();
3998 })
3999 }
4000
4001 fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
4002 peer.transceivers()
4003 .into_iter()
4004 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
4005 }
4006
4007 fn start_camera_line(
4008 local_video: &mut LocalVideo,
4009 peer: &PeerConnection,
4010 direct_mid: Option<&str>,
4011 choice: &DeviceChoice,
4012 ) -> Result<()> {
4013 if !local_video.has_lines() {
4014 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
4015 let camera = peer_transceiver(peer, mid)
4016 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
4017 if !matches!(
4018 camera.direction(),
4019 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
4020 ) {
4021 peer.add_track(
4022 MediaStreamTrack::Video(local_video.camera_track()),
4023 &[CAMERA_STREAM],
4024 )
4025 .map_err(|error| Error::Webrtc(error.to_string()))?;
4026 }
4027 local_video.set_lines(VideoLines {
4028 camera,
4029 share: None,
4030 })?;
4031 }
4032 local_video.start_camera(choice)
4033 }
4034
4035 #[allow(clippy::too_many_arguments)]
4036 async fn offer_same_peer(
4037 peer: &PeerConnection,
4038 gathered: &Gathered,
4039 own_share_mid: Option<String>,
4040 plan: &OfferPlan,
4041 layout: Layout,
4042 camera_mid: &str,
4043 hold: bool,
4044 camera: bool,
4045 share: bool,
4046 remote: &RemoteCall,
4047 links: &CallbackLinks,
4048 media_leg_id: &str,
4049 media_links: &BTreeMap<String, String>,
4050 negotiator: &mut MediaNegotiator,
4051 ) -> Result<(String, SignaledOffer, Vec<String>)> {
4052 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
4053 let url = media_links
4054 .get("mediaRenegotiation")
4055 .cloned()
4056 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
4057 if !negotiator.begin_same_peer_offer() {
4058 return Err(Error::Signaling(
4059 "another media negotiation is running".into(),
4060 ));
4061 }
4062 let offered = build_same_peer_offer(
4063 peer,
4064 plan,
4065 layout,
4066 hold,
4067 camera,
4068 share,
4069 camera_mid,
4070 own_share_mid,
4071 direct.then_some(gathered),
4072 )
4073 .await;
4074 let (text, signaled) = match offered {
4075 Ok(offered) => offered,
4076 Err(error) => {
4077 negotiator.same_peer_offer_failed();
4078 return Err(error);
4079 }
4080 };
4081 let modalities = offer_modalities(
4082 layout == Layout::OneToOne && camera && !hold,
4083 share && !hold,
4084 );
4085 let body = renegotiation_body(
4086 &remote.participant,
4087 links,
4088 &signaled.sdp,
4089 media_leg_id,
4090 &modalities,
4091 false,
4092 direct,
4093 );
4094 let reply_tags = offer_reply_tags(&body);
4095 if let Err(error) = remote
4096 .signaling
4097 .post_json("POST mediaRenegotiation (same peer)", &url, body)
4098 .await
4099 {
4100 negotiator.same_peer_offer_failed();
4101 rollback_offer(peer).await;
4102 return Err(error);
4103 }
4104 Ok((text, signaled, reply_tags))
4105 }
4106
4107 #[allow(clippy::too_many_arguments)]
4108 async fn build_same_peer_offer(
4109 peer: &PeerConnection,
4110 plan: &OfferPlan,
4111 layout: Layout,
4112 hold: bool,
4113 camera: bool,
4114 share: bool,
4115 camera_mid: &str,
4116 own_share_mid: Option<String>,
4117 gathered: Option<&Gathered>,
4118 ) -> Result<(String, SignaledOffer)> {
4119 let offer = peer
4120 .create_offer(OfferOptions {
4121 offer_to_receive_audio: true,
4122 offer_to_receive_video: true,
4123 ..OfferOptions::default()
4124 })
4125 .await
4126 .map_err(|error| Error::Webrtc(error.to_string()))?;
4127 let offer_text = offer.to_string();
4128 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
4129 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
4130 peer.current_remote_description()
4131 .and_then(|remote| direction_of(&remote.to_string(), mid))
4132 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
4133 });
4134 let text = directions_for(
4135 layout,
4136 false,
4137 camera,
4138 share,
4139 camera_mid,
4140 share_mid.as_deref(),
4141 remote_shares,
4142 &offer_text,
4143 );
4144 let description = parse_sdp(&text, SdpType::Offer)?;
4145 peer.set_local_description(description)
4146 .await
4147 .map_err(|error| Error::Webrtc(error.to_string()))?;
4148 let mut numbers = random_u32;
4149 let mut plan = plan.clone();
4150 if let Some(mid) = share_mid
4151 .as_ref()
4152 .filter(|mid| !plan.screen_share_mids.contains(mid))
4153 {
4154 plan.screen_share_mids.push(mid.clone());
4155 }
4156 let mut signaled = to_teams_offer(
4157 &directions_for(
4158 layout,
4159 hold,
4160 camera,
4161 share,
4162 camera_mid,
4163 share_mid.as_deref(),
4164 remote_shares,
4165 &text,
4166 ),
4167 &plan,
4168 &mut numbers,
4169 )?;
4170 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
4171 if gathered.is_some()
4172 && let Some(role) = negotiated_setup(
4173 peer.current_local_description()
4174 .map(|local| local.to_string())
4175 .as_deref(),
4176 peer.current_remote_description()
4177 .map(|remote| remote.to_string())
4178 .as_deref(),
4179 )
4180 {
4181 signaled.sdp = signaled
4182 .sdp
4183 .replace("a=setup:actpass", &format!("a=setup:{role}"));
4184 }
4185 Ok((text, signaled))
4186 }
4187
4188 /// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
4189 fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
4190 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
4191 Ok(Ok(description)) => Ok(description),
4192 Ok(Err(error)) => Err(Error::Sdp(format!(
4193 "{kind:?} rejected: {}",
4194 error.description
4195 ))),
4196 Err(_) => Err(Error::Sdp(format!(
4197 "{kind:?} rejected, libwebrtc gave no readable reason"
4198 ))),
4199 }
4200 }
4201
4202 async fn rollback_offer(peer: &PeerConnection) {
4203 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
4204 let _ = peer.set_local_description(rollback).await;
4205 }
4206 }
4207
4208 async fn rollback_remote_offer(peer: &PeerConnection) {
4209 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
4210 let _ = peer.set_remote_description(rollback).await;
4211 }
4212 }
4213
4214 fn is_glare_rejection(body: &serde_json::Value) -> bool {
4215 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
4216 }
4217
4218 fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
4219 let links = &body["mediaNegotiation"]["links"];
4220 ["mediaAnswer", "rejection"]
4221 .iter()
4222 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
4223 .collect()
4224 }
4225
4226 #[cfg(test)]
4227 mod reply_tag_tests {
4228 use super::*;
4229
4230 #[test]
4231 fn answers_and_rejections_match_the_offer_by_tag() {
4232 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
4233 assert!(answers_offer(
4234 "callAgent/c/aaaa1111/call/mediaAnswer/",
4235 &tags
4236 ));
4237 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
4238 assert!(!answers_offer(
4239 "callAgent/c/cccc3333/call/mediaAnswer/",
4240 &tags
4241 ));
4242 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
4243 }
4244
4245 #[test]
4246 fn an_offer_names_both_reply_tags() {
4247 let body = serde_json::json!({"mediaNegotiation": {"links": {
4248 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
4249 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
4250 assert_eq!(
4251 offer_reply_tags(&body),
4252 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
4253 );
4254 }
4255 }
4256
4257 fn defer_to_new_peer(
4258 change: Change,
4259 deferred: &mut Vec<Change>,
4260 local_video: &mut LocalVideo,
4261 control: &CallControl,
4262 ) {
4263 match change {
4264 Change::Camera(true) => {
4265 control.send(CallUpdate::Camera(true));
4266 deferred.push(change);
4267 }
4268 Change::Share(true) => deferred.push(change),
4269 change => undo_change(change, local_video, control),
4270 }
4271 }
4272
4273 /// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
4274 fn settle_failed_escalation(
4275 server: bool,
4276 layout: Layout,
4277 negotiator: &mut MediaNegotiator,
4278 deferred: &mut Vec<Change>,
4279 local_video: &mut LocalVideo,
4280 control: &CallControl,
4281 ) {
4282 if server {
4283 negotiator.server_escalation_failed();
4284 for change in deferred.drain(..) {
4285 undo_change(change, local_video, control);
4286 }
4287 } else if layout == Layout::OneToOne {
4288 drop_local_media(local_video, control);
4289 }
4290 }
4291
4292 fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
4293 if local_video.sharing() {
4294 local_video.stop_share();
4295 clear_share(control);
4296 }
4297 if local_video.camera_on() {
4298 local_video.stop_camera();
4299 control.send(CallUpdate::Camera(false));
4300 }
4301 }
4302
4303 fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
4304 match change {
4305 Change::Camera(true) => {
4306 local_video.stop_camera();
4307 control.send(CallUpdate::Camera(false));
4308 }
4309 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
4310 Change::Share(true) => {
4311 local_video.stop_share();
4312 clear_share(control);
4313 control.send(CallUpdate::Notice(notice_with_detail(
4314 SHARING_START_NOTICE,
4315 "",
4316 )));
4317 }
4318 Change::Share(false) => {}
4319 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
4320 }
4321 }
4322
4323 fn withhold_media(
4324 muted: &mut bool,
4325 audio: &AudioSetup,
4326 software_audio: Option<&SoftwareAudio>,
4327 remote: &RemoteCall,
4328 local_video: &mut LocalVideo,
4329 control: &CallControl,
4330 ) {
4331 *muted = apply_mute(
4332 MuteCommand::Mute,
4333 *muted,
4334 audio,
4335 software_audio,
4336 remote,
4337 control,
4338 );
4339 if local_video.camera_on() {
4340 local_video.stop_camera();
4341 control.send(CallUpdate::Camera(false));
4342 }
4343 }
4344
4345 async fn apply_background(
4346 choice: BackgroundChoice,
4347 local_video: &LocalVideo,
4348 control: &CallControl,
4349 timeline: &Timeline,
4350 ) {
4351 match choice {
4352 BackgroundChoice::None => local_video.set_background(false, None),
4353 BackgroundChoice::Blur => local_video.set_background(true, None),
4354 BackgroundChoice::Image(path) => {
4355 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
4356 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
4357 Ok(Err(error)) => {
4358 timeline.record("background image failed", error.to_string());
4359 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
4360 }
4361 Err(_) => {}
4362 }
4363 }
4364 }
4365 }
4366
4367 async fn save_meeting_options(
4368 session: &session::Session,
4369 target: &MeetingTarget,
4370 writes: &[OptionWrite],
4371 ) -> std::result::Result<meeting_options::MeetingOptions, String> {
4372 for change in writes {
4373 meeting_options::write(session, target, change)
4374 .await
4375 .map_err(|error| error.to_string())?;
4376 }
4377 meeting_options::fetch(session, target)
4378 .await
4379 .map_err(|error| error.to_string())
4380 }
4381
4382 fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
4383 let display_name = roster
4384 .members()
4385 .iter()
4386 .find(|member| member.mri == mri)
4387 .map_or("", |member| member.display_name.as_str());
4388 Target { mri, display_name }
4389 }
4390
4391 const RECORDING_STOP_RETRIES: usize = 6;
4392 const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5);
4393
4394 /// The recorder answers 409 to a stop sent while its start is still settling.
4395 fn recorder_busy(error: &Error) -> bool {
4396 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
4397 }
4398
4399 fn report_organizer_result(
4400 result: Result<u16>,
4401 label: &str,
4402 notice: &'static str,
4403 control: &CallControl,
4404 timeline: &Timeline,
4405 ) {
4406 if let Err(error) = &result {
4407 timeline.record(format!("{label} failed"), error.to_string());
4408 control.send(CallUpdate::Notice(notice.to_owned()));
4409 }
4410 control.send(CallUpdate::Organizer {
4411 action: label.to_owned(),
4412 outcome: result.map_err(|error| error.to_string()),
4413 });
4414 }
4415
4416 fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
4417 if entry.display_name.is_empty() {
4418 entry.display_name = roster
4419 .name_of(&entry.user_id)
4420 .unwrap_or_default()
4421 .to_owned();
4422 }
4423 entry
4424 }
4425
4426 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
4427 enum BotJob {
4428 Captions,
4429 Recording,
4430 }
4431
4432 #[allow(clippy::too_many_arguments)]
4433 async fn run_bot_steps(
4434 job: BotJob,
4435 flow: &mut CaptionFlow,
4436 roster: &Roster,
4437 remote: &RemoteCall,
4438 links: &CallbackLinks,
4439 meeting_chat: Option<&str>,
4440 plan: &RecordingPlan,
4441 bot_pending: &mut bool,
4442 control: &CallControl,
4443 timeline: &Timeline,
4444 ) {
4445 let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
4446 BotJob::Captions => |bot| bot.active,
4447 BotJob::Recording => |bot| bot.recording,
4448 };
4449 let fail = |flow: &mut CaptionFlow, reason: &str| {
4450 flow.failed();
4451 control.send(match job {
4452 BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
4453 BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
4454 });
4455 if job == BotJob::Recording {
4456 control.send(CallUpdate::RecordingPending(false));
4457 }
4458 };
4459 let (join_failure, start_failure) = match job {
4460 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
4461 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
4462 };
4463 loop {
4464 match flow.next_for(roster.caption_bot(), is_active) {
4465 CaptionStep::Wait => return,
4466 CaptionStep::AddBot => {
4467 if *bot_pending {
4468 continue;
4469 }
4470 let Some(thread) = meeting_chat else {
4471 return fail(
4472 flow,
4473 "This call has no chat for the captions and the recording",
4474 );
4475 };
4476 *bot_pending = true;
4477 let added = remote
4478 .signaling
4479 .add_caption_bot(
4480 &remote.conversation,
4481 &remote.participant,
4482 thread,
4483 links,
4484 remote.threadless,
4485 )
4486 .await;
4487 if job == BotJob::Recording {
4488 report_organizer_result(
4489 added
4490 .as_ref()
4491 .map(|status| *status)
4492 .map_err(|error| Error::Signaling(error.to_string())),
4493 "recording add bot",
4494 join_failure,
4495 control,
4496 timeline,
4497 );
4498 }
4499 if let Err(error) = added {
4500 timeline.record("bot invitation failed", error.to_string());
4501 *bot_pending = false;
4502 return fail(flow, join_failure);
4503 }
4504 }
4505 CaptionStep::Start => {
4506 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
4507 return;
4508 };
4509 match job {
4510 BotJob::Captions => {
4511 if let Err(error) = remote
4512 .signaling
4513 .caption_command(&url, BotAction::Start, &remote.participant)
4514 .await
4515 {
4516 timeline.record("caption start failed", error.to_string());
4517 return fail(flow, start_failure);
4518 }
4519 if let Err(error) = remote
4520 .signaling
4521 .set_caption_preference(&remote.conversation, &remote.participant, true)
4522 .await
4523 {
4524 timeline.record("caption preference failed", error.to_string());
4525 }
4526 }
4527 BotJob::Recording => {
4528 let started = remote
4529 .signaling
4530 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
4531 .await;
4532 let failed = started.is_err();
4533 report_organizer_result(
4534 started,
4535 "recording start",
4536 start_failure,
4537 control,
4538 timeline,
4539 );
4540 if failed {
4541 return fail(flow, start_failure);
4542 }
4543 }
4544 }
4545 }
4546 CaptionStep::Stop => {
4547 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
4548 continue;
4549 };
4550 match job {
4551 BotJob::Captions => {
4552 if let Err(error) = remote
4553 .signaling
4554 .caption_command(&url, BotAction::Stop, &remote.participant)
4555 .await
4556 {
4557 timeline.record("caption stop failed", error.to_string());
4558 }
4559 if let Err(error) = remote
4560 .signaling
4561 .set_caption_preference(
4562 &remote.conversation,
4563 &remote.participant,
4564 false,
4565 )
4566 .await
4567 {
4568 timeline.record("caption preference failed", error.to_string());
4569 }
4570 }
4571 BotJob::Recording => {
4572 let remote = remote.clone();
4573 let updates = control.updates();
4574 let (command, title) = (plan.stop(), plan.title.clone());
4575 tokio::spawn(async move {
4576 let mut stopped = remote
4577 .signaling
4578 .recording_command(&url, command, &remote.participant, &title)
4579 .await;
4580 for _ in 0..RECORDING_STOP_RETRIES {
4581 if !stopped.as_ref().is_err_and(recorder_busy) {
4582 break;
4583 }
4584 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
4585 stopped = remote
4586 .signaling
4587 .recording_command(&url, command, &remote.participant, &title)
4588 .await;
4589 }
4590 if stopped.is_err() {
4591 let _ = updates
4592 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
4593 }
4594 let _ = updates.send(CallUpdate::Organizer {
4595 action: "recording stop".into(),
4596 outcome: stopped.map_err(|error| error.to_string()),
4597 });
4598 });
4599 }
4600 }
4601 }
4602 CaptionStep::ReportOn => {
4603 if job == BotJob::Captions {
4604 control.send(CallUpdate::Captions(CaptionState::On));
4605 }
4606 }
4607 }
4608 }
4609 }
4610
4611 fn send_receive_change(control: &CallControl, change: ReceiveChange) {
4612 if let Some(sharer) = change.screen_sharer {
4613 control.send(CallUpdate::ScreenShare(sharer));
4614 }
4615 }
4616
4617 fn record_audio_devices(
4618 timeline: &Timeline,
4619 lists: &devices::DeviceLists,
4620 input: Option<&AppliedDevice>,
4621 output: Option<&AppliedDevice>,
4622 ) {
4623 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
4624 applied
4625 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
4626 .map_or("none", |device| device.name.as_str())
4627 .to_owned()
4628 };
4629 timeline.record(
4630 "audio devices",
4631 format!(
4632 "input={} output={}",
4633 name(&lists.inputs, input),
4634 name(&lists.outputs, output)
4635 ),
4636 );
4637 }
4638
4639 fn follow_device_change(
4640 flow: Flow,
4641 (previous, current): (&[AudioDevice], &[AudioDevice]),
4642 choice: &DeviceChoice,
4643 applied: &mut Option<AppliedDevice>,
4644 select: impl Fn(u16) -> bool,
4645 timeline: &Timeline,
4646 control: &CallControl,
4647 ) -> bool {
4648 let system_default = devices::system_default_id(flow);
4649 let (index, fell_back) =
4650 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
4651 Reselect::Keep => return false,
4652 Reselect::Select(index) => (index, false),
4653 Reselect::FallBack(index) => (index, true),
4654 };
4655 let selected = select(index);
4656 timeline.record(
4657 "device change",
4658 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
4659 );
4660 if selected {
4661 *applied = current
4662 .iter()
4663 .find(|device| device.index == index)
4664 .map(|device| AppliedDevice {
4665 index,
4666 key: device.key(),
4667 });
4668 }
4669 if fell_back {
4670 let fallback = current.iter().find(|device| device.index == index);
4671 control.send(CallUpdate::Notice(devices::disconnect_notice(
4672 previous, choice, fallback,
4673 )));
4674 }
4675 selected
4676 }
4677
4678 3003 fn far_future() -> Instant {
4679 3004 Instant::now() + FAR_FUTURE
4680 3005 }
4681 3006
4682 fn apply_mute(
4683 command: MuteCommand,
4684 currently_muted: bool,
4685 audio: &AudioSetup,
4686 software_audio: Option<&SoftwareAudio>,
4687 remote: &RemoteCall,
4688 control: &CallControl,
4689 ) -> bool {
4690 let effect = MuteEffect::for_muted(command.target(currently_muted));
4691 audio.track.set_enabled(effect.track_enabled);
4692 if let Some(software_audio) = software_audio {
4693 software_audio.set_microphone_muted(effect.muted);
4694 }
4695 control.send(CallUpdate::Muted(effect.muted));
4696 let remote = remote.clone();
4697 tokio::spawn(async move {
4698 let _ = remote
4699 .signaling
4700 .update_endpoint_state(
4701 &remote.conversation,
4702 &remote.participant,
4703 effect.endpoint_is_muted,
4704 )
4705 .await;
4706 });
4707 effect.muted
4708 }
4709
4710 fn silence_for_hold(
4711 on_hold: bool,
4712 muted: bool,
4713 audio: Option<&AudioSetup>,
4714 software_audio: Option<&SoftwareAudio>,
4715 ) {
4716 let silent = on_hold || muted;
4717 if let Some(audio) = audio {
4718 audio
4719 .track
4720 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
4721 }
4722 if let Some(software_audio) = software_audio {
4723 software_audio.set_microphone_muted(silent);
4724 }
4725 }
4726
4727 fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
4728 let sender = peer
4729 .senders()
4730 .into_iter()
4731 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
4732 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
4733 sender
4734 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
4735 .map_err(|error| Error::Webrtc(error.to_string()))
4736 }
4737
4738 fn outgoing_track<'a>(
4739 software_audio: Option<&'a SoftwareAudio>,
4740 device_track: &'a RtcAudioTrack,
4741 ) -> &'a RtcAudioTrack {
4742 pick_track(software_audio.map(|audio| &audio.track), device_track)
4743 }
4744
4745 fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T {
4746 software.unwrap_or(device)
4747 }
4748
4749 fn software_wanted(
4750 mic_settings: MicSettings,
4751 share_sound_wanted: bool,
4752 local_video: &LocalVideo,
4753 audio: Option<&AudioSetup>,
4754 ) -> Option<SoftwareAudioPlan> {
4755 let sharing_sound = share_sound_wanted && local_video.sharing();
4756 SoftwareAudioPlan::wanted(
4757 mic_settings,
4758 sharing_sound,
4759 audio.is_some_and(AudioSetup::uses_devices),
4760 )
4761 }
4762
4763 fn restore_device_track(
4764 factory: &PeerConnectionFactory,
4765 input: &DeviceChoice,
4766 peer: &PeerConnection,
4767 device_track: &RtcAudioTrack,
4768 timeline: &Timeline,
4769 ) {
4770 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4771 if !factory.adm_recording_enabled() {
4772 factory.set_adm_recording_enabled(true);
4773 devices::select_input(factory, input);
4774 }
4775 if let Err(error) = swap_audio_track(peer, device_track) {
4776 timeline.record("microphone track not restored", error.to_string());
4777 }
4778 }
4779
4780 #[allow(clippy::too_many_arguments)]
4781 fn sync_software_audio(
4782 factory: &PeerConnectionFactory,
4783 options: &CallOptions,
4784 input: &DeviceChoice,
4785 muted: bool,
4786 remote_audio: Option<RtcAudioTrack>,
4787 peer: &PeerConnection,
4788 device_track: &RtcAudioTrack,
4789 wanted: Option<SoftwareAudioPlan>,
4790 restart: bool,
4791 software_audio: &mut Option<SoftwareAudio>,
4792 mic_settings: MicSettings,
4793 control: &CallControl,
4794 timeline: &Timeline,
4795 ) {
4796 let running = software_audio.as_ref().map(|audio| audio.plan);
4797 if running == wanted && !restart {
4798 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4799 return;
4800 }
4801 if running.is_some() {
4802 timeline.record("software audio", "stopping");
4803 }
4804 *software_audio = None;
4805 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
4806 let Some(plan) = wanted else {
4807 restore_device_track(factory, input, peer, device_track, timeline);
4808 control.send(CallUpdate::ShareSound(false));
4809 crate::noise_stage::apply_for_outgoing(mic_settings, true);
4810 return;
4811 };
4812 let started = SoftwareAudio::start(
4813 factory,
4814 options.audio,
4815 options.tone_hz,
4816 input,
4817 plan,
4818 muted,
4819 remote_audio,
4820 )
4821 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4822 match started {
4823 Ok(audio) => {
4824 timeline.record(
4825 "software audio",
4826 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4827 );
4828 if let Some(source) = &audio.microphone_source {
4829 timeline.record("mic capture", source.clone());
4830 }
4831 if audio.microphone_source.is_some() {
4832 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4833 factory.set_adm_recording_enabled(false);
4834 }
4835 if let Some(warning) = &audio.warning {
4836 timeline.record("computer sound warning", warning.clone());
4837 }
4838 control.send(CallUpdate::ShareSound(plan.computer_sound));
4839 if let Some(notice) = audio.microphone_notice {
4840 control.send(CallUpdate::Notice(notice.into()));
4841 }
4842 *software_audio = Some(audio);
4843 }
4844 Err(error) => {
4845 timeline.record("software audio failed", error.to_string());
4846 restore_device_track(factory, input, peer, device_track, timeline);
4847 if was_sharing_sound || plan.computer_sound {
4848 control.send(CallUpdate::ShareSound(false));
4849 }
4850 let notice = if plan.computer_sound {
4851 "Computer sound could not start, sharing without it"
4852 } else {
4853 "Microphone processing could not start, using the standard microphone"
4854 };
4855 control.send(CallUpdate::Notice(notice.into()));
4856 }
4857 }
4858 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4859 }
4860
4861 async fn stop_local_publish(
4862 local_video: &mut LocalVideo,
4863 remote: &RemoteCall,
4864 media_links: &BTreeMap<String, String>,
4865 request_id: &mut u32,
4866 control: &CallControl,
4867 timeline: &Timeline,
4868 ) {
4869 let camera_mid = local_video.camera_mid();
4870 let share_mid = local_video.share_mid();
4871 let was_sharing = local_video.sharing();
4872 let was_camera = local_video.camera_on() || local_video.camera_previewing();
4873 if was_sharing {
4874 local_video.stop_share();
4875 clear_share(control);
4876 }
4877 if was_camera {
4878 local_video.stop_camera();
4879 control.send(CallUpdate::Camera(false));
4880 }
4881 local_video.clear_lines();
4882 let Some(url) = media_links.get("updateMediaDescriptions").cloned() else {
4883 return;
4884 };
4885 let mut descriptions = Vec::new();
4886 if was_camera {
4887 descriptions.push(MediaDescription::camera_line(
4888 camera_mid.unwrap_or_else(|| CAMERA_MID.to_owned()),
4889 false,
4890 ));
4891 }
4892 if was_sharing {
4893 descriptions.push(MediaDescription::share_line(
4894 share_mid.unwrap_or_else(|| SHARE_MID.to_owned()),
4895 false,
4896 ));
4897 }
4898 if descriptions.is_empty() {
4899 return;
4900 }
4901 *request_id += 1;
4902 let id = *request_id;
4903 match remote
4904 .signaling
4905 .update_media_descriptions(&url, &descriptions, id)
4906 .await
4907 {
4908 Ok(()) => timeline.record(
4909 "updateMediaDescriptions",
4910 format!("publish off before leave, request {id}"),
4911 ),
4912 Err(error) => timeline.record(
4913 "updateMediaDescriptions failed",
4914 format!("publish off before leave: {error}"),
4915 ),
4916 }
4917 }
4918
4919 async fn tear_down(
4920 mut live: Live,
4921 inner: &Inner,
4922 timeline: &Timeline,
4923 report: &mut CallReport,
4924 cancelled: bool,
4925 ) {
4926 if crate::noise_stage::overloaded() {
4927 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
4928 }
4929 crate::noise_stage::clear();
4930 // Stop keep-alive / broker first so Teams does not see us as still present.
4931 live.broker_running.store(false, Ordering::SeqCst);
4932 if let Some(broker) = live.broker.take() {
4933 broker.abort();
4934 }
4935 if let Some(audio) = live.audio.take() {
4936 audio.stop().await;
4937 }
4938 // Leave and drop call legs while peers are still open, then close media.
4939 if !live.skip_leave
4940 && let Some(remote) = &live.remote
4941 {
4942 let reason = if cancelled {
4943 LeaveReason::Cancel
4944 } else {
4945 LeaveReason::Hangup
4946 };
4947 match remote
4948 .signaling
4949 .leave(&remote.conversation, &remote.participant, reason)
4950 .await
4951 {
4952 Ok(()) => report.left_cleanly = true,
4953 Err(error) => timeline.record("leave failed", error.to_string()),
4954 }
4955 for call_leg in &live.call_legs {
4956 if let Err(error) = remote.signaling.end_call_leg(call_leg).await {
4957 timeline.record("callLeg end failed", error.to_string());
4958 }
4959 }
4960 }
4961 if report.end.is_none()
4962 && let Some(callbacks) = live.callbacks.as_mut()
4963 && live.remote.is_some()
4964 {
4965 let waited = timeout(END_CALLBACK_WAIT, async {
4966 while let Some(callback) = callbacks.recv().await {
4967 let event = handle_callback(&callback, timeline);
4968 if let Ok(CallEvent::End(end)) = event {
4969 return Some(end);
4970 }
4971 }
4972 None
4973 })
4974 .await;
4975 report.end = waited.ok().flatten();
4976 }
4977 for peer in &live.peers {
4978 peer.close();
4979 }
4980 for task in live.video_tasks.drain(..) {
4981 task.abort();
4982 }
4983 if let Some(route_id) = &live.route_id {
4984 inner.unregister_route(route_id);
4985 }
4986 timeline.record("closed", "peer closed, call route removed");
4987 }
4988
4989 fn setup_end_kind(end: &CallEnd) -> EndKind {
4990 match end.kind() {
4991 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
4992 kind => kind,
4993 }
4994 }
4995
4996 fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
4997 let body = decode_body(callback)?;
4998 let (_, event) = classify(&callback.path, body)?;
4999 let detail = match &event {
5000 CallEvent::Acceptance(acceptance) => format!(
5001 "answer sdp {} bytes, fromMixer={}",
5002 acceptance.sdp.len(),
5003 acceptance.from_mixer
5004 ),
5005 CallEvent::End(end) => format!(
5006 "code={} subCode={} phrase={}",
5007 end.code, end.sub_code, end.phrase
5008 ),
5009 CallEvent::Progress(status) => format!("{status:?}"),
5010 CallEvent::ConversationEnd(body)
5011 | CallEvent::Rejection(body)
5012 | CallEvent::AddParticipantFailure(body)
5013 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
5014 CallEvent::ControlVideoStreaming(body) => parse_request(body)
5015 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
5016 CallEvent::MediaAcknowledgement(ack) => {
5017 let names = ack.links.keys().cloned().collect::<Vec<_>>().join(",");
5018 if names.is_empty() {
5019 format!("links=none keys={}", ack.keys)
5020 } else {
5021 format!("links={names}")
5022 }
5023 }
5024 _ => String::new(),
5025 };
5026 timeline.record(format!("Trouter {}", event.name()), detail);
5027 match &event {
5028 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
5029 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
5030 CallEvent::MediaRenegotiation(renegotiation) => {
5031 timeline.record_sdp("remote offer", &renegotiation.sdp);
5032 let names = renegotiation
5033 .links
5034 .keys()
5035 .cloned()
5036 .collect::<Vec<_>>()
5037 .join(",");
5038 timeline.record(
5039 "renegotiation links",
5040 if names.is_empty() {
5041 "none".to_owned()
5042 } else {
5043 names
5044 },
5045 );
5046 }
5047 _ => {}
5048 }
5049 Ok(event)
5050 }
5051
5052 async fn apply_answer(
5053 peer: &PeerConnection,
5054 teams_answer: &str,
5055 signaled: &SignaledOffer,
5056 browser_offer: &str,
5057 ) -> Result<()> {
5058 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
5059 set_browser_answer(peer, &answer).await
5060 }
5061
5062 /// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
5063 async fn apply_hold_answer(
5064 peer: &PeerConnection,
5065 teams_answer: &str,
5066 signaled: &SignaledOffer,
5067 browser_offer: &str,
5068 ) -> Result<()> {
5069 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
5070 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
5071 }
5072
5073 async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
5074 let description = parse_sdp(answer, SdpType::Answer)?;
5075 peer.set_remote_description(description)
5076 .await
5077 .map_err(|error| Error::Webrtc(error.to_string()))
5078 }
5079
5080 /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
5081 fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
5082 let Some(directory) = &options.sdp_dump_dir else {
5083 return;
5084 };
5085 let masked: Vec<String> = sdp
5086 .lines()
5087 .map(|line| {
5088 for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] {
5089 if line.starts_with(prefix) {
5090 return format!("{prefix}<masked>");
5091 }
5092 }
5093 line.split(' ')
5094 .map(mask_address)
5095 .collect::<Vec<_>>()
5096 .join(" ")
5097 })
5098 .collect();
5099 let _ = std::fs::create_dir_all(directory);
5100 let _ = std::fs::write(directory.join(name), masked.join("\n"));
5101 }
5102
5103 fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {
5104 let Some(directory) = &options.sdp_dump_dir else {
5105 return;
5106 };
5107 let mut lines: Vec<String> = timeline
5108 .entries()
5109 .iter()
5110 .map(|entry| {
5111 format!(
5112 "{:>6} ms {} {}",
5113 entry.elapsed_ms, entry.label, entry.detail
5114 )
5115 })
5116 .collect();
5117 lines.push(match failure {
5118 Some(error) => format!("failed: {error}"),
5119 None => "ended without error".to_owned(),
5120 });
5121 let _ = std::fs::create_dir_all(directory);
5122 let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));
5123 }
5124
5125 fn mask_address(token: &str) -> String {
5126 let dotted_quad =
5127 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
5128 let colon_address =
5129 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
5130 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
5131 || colon_address
5132 {
5133 "<addr>".to_owned()
5134 } else {
5135 token.to_owned()
5136 }
5137 }
5138
5139 async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) {
5140 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
5141 while let Some(frame) = stream.next().await {
5142 let mut recording = recording.lock().await;
5143 recording.samples.extend_from_slice(&frame.data);
5144 recording.current_second.extend_from_slice(&frame.data);
5145 if recording.current_second.len() >= SAMPLE_RATE as usize {
5146 let second: Vec<i16> = std::mem::take(&mut recording.current_second);
5147 let summary = (rms(&second), tone_ratio(&second, tone_hz));
5148 recording.per_second.push(summary);
5149 }
5150 }
5151 }
5152
5153 async fn poll_broker(
5154 signaling: Arc<Signaling>,
5155 conversation: Conversation,
5156 running: Arc<AtomicBool>,
5157 ) {
5158 let Ok(first) = conversation.link("subscribe") else {
5159 return;
5160 };
5161 let mut url = first.to_owned();
5162 while running.load(Ordering::SeqCst) {
5163 match signaling.poll_broker(&url).await {
5164 Ok(Some(next)) => url = next,
5165 Ok(None) => tokio::time::sleep(BROKER_IDLE_WAIT).await,
5166 Err(_) => tokio::time::sleep(BROKER_RETRY_WAIT).await,
5167 }
5168 }
5169 }
5170
5171 #[derive(Debug, Default)]
5172 struct StatsSnapshot {
5173 inbound_packets: u64,
5174 inbound_bytes: u64,
5175 outbound_packets: u64,
5176 outbound_bytes: u64,
5177 source_levels: Vec<String>,
5178 video_senders: Vec<String>,
5179 audio_level: f64,
5180 local_level: f64,
5181 echo_return_loss_enhancement: f64,
5182 video: VideoReport,
5183 camera_target_bitrate: u64,
5184 share_inbound_packets: u64,
5185 share_outbound_packets: u64,
5186 share_receive: Option<ShareReceive>,
5187 dtls_state: String,
5188 tls_version: String,
5189 dtls_cipher: String,
5190 srtp_cipher: String,
5191 selected_pair: Option<String>,
5192 health: HealthCounters,
5193 transport: TransportDetails,
5194 }
5195
5196 #[derive(Debug, Default)]
5197 struct ShareReceive {
5198 frames_decoded: u32,
5199 key_frames_decoded: u32,
5200 width: u32,
5201 height: u32,
5202 frames_per_second: f64,
5203 pli_count: u32,
5204 fir_count: u32,
5205 freeze_count: u32,
5206 qp_sum: u64,
5207 bytes_received: u64,
5208 }
5209
5210 impl ShareReceive {
5211 fn average_qp(&self) -> u64 {
5212 self.qp_sum
5213 .checked_div(u64::from(self.frames_decoded))
5214 .unwrap_or(0)
5215 }
5216
5217 fn summary(&self) -> String {
5218 format!(
5219 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
5220 self.frames_decoded,
5221 self.key_frames_decoded,
5222 self.width,
5223 self.height,
5224 self.frames_per_second,
5225 self.average_qp(),
5226 self.bytes_received,
5227 self.pli_count,
5228 self.fir_count,
5229 self.freeze_count
5230 )
5231 }
5232 }
5233
5234 async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSnapshot {
5235 let Ok(stats) = peer.get_stats().await else {
5236 return StatsSnapshot::default();
5237 };
5238 let mut snapshot = StatsSnapshot::default();
5239 (snapshot.health, snapshot.transport) = health_from_stats(&stats);
5240 let mut selected_pair_id = None;
5241 for entry in &stats {
5242 match entry {
5243 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => {
5244 snapshot.inbound_packets += inbound.received.packets_received;
5245 snapshot.inbound_bytes += inbound.inbound.bytes_received;
5246 snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level);
5247 }
5248 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
5249 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
5250 snapshot.source_levels.push(format!(
5251 "{}={:.3}",
5252 source.source.track_identifier, source.audio.audio_level
5253 ));
5254 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
5255 }
5256 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
5257 snapshot.outbound_packets += outbound.sent.packets_sent;
5258 snapshot.outbound_bytes += outbound.sent.bytes_sent;
5259 }
5260 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
5261 snapshot.video.inbound_packets += inbound.received.packets_received;
5262 if share_mids.contains(&inbound.inbound.mid) {
5263 snapshot.share_inbound_packets += inbound.received.packets_received;
5264 snapshot.share_receive = Some(ShareReceive {
5265 frames_decoded: inbound.inbound.frames_decoded,
5266 key_frames_decoded: inbound.inbound.key_frames_decoded,
5267 width: inbound.inbound.frame_width,
5268 height: inbound.inbound.frame_height,
5269 frames_per_second: inbound.inbound.frames_per_second,
5270 pli_count: inbound.inbound.pli_count,
5271 fir_count: inbound.inbound.fir_count,
5272 freeze_count: inbound.inbound.freeze_count,
5273 qp_sum: inbound.inbound.qp_sum,
5274 bytes_received: inbound.inbound.bytes_received,
5275 });
5276 }
5277 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
5278 snapshot.video.inbound_width = snapshot
5279 .video
5280 .inbound_width
5281 .max(inbound.inbound.frame_width);
5282 snapshot.video.inbound_height = snapshot
5283 .video
5284 .inbound_height
5285 .max(inbound.inbound.frame_height);
5286 }
5287 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
5288 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
5289 snapshot.video.remote_round_trip_ms = snapshot
5290 .video
5291 .remote_round_trip_ms
5292 .max(remote.remote_inbound.round_trip_time * 1000.0);
5293 }
5294 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
5295 snapshot.video.outbound_packets += outbound.sent.packets_sent;
5296 if share_mids.contains(&outbound.outbound.mid) {
5297 snapshot.share_outbound_packets += outbound.sent.packets_sent;
5298 } else if outbound.outbound.active {
5299 snapshot.camera_target_bitrate = snapshot
5300 .camera_target_bitrate
5301 .max(outbound.outbound.target_bitrate as u64);
5302 }
5303 snapshot.video.outbound_frames_encoded +=
5304 u64::from(outbound.outbound.frames_encoded);
5305 snapshot.video_senders.push(format!(
5306 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
5307 outbound.outbound.mid,
5308 outbound.sent.packets_sent,
5309 outbound.outbound.key_frames_encoded,
5310 outbound.outbound.pli_count,
5311 outbound.outbound.fir_count,
5312 outbound.outbound.nack_count,
5313 outbound.outbound.target_bitrate / 1000.0,
5314 outbound.outbound.quality_limitation_reason,
5315 outbound.outbound.active
5316 ));
5317 snapshot.video.outbound_width = snapshot
5318 .video
5319 .outbound_width
5320 .max(outbound.outbound.frame_width);
5321 snapshot.video.outbound_height = snapshot
5322 .video
5323 .outbound_height
5324 .max(outbound.outbound.frame_height);
5325 }
5326 RtcStats::Transport(transport) => {
5327 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
5328 snapshot.tls_version = transport.transport.tls_version.clone();
5329 snapshot.dtls_cipher = transport.transport.dtls_cipher.clone();
5330 snapshot.srtp_cipher = transport.transport.srtp_cipher.clone();
5331 if !transport.transport.selected_candidate_pair_id.is_empty() {
5332 selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone());
5333 }
5334 }
5335 _ => {}
5336 }
5337 }
5338 if let Some(pair_id) = selected_pair_id {
5339 let pair = stats.iter().find_map(|entry| match entry {
5340 RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair),
5341 _ => None,
5342 });
5343 if let Some(pair) = pair {
5344 let describe = |candidate_id: &str| {
5345 stats
5346 .iter()
5347 .find_map(|entry| match entry {
5348 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
5349 Some(&local.local_candidate)
5350 }
5351 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
5352 Some(&remote.remote_candidate)
5353 }
5354 _ => None,
5355 })
5356 .map(|candidate| {
5357 let kind = candidate
5358 .candidate_type
5359 .map(|kind| format!("{kind:?}"))
5360 .unwrap_or_default();
5361 let relay = candidate
5362 .relay_protocol
5363 .map(|relay| format!(" via {relay:?}"))
5364 .unwrap_or_default();
5365 format!("{kind}/{}{relay}", candidate.protocol)
5366 })
5367 .unwrap_or_else(|| "?".into())
5368 };
5369 snapshot.selected_pair = Some(format!(
5370 "local {} <-> remote {}",
5371 describe(&pair.candidate_pair.local_candidate_id),
5372 describe(&pair.candidate_pair.remote_candidate_id)
5373 ));
5374 }
5375 }
5376 snapshot
5377 }
5378
5379 3007 #[cfg(test)]
5380 3008 mod tests {
5381 3009 #[test]
@@ -5552,7 +3180,7 @@ mod tests {
5552 3180 .unwrap();
5553 3181 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
5554 3182 let track = factory.create_audio_track("microphone", source);
5555 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3183 let offer = include_str!("../../tests/fixtures/teams_p2p_offer.sdp");
5556 3184 let answered = answer_offer(
5557 3185 &peer,
5558 3186 Some(&track),
@@ -1,9 +1,18 @@
1mod audio_switch;
2mod bots;
3mod escalation;
4mod peer_sdp;
5mod stats;
6mod teardown;
7
1use std::collections::BTreeMap;
8use std::collections::BTreeMap;
2use std::path::PathBuf;
9use std::path::PathBuf;
3use std::sync::Arc;
10use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
11use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
5use std::time::Duration;
12use std::time::Duration;
6
13
14use self::{audio_switch::*, bots::*, escalation::*, peer_sdp::*, stats::*, teardown::*};
15
7use chatsvc::TrouterCallback;
16use chatsvc::TrouterCallback;
8use futures_util::StreamExt;
17use futures_util::StreamExt;
9use libwebrtc::audio_stream::native::NativeAudioStream;
18use libwebrtc::audio_stream::native::NativeAudioStream;
@@ -308,86 +317,6 @@ fn random_u32() -> u32 {
308 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
317 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
309}
318}
310
319
311#[derive(Default)]
312struct Recording {
313 samples: Vec<i16>,
314 current_second: Vec<i16>,
315 per_second: Vec<(f32, f32)>,
316}
317
318enum PeerEvent {
319 Ice(IceConnectionState),
320 Connection(PeerConnectionState),
321 Track(RtcAudioTrack),
322 VideoTrack { mid: String, track: RtcVideoTrack },
323 Data(Vec<u8>),
324}
325
326struct PeerSession {
327 peer: PeerConnection,
328 events: mpsc::UnboundedReceiver<PeerEvent>,
329 _data_channel: Option<DataChannel>,
330 gathered: Gathered,
331}
332
333#[derive(Clone, Default)]
334struct Gathered {
335 candidates: Arc<std::sync::Mutex<Vec<String>>>,
336 complete: Arc<AtomicBool>,
337 relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
338 waited_ms: Arc<AtomicU64>,
339}
340
341/// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
342fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
343 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
344}
345
346impl Gathered {
347 fn settled(&self) -> bool {
348 let since_udp_relay = self
349 .relay_seen_at
350 .lock()
351 .expect("relay time lock")
352 .map(|at| at.elapsed());
353 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
354 }
355
356 async fn candidates(&self) -> Vec<String> {
357 let waited = Instant::now();
358 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
359 tokio::time::sleep(GATHERING_POLL).await;
360 }
361 self.complete.store(true, Ordering::SeqCst);
362 self.waited_ms
363 .store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
364 self.candidates.lock().expect("candidates lock").clone()
365 }
366
367 fn summary(&self) -> String {
368 let count = self.candidates.lock().expect("candidates lock").len();
369 format!(
370 "{count} candidate(s) after {} ms",
371 self.waited_ms.load(Ordering::SeqCst)
372 )
373 }
374}
375
376async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
377 match gathered {
378 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
379 None => Ok(teams_sdp.to_owned()),
380 }
381}
382
383struct OfferedMedia {
384 browser_offer: String,
385 signaled: SignaledOffer,
386 video: VideoLines,
387 plan: OfferPlan,
388 modalities: Vec<String>,
389}
390
391#[derive(Debug, Clone, Copy, PartialEq, Eq)]
320#[derive(Debug, Clone, Copy, PartialEq, Eq)]
392enum Layout {
321enum Layout {
393 Conference,
322 Conference,
@@ -400,84 +329,6 @@ pub enum AcceptMode {
400 Video,
329 Video,
401}
330}
402
331
403#[derive(Clone, Copy)]
404enum AnswerVideo<'a> {
405 Reject,
406 Receive,
407 Send(&'a RtcVideoTrack),
408}
409
410#[derive(Debug, Clone, Copy, PartialEq, Eq)]
411enum Change {
412 Hold(bool),
413 Camera(bool),
414 Share(bool),
415}
416
417struct SamePeerOffer {
418 browser_offer: String,
419 signaled: SignaledOffer,
420 change: Change,
421 reply_tags: Vec<String>,
422}
423
424struct GlareResend {
425 change: Change,
426 reply_tags: Vec<String>,
427 at: Instant,
428}
429
430struct NextPeer {
431 session: PeerSession,
432 offered: Option<OfferedMedia>,
433 answered: Option<AnsweredMedia>,
434 leg_links: BTreeMap<String, String>,
435 remote_audio: Option<RtcAudioTrack>,
436 reply_tags: Vec<String>,
437 deadline: Option<Instant>,
438 connected: bool,
439 retargeted: bool,
440}
441
442/// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced.
443fn replace_leg_media_links(
444 media_links: &mut BTreeMap<String, String>,
445 leg_links: &BTreeMap<String, String>,
446) {
447 media_links.extend(leg_links.clone());
448}
449
450fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
451 match callback_tag(callback_path) {
452 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
453 _ => true,
454 }
455}
456
457#[derive(Clone)]
458struct RemoteCall {
459 signaling: Arc<Signaling>,
460 conversation: Conversation,
461 participant: Participant,
462 threadless: bool,
463}
464
465#[derive(Default)]
466struct Live {
467 peers: Vec<PeerConnection>,
468 audio: Option<AudioSetup>,
469 remote: Option<RemoteCall>,
470 broker: Option<JoinHandle<()>>,
471 broker_running: Arc<AtomicBool>,
472 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
473 route_id: Option<String>,
474 call_legs: Vec<String>,
475 skip_leave: bool,
476 cancel_leave: bool,
477 video_tasks: Vec<JoinHandle<()>>,
478 video_counters: Arc<VideoCounters>,
479}
480
481fn remember_call_leg(live: &mut Live, url: Option<&str>) {
332fn remember_call_leg(live: &mut Live, url: Option<&str>) {
482 let Some(url) = url.filter(|url| !url.is_empty()) else {
333 let Some(url) = url.filter(|url| !url.is_empty()) else {
483 return;
334 return;
@@ -618,383 +469,6 @@ impl CallEngine {
618 }
469 }
619}
470}
620
471
621fn open_peer(
622 factory: &PeerConnectionFactory,
623 grant: &RelayGrant,
624 relay_host: &str,
625 with_data_channel: bool,
626) -> Result<PeerSession> {
627 let mut configuration = RtcConfiguration::default();
628 configuration.ice_servers = vec![grant.ice_server(relay_host)];
629 let peer = factory
630 .create_peer_connection(configuration)
631 .map_err(|error| Error::Webrtc(error.to_string()))?;
632 let (sender, events) = mpsc::unbounded_channel();
633 let data_channel = with_data_channel
634 .then(|| open_data_channel(&peer, sender.clone()))
635 .transpose()?;
636 let gathered = Gathered::default();
637 let candidate_sink = gathered.candidates.clone();
638 let relay_seen_at = gathered.relay_seen_at.clone();
639 peer.on_ice_candidate(Some(Box::new(move |candidate| {
640 if candidate.sdp_mline_index() == 0 {
641 let text = candidate.candidate();
642 if is_udp_relay(&text) {
643 relay_seen_at
644 .lock()
645 .expect("relay time lock")
646 .get_or_insert_with(Instant::now);
647 }
648 candidate_sink.lock().expect("candidates lock").push(text);
649 }
650 })));
651 let gathering_done = gathered.complete.clone();
652 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
653 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
654 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
655 IceGatheringState::New => {}
656 })));
657 let ice_sender = sender.clone();
658 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
659 let _ = ice_sender.send(PeerEvent::Ice(state));
660 })));
661 let connection_sender = sender.clone();
662 peer.on_connection_state_change(Some(Box::new(move |state| {
663 let _ = connection_sender.send(PeerEvent::Connection(state));
664 })));
665 peer.on_track(Some(Box::new(move |event| match event.track {
666 MediaStreamTrack::Audio(track) => {
667 let _ = sender.send(PeerEvent::Track(track));
668 }
669 MediaStreamTrack::Video(track) => {
670 let mid = event.transceiver.mid().unwrap_or_default();
671 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
672 }
673 })));
674 Ok(PeerSession {
675 peer,
676 events,
677 _data_channel: data_channel,
678 gathered,
679 })
680}
681
682fn open_data_channel(
683 peer: &PeerConnection,
684 sender: mpsc::UnboundedSender<PeerEvent>,
685) -> Result<DataChannel> {
686 let channel = peer
687 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
688 .map_err(|error| Error::Webrtc(error.to_string()))?;
689 channel.on_message(Some(Box::new(move |buffer| {
690 let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));
691 })));
692 Ok(channel)
693}
694
695fn one_to_one_directions<'a>(
696 camera: bool,
697 share: bool,
698 camera_mid: &'a str,
699 share_mid: Option<&'a str>,
700 remote_shares: bool,
701) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
702 move |line| match line.kind {
703 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
704 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
705 (true, true) => "sendrecv",
706 (true, false) => "sendonly",
707 (false, true) => "recvonly",
708 (false, false) => INACTIVE,
709 }),
710 _ => None,
711 }
712}
713
714fn share_mid_in(offer_text: &str) -> Option<String> {
715 let mut mid = None;
716 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
717 if line.starts_with("m=") {
718 mid = None;
719 } else if let Some(value) = line.strip_prefix("a=mid:") {
720 mid = Some(value.to_owned());
721 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
722 return mid;
723 }
724 }
725 None
726}
727
728#[allow(clippy::too_many_arguments)]
729fn directions_for(
730 layout: Layout,
731 hold: bool,
732 camera: bool,
733 share: bool,
734 camera_mid: &str,
735 share_mid: Option<&str>,
736 remote_shares: bool,
737 text: &str,
738) -> String {
739 match (hold, layout) {
740 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
741 (false, Layout::OneToOne) => rewrite_directions(
742 text,
743 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
744 ),
745 (false, Layout::Conference) => text.to_owned(),
746 }
747}
748
749async fn create_offer(
750 peer: &PeerConnection,
751 factory: &PeerConnectionFactory,
752 track: &RtcAudioTrack,
753 layout: Layout,
754 gathered: Option<&Gathered>,
755) -> Result<OfferedMedia> {
756 let transceiver_init = RtpTransceiverInit {
757 direction: RtpTransceiverDirection::SendRecv,
758 stream_ids: vec![MIC_STREAM.into()],
759 send_encodings: Vec::new(),
760 };
761 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
762 .map_err(|error| Error::Webrtc(error.to_string()))?;
763 let (video, plan) = match layout {
764 Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),
765 Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),
766 };
767 let offer = peer
768 .create_offer(OfferOptions {
769 offer_to_receive_audio: true,
770 offer_to_receive_video: true,
771 ..OfferOptions::default()
772 })
773 .await
774 .map_err(|error| Error::Webrtc(error.to_string()))?;
775 let browser_offer = directions_for(
776 layout,
777 false,
778 false,
779 false,
780 CAMERA_MID,
781 Some(ONE_TO_ONE_SHARE_MID),
782 false,
783 &offer.to_string(),
784 );
785 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
786 peer.set_local_description(description)
787 .await
788 .map_err(|error| Error::Webrtc(error.to_string()))?;
789 let mut numbers = random_u32;
790 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
791 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
792 Ok(OfferedMedia {
793 browser_offer,
794 signaled,
795 video,
796 plan,
797 modalities: accepted_modalities(false),
798 })
799}
800
801struct AnsweredMedia {
802 remote: RemoteOffer,
803 offer_sdp: String,
804 answer_sdp: String,
805 camera_mid: Option<String>,
806 receiving_share_mid: Option<String>,
807}
808
809fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
810 let main: Vec<_> = remote
811 .lines
812 .iter()
813 .filter(|line| line.role == LineRole::MainVideo)
814 .filter_map(|line| line.browser_mids.first().cloned())
815 .collect();
816 main.iter()
817 .find(|mid| {
818 matches!(
819 direction_of(&remote.browser_sdp, mid).as_deref(),
820 Some("sendrecv" | "recvonly")
821 )
822 })
823 .cloned()
824 .or_else(|| main.into_iter().next())
825}
826
827fn share_mids(remote: &RemoteOffer) -> Vec<String> {
828 remote
829 .lines
830 .iter()
831 .filter(|line| line.role == LineRole::ScreenShare)
832 .flat_map(|line| line.browser_mids.iter().cloned())
833 .collect()
834}
835
836fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> {
837 remote
838 .lines
839 .iter()
840 .find(|line| line.role == LineRole::ScreenShare)
841 .and_then(|line| line.browser_mids.last().cloned())
842}
843
844async fn answer_offer(
845 peer: &PeerConnection,
846 track: Option<&RtcAudioTrack>,
847 teams_offer: &str,
848 video: AnswerVideo<'_>,
849 sending_share_mid: Option<String>,
850 camera_on: bool,
851 gathered: Option<&Gathered>,
852) -> Result<AnsweredMedia> {
853 answer_offer_with(
854 peer,
855 track,
856 teams_offer,
857 video,
858 sending_share_mid,
859 None,
860 camera_on,
861 gathered,
862 false,
863 false,
864 )
865 .await
866}
867
868#[allow(clippy::too_many_arguments)]
869async fn answer_offer_with(
870 peer: &PeerConnection,
871 track: Option<&RtcAudioTrack>,
872 teams_offer: &str,
873 video: AnswerVideo<'_>,
874 sending_share_mid: Option<String>,
875 share_track: Option<&RtcVideoTrack>,
876 camera_on: bool,
877 gathered: Option<&Gathered>,
878 keep_receive_slots: bool,
879 mixer: bool,
880) -> Result<AnsweredMedia> {
881 let remote = from_teams_offer(teams_offer)?;
882 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
883 peer.set_remote_description(description)
884 .await
885 .map_err(|error| {
886 let lines: Vec<String> = remote
887 .lines
888 .iter()
889 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
890 .collect();
891 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
892 })?;
893 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
894 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
895 Vec::new()
896 } else {
897 share_mids(&remote)
898 };
899 if !keep_receive_slots {
900 for transceiver in peer.transceivers() {
901 let is_video = matches!(
902 transceiver.receiver().track(),
903 Some(MediaStreamTrack::Video(_))
904 );
905 let unused = transceiver.mid().is_some_and(|mid| {
906 Some(&mid) != camera_mid.as_ref()
907 && !kept_share_mids.contains(&mid)
908 && Some(&mid) != sending_share_mid.as_ref()
909 });
910 if is_video && unused {
911 let _ = transceiver.stop();
912 }
913 }
914 }
915 if let Some(track) = track {
916 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
917 .map_err(|error| Error::Webrtc(error.to_string()))?;
918 }
919 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
920 if mixer {
921 // Keep camera sendrecv so a later set_track / updateMediaDescriptions
922 // can start sending without renegotiation. Do NOT force folded
923 // x-multi-stream share lines to sendrecv: Teams rejects that answer
924 // with SdpParsingFailure (301000); starting share upgrades the peer.
925 if let Some(mid) = camera_mid.as_deref()
926 && let Some(camera) = peer_transceiver(peer, mid)
927 {
928 let _ = camera.set_direction(RtpTransceiverDirection::SendRecv);
929 if let AnswerVideo::Send(track) = video {
930 let _ = camera
931 .sender()
932 .set_track(Some(MediaStreamTrack::Video(track.clone())));
933 }
934 }
935 if let Some(mid) = sending_share_mid.as_deref()
936 && let Some(share) = peer_transceiver(peer, mid)
937 {
938 let _ = share.set_direction(RtpTransceiverDirection::SendRecv);
939 if let Some(track) = share_track {
940 let _ = share
941 .sender()
942 .set_track(Some(MediaStreamTrack::Video(track.clone())));
943 }
944 }
945 } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
946 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
947 .map_err(|error| Error::Webrtc(error.to_string()))?;
948 }
949 let answer = peer
950 .create_answer(AnswerOptions::default())
951 .await
952 .map_err(|error| Error::Webrtc(error.to_string()))?;
953 let mut answer_text = answer.to_string();
954 for mid in kept_share_mids
955 .iter()
956 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
957 {
958 answer_text = stop_sending_on(&answer_text, mid);
959 }
960 if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
961 answer_text = stop_sending_on(&answer_text, mid);
962 }
963 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
964 .await
965 .map_err(|error| Error::Webrtc(error.to_string()))?;
966 if mixer
967 && !sends_camera
968 && let Some(mid) = camera_mid.as_deref()
969 && let Some(camera) = peer_transceiver(peer, mid)
970 {
971 let _ = LocalVideo::set_sender_active(&camera.sender(), false);
972 }
973 let receiving_share_mid = share_carrier_mid(&remote)
974 .into_iter()
975 .chain(kept_share_mids)
976 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
977 .find(|mid| {
978 matches!(
979 direction_of(&answer_text, mid).as_deref(),
980 Some("recvonly" | "sendrecv")
981 )
982 });
983 let mut numbers = random_u32;
984 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
985 Ok(AnsweredMedia {
986 remote,
987 offer_sdp: teams_offer.to_owned(),
988 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
989 camera_mid,
990 receiving_share_mid,
991 })
992}
993
994fn new_media_leg_id() -> String {
995 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
996}
997
998async fn setup_step<T, E>(
472async fn setup_step<T, E>(
999 control: &mut CallControl,
473 control: &mut CallControl,
1000 step: impl std::future::Future<Output = std::result::Result<T, E>>,
474 step: impl std::future::Future<Output = std::result::Result<T, E>>,
@@ -1019,22 +493,6 @@ where
1019 }
493 }
1020}
494}
1021
495
1022async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
1023 match next {
1024 Some(next) => next.session.events.recv().await,
1025 None => std::future::pending().await,
1026 }
1027}
1028
1029fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
1030 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
1031}
1032
1033/// Re-queuing while `next` is set spins the call task (defer -> pending -> defer...).
1034fn camera_may_start(pending: bool, next_is_some: bool, possible: bool) -> bool {
1035 pending && !next_is_some && possible
1036}
1037
1038#[allow(clippy::too_many_arguments)]
496#[allow(clippy::too_many_arguments)]
1039async fn drive(
497async fn drive(
1040 inner: &Inner,
498 inner: &Inner,
@@ -3542,1840 +3000,10 @@ async fn drive(
3542 Ok(())
3000 Ok(())
3543}
3001}
3544
3002
3545#[allow(clippy::too_many_arguments)]
3546async fn start_escalation(
3547 factory: &PeerConnectionFactory,
3548 grant: &RelayGrant,
3549 options: &CallOptions,
3550 track: &RtcAudioTrack,
3551 remote: &RemoteCall,
3552 links: &CallbackLinks,
3553 media_leg_id: &str,
3554 acceptance_links: &BTreeMap<String, String>,
3555) -> Result<NextPeer> {
3556 let url = acceptance_links
3557 .get("mediaRenegotiation")
3558 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
3559 let session = open_peer(factory, grant, &options.relay_host, false)?;
3560 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
3561 let body = renegotiation_body(
3562 &remote.participant,
3563 links,
3564 &media.signaled.sdp,
3565 media_leg_id,
3566 &media.modalities,
3567 true,
3568 false,
3569 );
3570 let reply_tags = offer_reply_tags(&body);
3571 remote
3572 .signaling
3573 .post_json("POST mediaRenegotiation", url, body)
3574 .await?;
3575 Ok(NextPeer {
3576 session,
3577 offered: Some(media),
3578 answered: None,
3579 leg_links: acceptance_links.clone(),
3580 remote_audio: None,
3581 reply_tags,
3582 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
3583 connected: false,
3584 retargeted: false,
3585 })
3586}
3587
3588#[allow(clippy::too_many_arguments)]
3589async fn escalate(
3590 factory: &PeerConnectionFactory,
3591 grant: &RelayGrant,
3592 options: &CallOptions,
3593 track: &RtcAudioTrack,
3594 remote: &RemoteCall,
3595 links: &CallbackLinks,
3596 media_leg_id: &str,
3597 acceptance_links: &BTreeMap<String, String>,
3598 negotiator: &mut MediaNegotiator,
3599 live: &mut Live,
3600 timeline: &Timeline,
3601) -> Option<NextPeer> {
3602 match start_escalation(
3603 factory,
3604 grant,
3605 options,
3606 track,
3607 remote,
3608 links,
3609 media_leg_id,
3610 acceptance_links,
3611 )
3612 .await
3613 {
3614 Ok(pending) => {
3615 timeline.record("escalation", "new peer connection, new offer sent");
3616 if let Some(media) = &pending.offered {
3617 timeline.record_sdp("local offer", &media.signaled.sdp);
3618 }
3619 live.peers.push(pending.session.peer.clone());
3620 Some(pending)
3621 }
3622 Err(error) => {
3623 negotiator.escalation_failed();
3624 timeline.record("escalation failed", error.to_string());
3625 None
3626 }
3627 }
3628}
3629
3630#[allow(clippy::too_many_arguments)]
3631async fn answer_on_new_peer(
3632 factory: &PeerConnectionFactory,
3633 grant: &RelayGrant,
3634 options: &CallOptions,
3635 track: &RtcAudioTrack,
3636 teams_offer: &str,
3637 camera_on: bool,
3638 camera: Option<&RtcVideoTrack>,
3639 share: Option<&RtcVideoTrack>,
3640) -> Result<(PeerSession, AnsweredMedia)> {
3641 let session = open_peer(factory, grant, &options.relay_host, false)?;
3642 // Keep every video mid from the mixer offer (camera, gallery, share).
3643 // Reject would stop them and leave set_track InvalidState after the new
3644 // peer replaces the old one. When the camera is already on, answer sendrecv
3645 // so the remote keeps receiving across the escalation.
3646 let video = match (camera_on, camera) {
3647 (true, Some(camera)) => AnswerVideo::Send(camera),
3648 _ => AnswerVideo::Receive,
3649 };
3650 let answered = answer_offer_with(
3651 &session.peer,
3652 Some(track),
3653 teams_offer,
3654 video,
3655 None,
3656 share,
3657 camera_on,
3658 None,
3659 true,
3660 true,
3661 )
3662 .await?;
3663 Ok((session, answered))
3664}
3665
3666fn video_lines_from_answer(peer: &PeerConnection, answered: &AnsweredMedia) -> Option<VideoLines> {
3667 let camera_mid = answered.camera_mid.as_deref()?;
3668 let camera = peer_transceiver(peer, camera_mid)?;
3669 let share = share_carrier_mid(&answered.remote).and_then(|mid| peer_transceiver(peer, &mid));
3670 Some(VideoLines { camera, share })
3671}
3672
3673async fn send_media_answer(
3674 remote: &RemoteCall,
3675 links: &CallbackLinks,
3676 reply_links: &BTreeMap<String, String>,
3677 answered: &AnsweredMedia,
3678 media_leg_id: &str,
3679) -> Result<(BTreeMap<String, String>, String)> {
3680 let url = reply_links
3681 .get("mediaAnswer")
3682 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
3683 let body = escalation_answer_body(
3684 &remote.participant,
3685 links,
3686 &answered.answer_sdp,
3687 media_leg_id,
3688 );
3689 let response = remote
3690 .signaling
3691 .post_json_body("POST mediaAnswer", url, body)
3692 .await?;
3693 Ok((nested_links(&response), object_keys(&response)))
3694}
3695
3696fn absorb_answered_links(
3697 into: &mut BTreeMap<String, String>,
3698 extra: &BTreeMap<String, String>,
3699 timeline: &Timeline,
3700 response_keys: &str,
3701) {
3702 if extra.is_empty() {
3703 if !response_keys.is_empty() {
3704 timeline.record(
3705 "media answer links",
3706 format!("none, body keys {response_keys}"),
3707 );
3708 }
3709 return;
3710 }
3711 let names = extra.keys().cloned().collect::<Vec<_>>().join(",");
3712 timeline.record("media answer links", names);
3713 into.extend(extra.clone());
3714}
3715
3716#[allow(clippy::too_many_arguments)]
3717fn negotiate_video(
3718 video: &mut VideoReceive,
3719 signaling: &Arc<Signaling>,
3720 control: &CallControl,
3721 timeline: &Timeline,
3722 answer_sdp: &str,
3723 media: &OfferedMedia,
3724 from_mixer: bool,
3725 links: &BTreeMap<String, String>,
3726 roster: &Roster,
3727) {
3728 negotiate_video_lines(
3729 video,
3730 signaling,
3731 control,
3732 timeline,
3733 answer_sdp,
3734 &media.signaled.lines,
3735 from_mixer,
3736 links,
3737 roster,
3738 );
3739}
3740
3741#[allow(clippy::too_many_arguments)]
3742fn negotiate_video_lines(
3743 video: &mut VideoReceive,
3744 signaling: &Arc<Signaling>,
3745 control: &CallControl,
3746 timeline: &Timeline,
3747 teams_sdp: &str,
3748 lines: &[crate::sdp::SignaledLine],
3749 from_mixer: bool,
3750 links: &BTreeMap<String, String>,
3751 roster: &Roster,
3752) {
3753 let streams = match stream_lines(teams_sdp, lines) {
3754 Ok(streams) => streams,
3755 Err(error) => {
3756 timeline.record("video slots unknown", error.to_string());
3757 return;
3758 }
3759 };
3760 let table = SlotTable::from_streams(&streams);
3761 let link = links
3762 .get("applyChannelParameters")
3763 .or_else(|| links.get("controlVideoStreaming"));
3764 timeline.record(
3765 "video slots",
3766 format!(
3767 "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}",
3768 table.people.len(),
3769 table.screen.is_some(),
3770 link.is_some()
3771 ),
3772 );
3773 let requester = link.filter(|_| from_mixer).map(|url| {
3774 SourceRequester::start(
3775 signaling.clone(),
3776 url.clone(),
3777 video.router().clone(),
3778 control.video.clone(),
3779 timeline.clone(),
3780 )
3781 });
3782 video.negotiated(table, requester);
3783 send_receive_change(control, video.reselect(roster));
3784}
3785
3786fn tell_bound_camera(
3787 remote: &RemoteCall,
3788 links: &BTreeMap<String, String>,
3789 local_video: &LocalVideo,
3790 request_id: &mut u32,
3791 timeline: &Timeline,
3792) {
3793 let mid = local_video
3794 .camera_mid()
3795 .unwrap_or_else(|| CAMERA_MID.to_owned());
3796 tell_media_descriptions(
3797 remote,
3798 links,
3799 MediaDescription::camera_line(mid, local_video.camera_on()),
3800 request_id,
3801 timeline,
3802 );
3803}
3804
3805fn tell_bound_share(
3806 remote: &RemoteCall,
3807 links: &BTreeMap<String, String>,
3808 local_video: &LocalVideo,
3809 request_id: &mut u32,
3810 timeline: &Timeline,
3811) {
3812 if !local_video.sharing() {
3813 return;
3814 }
3815 let mid = local_video
3816 .share_mid()
3817 .unwrap_or_else(|| SHARE_MID.to_owned());
3818 tell_media_descriptions(
3819 remote,
3820 links,
3821 MediaDescription::share_line(mid, true),
3822 request_id,
3823 timeline,
3824 );
3825}
3826
3827async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3828 match mode {
3829 VideoMode::Pattern => vec![CameraDevice {
3830 key: "pattern".into(),
3831 name: "Test pattern".into(),
3832 }],
3833 VideoMode::Off => Vec::new(),
3834 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3835 .await
3836 .unwrap_or_default(),
3837 }
3838}
3839
3840fn refresh_cameras(
3841 updates: mpsc::UnboundedSender<CallUpdate>,
3842 mode: VideoMode,
3843 timeline: Timeline,
3844) {
3845 tokio::spawn(async move {
3846 let started = Instant::now();
3847 let cameras = camera_devices(mode).await;
3848 timeline.record(
3849 "camera list",
3850 format!(
3851 "{} camera(s) in {} ms",
3852 cameras.len(),
3853 started.elapsed().as_millis()
3854 ),
3855 );
3856 let _ = updates.send(CallUpdate::Cameras(cameras));
3857 });
3858}
3859
3860const SHARE_THUMBNAIL_WINDOWS: usize = 12;
3861const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3862const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3863
3864fn announce_share(control: &CallControl, source: &ShareSource) {
3865 control.send(CallUpdate::ShareKind(Some(source.kind)));
3866 control.send(CallUpdate::LocalShare(Some(source.label())));
3867}
3868
3869fn clear_share(control: &CallControl) {
3870 control.send(CallUpdate::ShareKind(None));
3871 control.send(CallUpdate::LocalShare(None));
3872}
3873
3874fn refresh_share_sources(
3875 updates: mpsc::UnboundedSender<CallUpdate>,
3876 mode: VideoMode,
3877 with_thumbnails: bool,
3878) {
3879 tokio::spawn(async move {
3880 let picker = current_share_picker();
3881 let sources = match mode {
3882 VideoMode::Pattern => vec![
3883 ShareSource {
3884 id: 1,
3885 kind: ShareKind::Screen,
3886 title: "Test screen".into(),
3887 },
3888 ShareSource {
3889 id: 2,
3890 kind: ShareKind::Window,
3891 title: "Test window".into(),
3892 },
3893 ],
3894 VideoMode::Off => Vec::new(),
3895 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3896 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3897 .await
3898 .unwrap_or_default(),
3899 };
3900 let sources = share_sources_for_menu(picker, sources);
3901 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3902 if picker == SharePicker::Portal || !with_thumbnails {
3903 return;
3904 }
3905 let wanted: Vec<ShareSource> = sources
3906 .iter()
3907 .filter(|source| source.kind == ShareKind::Screen)
3908 .chain(
3909 sources
3910 .iter()
3911 .filter(|source| source.kind == ShareKind::Window)
3912 .take(SHARE_THUMBNAIL_WINDOWS),
3913 )
3914 .cloned()
3915 .collect();
3916 for source in wanted {
3917 let picture = match mode {
3918 VideoMode::Platform => {
3919 let wanted = source.clone();
3920 tokio::task::spawn_blocking(move || {
3921 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3922 })
3923 .await
3924 .ok()
3925 .flatten()
3926 }
3927 VideoMode::Pattern => Some(VideoPicture::solid(
3928 SHARE_THUMBNAIL_WIDTH,
3929 SHARE_THUMBNAIL_HEIGHT,
3930 120,
3931 80,
3932 40,
3933 )),
3934 VideoMode::Off => None,
3935 };
3936 if let Some(picture) = picture
3937 && updates
3938 .send(CallUpdate::ShareThumbnail {
3939 source,
3940 picture: Arc::new(picture),
3941 })
3942 .is_err()
3943 {
3944 return;
3945 }
3946 }
3947 });
3948}
3949
3950fn tell_media_descriptions(
3951 remote: &RemoteCall,
3952 links: &BTreeMap<String, String>,
3953 description: MediaDescription,
3954 request_id: &mut u32,
3955 timeline: &Timeline,
3956) {
3957 let Some(url) = links.get("updateMediaDescriptions").cloned() else {
3958 timeline.record("updateMediaDescriptions skipped", "no link from the mixer");
3959 return;
3960 };
3961 *request_id += 1;
3962 let request_id = *request_id;
3963 let signaling = remote.signaling.clone();
3964 let timeline = timeline.clone();
3965 tokio::spawn(async move {
3966 let sent = format!(
3967 "{} {} request {request_id}",
3968 description.mid, description.direction
3969 );
3970 if let Err(error) = signaling
3971 .update_media_descriptions(&url, &[description], request_id)
3972 .await
3973 {
3974 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
3975 }
3976 });
3977}
3978
3979fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
3980 own.is_some_and(|own| own.thread_id == target.thread_id)
3981}
3982
3983fn attach_share_line(
3984 peer: &PeerConnection,
3985 factory: &PeerConnectionFactory,
3986 local_video: &mut LocalVideo,
3987 camera_mid: Option<&str>,
3988) -> Result<()> {
3989 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
3990 if !local_video.has_lines() && camera.is_none() {
3991 return Err(Error::Webrtc("no video line negotiated".into()));
3992 }
3993 let share = add_share_line(peer, factory)?;
3994 local_video
3995 .add_share_line(share.clone(), camera)
3996 .inspect_err(|_| {
3997 let _ = share.stop();
3998 })
3999}
4000
4001fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
4002 peer.transceivers()
4003 .into_iter()
4004 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
4005}
4006
4007fn start_camera_line(
4008 local_video: &mut LocalVideo,
4009 peer: &PeerConnection,
4010 direct_mid: Option<&str>,
4011 choice: &DeviceChoice,
4012) -> Result<()> {
4013 if !local_video.has_lines() {
4014 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
4015 let camera = peer_transceiver(peer, mid)
4016 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
4017 if !matches!(
4018 camera.direction(),
4019 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
4020 ) {
4021 peer.add_track(
4022 MediaStreamTrack::Video(local_video.camera_track()),
4023 &[CAMERA_STREAM],
4024 )
4025 .map_err(|error| Error::Webrtc(error.to_string()))?;
4026 }
4027 local_video.set_lines(VideoLines {
4028 camera,
4029 share: None,
4030 })?;
4031 }
4032 local_video.start_camera(choice)
4033}
4034
4035#[allow(clippy::too_many_arguments)]
4036async fn offer_same_peer(
4037 peer: &PeerConnection,
4038 gathered: &Gathered,
4039 own_share_mid: Option<String>,
4040 plan: &OfferPlan,
4041 layout: Layout,
4042 camera_mid: &str,
4043 hold: bool,
4044 camera: bool,
4045 share: bool,
4046 remote: &RemoteCall,
4047 links: &CallbackLinks,
4048 media_leg_id: &str,
4049 media_links: &BTreeMap<String, String>,
4050 negotiator: &mut MediaNegotiator,
4051) -> Result<(String, SignaledOffer, Vec<String>)> {
4052 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
4053 let url = media_links
4054 .get("mediaRenegotiation")
4055 .cloned()
4056 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
4057 if !negotiator.begin_same_peer_offer() {
4058 return Err(Error::Signaling(
4059 "another media negotiation is running".into(),
4060 ));
4061 }
4062 let offered = build_same_peer_offer(
4063 peer,
4064 plan,
4065 layout,
4066 hold,
4067 camera,
4068 share,
4069 camera_mid,
4070 own_share_mid,
4071 direct.then_some(gathered),
4072 )
4073 .await;
4074 let (text, signaled) = match offered {
4075 Ok(offered) => offered,
4076 Err(error) => {
4077 negotiator.same_peer_offer_failed();
4078 return Err(error);
4079 }
4080 };
4081 let modalities = offer_modalities(
4082 layout == Layout::OneToOne && camera && !hold,
4083 share && !hold,
4084 );
4085 let body = renegotiation_body(
4086 &remote.participant,
4087 links,
4088 &signaled.sdp,
4089 media_leg_id,
4090 &modalities,
4091 false,
4092 direct,
4093 );
4094 let reply_tags = offer_reply_tags(&body);
4095 if let Err(error) = remote
4096 .signaling
4097 .post_json("POST mediaRenegotiation (same peer)", &url, body)
4098 .await
4099 {
4100 negotiator.same_peer_offer_failed();
4101 rollback_offer(peer).await;
4102 return Err(error);
4103 }
4104 Ok((text, signaled, reply_tags))
4105}
4106
4107#[allow(clippy::too_many_arguments)]
4108async fn build_same_peer_offer(
4109 peer: &PeerConnection,
4110 plan: &OfferPlan,
4111 layout: Layout,
4112 hold: bool,
4113 camera: bool,
4114 share: bool,
4115 camera_mid: &str,
4116 own_share_mid: Option<String>,
4117 gathered: Option<&Gathered>,
4118) -> Result<(String, SignaledOffer)> {
4119 let offer = peer
4120 .create_offer(OfferOptions {
4121 offer_to_receive_audio: true,
4122 offer_to_receive_video: true,
4123 ..OfferOptions::default()
4124 })
4125 .await
4126 .map_err(|error| Error::Webrtc(error.to_string()))?;
4127 let offer_text = offer.to_string();
4128 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
4129 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
4130 peer.current_remote_description()
4131 .and_then(|remote| direction_of(&remote.to_string(), mid))
4132 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
4133 });
4134 let text = directions_for(
4135 layout,
4136 false,
4137 camera,
4138 share,
4139 camera_mid,
4140 share_mid.as_deref(),
4141 remote_shares,
4142 &offer_text,
4143 );
4144 let description = parse_sdp(&text, SdpType::Offer)?;
4145 peer.set_local_description(description)
4146 .await
4147 .map_err(|error| Error::Webrtc(error.to_string()))?;
4148 let mut numbers = random_u32;
4149 let mut plan = plan.clone();
4150 if let Some(mid) = share_mid
4151 .as_ref()
4152 .filter(|mid| !plan.screen_share_mids.contains(mid))
4153 {
4154 plan.screen_share_mids.push(mid.clone());
4155 }
4156 let mut signaled = to_teams_offer(
4157 &directions_for(
4158 layout,
4159 hold,
4160 camera,
4161 share,
4162 camera_mid,
4163 share_mid.as_deref(),
4164 remote_shares,
4165 &text,
4166 ),
4167 &plan,
4168 &mut numbers,
4169 )?;
4170 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
4171 if gathered.is_some()
4172 && let Some(role) = negotiated_setup(
4173 peer.current_local_description()
4174 .map(|local| local.to_string())
4175 .as_deref(),
4176 peer.current_remote_description()
4177 .map(|remote| remote.to_string())
4178 .as_deref(),
4179 )
4180 {
4181 signaled.sdp = signaled
4182 .sdp
4183 .replace("a=setup:actpass", &format!("a=setup:{role}"));
4184 }
4185 Ok((text, signaled))
4186}
4187
4188/// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
4189fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
4190 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
4191 Ok(Ok(description)) => Ok(description),
4192 Ok(Err(error)) => Err(Error::Sdp(format!(
4193 "{kind:?} rejected: {}",
4194 error.description
4195 ))),
4196 Err(_) => Err(Error::Sdp(format!(
4197 "{kind:?} rejected, libwebrtc gave no readable reason"
4198 ))),
4199 }
4200}
4201
4202async fn rollback_offer(peer: &PeerConnection) {
4203 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
4204 let _ = peer.set_local_description(rollback).await;
4205 }
4206}
4207
4208async fn rollback_remote_offer(peer: &PeerConnection) {
4209 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
4210 let _ = peer.set_remote_description(rollback).await;
4211 }
4212}
4213
4214fn is_glare_rejection(body: &serde_json::Value) -> bool {
4215 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
4216}
4217
4218fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
4219 let links = &body["mediaNegotiation"]["links"];
4220 ["mediaAnswer", "rejection"]
4221 .iter()
4222 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
4223 .collect()
4224}
4225
4226#[cfg(test)]
4227mod reply_tag_tests {
4228 use super::*;
4229
4230 #[test]
4231 fn answers_and_rejections_match_the_offer_by_tag() {
4232 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
4233 assert!(answers_offer(
4234 "callAgent/c/aaaa1111/call/mediaAnswer/",
4235 &tags
4236 ));
4237 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
4238 assert!(!answers_offer(
4239 "callAgent/c/cccc3333/call/mediaAnswer/",
4240 &tags
4241 ));
4242 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
4243 }
4244
4245 #[test]
4246 fn an_offer_names_both_reply_tags() {
4247 let body = serde_json::json!({"mediaNegotiation": {"links": {
4248 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
4249 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
4250 assert_eq!(
4251 offer_reply_tags(&body),
4252 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
4253 );
4254 }
4255}
4256
4257fn defer_to_new_peer(
4258 change: Change,
4259 deferred: &mut Vec<Change>,
4260 local_video: &mut LocalVideo,
4261 control: &CallControl,
4262) {
4263 match change {
4264 Change::Camera(true) => {
4265 control.send(CallUpdate::Camera(true));
4266 deferred.push(change);
4267 }
4268 Change::Share(true) => deferred.push(change),
4269 change => undo_change(change, local_video, control),
4270 }
4271}
4272
4273/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
4274fn settle_failed_escalation(
4275 server: bool,
4276 layout: Layout,
4277 negotiator: &mut MediaNegotiator,
4278 deferred: &mut Vec<Change>,
4279 local_video: &mut LocalVideo,
4280 control: &CallControl,
4281) {
4282 if server {
4283 negotiator.server_escalation_failed();
4284 for change in deferred.drain(..) {
4285 undo_change(change, local_video, control);
4286 }
4287 } else if layout == Layout::OneToOne {
4288 drop_local_media(local_video, control);
4289 }
4290}
4291
4292fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
4293 if local_video.sharing() {
4294 local_video.stop_share();
4295 clear_share(control);
4296 }
4297 if local_video.camera_on() {
4298 local_video.stop_camera();
4299 control.send(CallUpdate::Camera(false));
4300 }
4301}
4302
4303fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
4304 match change {
4305 Change::Camera(true) => {
4306 local_video.stop_camera();
4307 control.send(CallUpdate::Camera(false));
4308 }
4309 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
4310 Change::Share(true) => {
4311 local_video.stop_share();
4312 clear_share(control);
4313 control.send(CallUpdate::Notice(notice_with_detail(
4314 SHARING_START_NOTICE,
4315 "",
4316 )));
4317 }
4318 Change::Share(false) => {}
4319 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
4320 }
4321}
4322
4323fn withhold_media(
4324 muted: &mut bool,
4325 audio: &AudioSetup,
4326 software_audio: Option<&SoftwareAudio>,
4327 remote: &RemoteCall,
4328 local_video: &mut LocalVideo,
4329 control: &CallControl,
4330) {
4331 *muted = apply_mute(
4332 MuteCommand::Mute,
4333 *muted,
4334 audio,
4335 software_audio,
4336 remote,
4337 control,
4338 );
4339 if local_video.camera_on() {
4340 local_video.stop_camera();
4341 control.send(CallUpdate::Camera(false));
4342 }
4343}
4344
4345async fn apply_background(
4346 choice: BackgroundChoice,
4347 local_video: &LocalVideo,
4348 control: &CallControl,
4349 timeline: &Timeline,
4350) {
4351 match choice {
4352 BackgroundChoice::None => local_video.set_background(false, None),
4353 BackgroundChoice::Blur => local_video.set_background(true, None),
4354 BackgroundChoice::Image(path) => {
4355 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
4356 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
4357 Ok(Err(error)) => {
4358 timeline.record("background image failed", error.to_string());
4359 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
4360 }
4361 Err(_) => {}
4362 }
4363 }
4364 }
4365}
4366
4367async fn save_meeting_options(
4368 session: &session::Session,
4369 target: &MeetingTarget,
4370 writes: &[OptionWrite],
4371) -> std::result::Result<meeting_options::MeetingOptions, String> {
4372 for change in writes {
4373 meeting_options::write(session, target, change)
4374 .await
4375 .map_err(|error| error.to_string())?;
4376 }
4377 meeting_options::fetch(session, target)
4378 .await
4379 .map_err(|error| error.to_string())
4380}
4381
4382fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
4383 let display_name = roster
4384 .members()
4385 .iter()
4386 .find(|member| member.mri == mri)
4387 .map_or("", |member| member.display_name.as_str());
4388 Target { mri, display_name }
4389}
4390
4391const RECORDING_STOP_RETRIES: usize = 6;
4392const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5);
4393
4394/// The recorder answers 409 to a stop sent while its start is still settling.
4395fn recorder_busy(error: &Error) -> bool {
4396 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
4397}
4398
4399fn report_organizer_result(
4400 result: Result<u16>,
4401 label: &str,
4402 notice: &'static str,
4403 control: &CallControl,
4404 timeline: &Timeline,
4405) {
4406 if let Err(error) = &result {
4407 timeline.record(format!("{label} failed"), error.to_string());
4408 control.send(CallUpdate::Notice(notice.to_owned()));
4409 }
4410 control.send(CallUpdate::Organizer {
4411 action: label.to_owned(),
4412 outcome: result.map_err(|error| error.to_string()),
4413 });
4414}
4415
4416fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
4417 if entry.display_name.is_empty() {
4418 entry.display_name = roster
4419 .name_of(&entry.user_id)
4420 .unwrap_or_default()
4421 .to_owned();
4422 }
4423 entry
4424}
4425
4426#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4427enum BotJob {
4428 Captions,
4429 Recording,
4430}
4431
4432#[allow(clippy::too_many_arguments)]
4433async fn run_bot_steps(
4434 job: BotJob,
4435 flow: &mut CaptionFlow,
4436 roster: &Roster,
4437 remote: &RemoteCall,
4438 links: &CallbackLinks,
4439 meeting_chat: Option<&str>,
4440 plan: &RecordingPlan,
4441 bot_pending: &mut bool,
4442 control: &CallControl,
4443 timeline: &Timeline,
4444) {
4445 let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
4446 BotJob::Captions => |bot| bot.active,
4447 BotJob::Recording => |bot| bot.recording,
4448 };
4449 let fail = |flow: &mut CaptionFlow, reason: &str| {
4450 flow.failed();
4451 control.send(match job {
4452 BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
4453 BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
4454 });
4455 if job == BotJob::Recording {
4456 control.send(CallUpdate::RecordingPending(false));
4457 }
4458 };
4459 let (join_failure, start_failure) = match job {
4460 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
4461 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
4462 };
4463 loop {
4464 match flow.next_for(roster.caption_bot(), is_active) {
4465 CaptionStep::Wait => return,
4466 CaptionStep::AddBot => {
4467 if *bot_pending {
4468 continue;
4469 }
4470 let Some(thread) = meeting_chat else {
4471 return fail(
4472 flow,
4473 "This call has no chat for the captions and the recording",
4474 );
4475 };
4476 *bot_pending = true;
4477 let added = remote
4478 .signaling
4479 .add_caption_bot(
4480 &remote.conversation,
4481 &remote.participant,
4482 thread,
4483 links,
4484 remote.threadless,
4485 )
4486 .await;
4487 if job == BotJob::Recording {
4488 report_organizer_result(
4489 added
4490 .as_ref()
4491 .map(|status| *status)
4492 .map_err(|error| Error::Signaling(error.to_string())),
4493 "recording add bot",
4494 join_failure,
4495 control,
4496 timeline,
4497 );
4498 }
4499 if let Err(error) = added {
4500 timeline.record("bot invitation failed", error.to_string());
4501 *bot_pending = false;
4502 return fail(flow, join_failure);
4503 }
4504 }
4505 CaptionStep::Start => {
4506 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
4507 return;
4508 };
4509 match job {
4510 BotJob::Captions => {
4511 if let Err(error) = remote
4512 .signaling
4513 .caption_command(&url, BotAction::Start, &remote.participant)
4514 .await
4515 {
4516 timeline.record("caption start failed", error.to_string());
4517 return fail(flow, start_failure);
4518 }
4519 if let Err(error) = remote
4520 .signaling
4521 .set_caption_preference(&remote.conversation, &remote.participant, true)
4522 .await
4523 {
4524 timeline.record("caption preference failed", error.to_string());
4525 }
4526 }
4527 BotJob::Recording => {
4528 let started = remote
4529 .signaling
4530 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
4531 .await;
4532 let failed = started.is_err();
4533 report_organizer_result(
4534 started,
4535 "recording start",
4536 start_failure,
4537 control,
4538 timeline,
4539 );
4540 if failed {
4541 return fail(flow, start_failure);
4542 }
4543 }
4544 }
4545 }
4546 CaptionStep::Stop => {
4547 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
4548 continue;
4549 };
4550 match job {
4551 BotJob::Captions => {
4552 if let Err(error) = remote
4553 .signaling
4554 .caption_command(&url, BotAction::Stop, &remote.participant)
4555 .await
4556 {
4557 timeline.record("caption stop failed", error.to_string());
4558 }
4559 if let Err(error) = remote
4560 .signaling
4561 .set_caption_preference(
4562 &remote.conversation,
4563 &remote.participant,
4564 false,
4565 )
4566 .await
4567 {
4568 timeline.record("caption preference failed", error.to_string());
4569 }
4570 }
4571 BotJob::Recording => {
4572 let remote = remote.clone();
4573 let updates = control.updates();
4574 let (command, title) = (plan.stop(), plan.title.clone());
4575 tokio::spawn(async move {
4576 let mut stopped = remote
4577 .signaling
4578 .recording_command(&url, command, &remote.participant, &title)
4579 .await;
4580 for _ in 0..RECORDING_STOP_RETRIES {
4581 if !stopped.as_ref().is_err_and(recorder_busy) {
4582 break;
4583 }
4584 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
4585 stopped = remote
4586 .signaling
4587 .recording_command(&url, command, &remote.participant, &title)
4588 .await;
4589 }
4590 if stopped.is_err() {
4591 let _ = updates
4592 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
4593 }
4594 let _ = updates.send(CallUpdate::Organizer {
4595 action: "recording stop".into(),
4596 outcome: stopped.map_err(|error| error.to_string()),
4597 });
4598 });
4599 }
4600 }
4601 }
4602 CaptionStep::ReportOn => {
4603 if job == BotJob::Captions {
4604 control.send(CallUpdate::Captions(CaptionState::On));
4605 }
4606 }
4607 }
4608 }
4609}
4610
4611fn send_receive_change(control: &CallControl, change: ReceiveChange) {
4612 if let Some(sharer) = change.screen_sharer {
4613 control.send(CallUpdate::ScreenShare(sharer));
4614 }
4615}
4616
4617fn record_audio_devices(
4618 timeline: &Timeline,
4619 lists: &devices::DeviceLists,
4620 input: Option<&AppliedDevice>,
4621 output: Option<&AppliedDevice>,
4622) {
4623 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
4624 applied
4625 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
4626 .map_or("none", |device| device.name.as_str())
4627 .to_owned()
4628 };
4629 timeline.record(
4630 "audio devices",
4631 format!(
4632 "input={} output={}",
4633 name(&lists.inputs, input),
4634 name(&lists.outputs, output)
4635 ),
4636 );
4637}
4638
4639fn follow_device_change(
4640 flow: Flow,
4641 (previous, current): (&[AudioDevice], &[AudioDevice]),
4642 choice: &DeviceChoice,
4643 applied: &mut Option<AppliedDevice>,
4644 select: impl Fn(u16) -> bool,
4645 timeline: &Timeline,
4646 control: &CallControl,
4647) -> bool {
4648 let system_default = devices::system_default_id(flow);
4649 let (index, fell_back) =
4650 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
4651 Reselect::Keep => return false,
4652 Reselect::Select(index) => (index, false),
4653 Reselect::FallBack(index) => (index, true),
4654 };
4655 let selected = select(index);
4656 timeline.record(
4657 "device change",
4658 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
4659 );
4660 if selected {
4661 *applied = current
4662 .iter()
4663 .find(|device| device.index == index)
4664 .map(|device| AppliedDevice {
4665 index,
4666 key: device.key(),
4667 });
4668 }
4669 if fell_back {
4670 let fallback = current.iter().find(|device| device.index == index);
4671 control.send(CallUpdate::Notice(devices::disconnect_notice(
4672 previous, choice, fallback,
4673 )));
4674 }
4675 selected
4676}
4677
4678fn far_future() -> Instant {
3003fn far_future() -> Instant {
4679 Instant::now() + FAR_FUTURE
3004 Instant::now() + FAR_FUTURE
4680}
3005}
4681
3006
4682fn apply_mute(
4683 command: MuteCommand,
4684 currently_muted: bool,
4685 audio: &AudioSetup,
4686 software_audio: Option<&SoftwareAudio>,
4687 remote: &RemoteCall,
4688 control: &CallControl,
4689) -> bool {
4690 let effect = MuteEffect::for_muted(command.target(currently_muted));
4691 audio.track.set_enabled(effect.track_enabled);
4692 if let Some(software_audio) = software_audio {
4693 software_audio.set_microphone_muted(effect.muted);
4694 }
4695 control.send(CallUpdate::Muted(effect.muted));
4696 let remote = remote.clone();
4697 tokio::spawn(async move {
4698 let _ = remote
4699 .signaling
4700 .update_endpoint_state(
4701 &remote.conversation,
4702 &remote.participant,
4703 effect.endpoint_is_muted,
4704 )
4705 .await;
4706 });
4707 effect.muted
4708}
4709
4710fn silence_for_hold(
4711 on_hold: bool,
4712 muted: bool,
4713 audio: Option<&AudioSetup>,
4714 software_audio: Option<&SoftwareAudio>,
4715) {
4716 let silent = on_hold || muted;
4717 if let Some(audio) = audio {
4718 audio
4719 .track
4720 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
4721 }
4722 if let Some(software_audio) = software_audio {
4723 software_audio.set_microphone_muted(silent);
4724 }
4725}
4726
4727fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
4728 let sender = peer
4729 .senders()
4730 .into_iter()
4731 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
4732 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
4733 sender
4734 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
4735 .map_err(|error| Error::Webrtc(error.to_string()))
4736}
4737
4738fn outgoing_track<'a>(
4739 software_audio: Option<&'a SoftwareAudio>,
4740 device_track: &'a RtcAudioTrack,
4741) -> &'a RtcAudioTrack {
4742 pick_track(software_audio.map(|audio| &audio.track), device_track)
4743}
4744
4745fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T {
4746 software.unwrap_or(device)
4747}
4748
4749fn software_wanted(
4750 mic_settings: MicSettings,
4751 share_sound_wanted: bool,
4752 local_video: &LocalVideo,
4753 audio: Option<&AudioSetup>,
4754) -> Option<SoftwareAudioPlan> {
4755 let sharing_sound = share_sound_wanted && local_video.sharing();
4756 SoftwareAudioPlan::wanted(
4757 mic_settings,
4758 sharing_sound,
4759 audio.is_some_and(AudioSetup::uses_devices),
4760 )
4761}
4762
4763fn restore_device_track(
4764 factory: &PeerConnectionFactory,
4765 input: &DeviceChoice,
4766 peer: &PeerConnection,
4767 device_track: &RtcAudioTrack,
4768 timeline: &Timeline,
4769) {
4770 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4771 if !factory.adm_recording_enabled() {
4772 factory.set_adm_recording_enabled(true);
4773 devices::select_input(factory, input);
4774 }
4775 if let Err(error) = swap_audio_track(peer, device_track) {
4776 timeline.record("microphone track not restored", error.to_string());
4777 }
4778}
4779
4780#[allow(clippy::too_many_arguments)]
4781fn sync_software_audio(
4782 factory: &PeerConnectionFactory,
4783 options: &CallOptions,
4784 input: &DeviceChoice,
4785 muted: bool,
4786 remote_audio: Option<RtcAudioTrack>,
4787 peer: &PeerConnection,
4788 device_track: &RtcAudioTrack,
4789 wanted: Option<SoftwareAudioPlan>,
4790 restart: bool,
4791 software_audio: &mut Option<SoftwareAudio>,
4792 mic_settings: MicSettings,
4793 control: &CallControl,
4794 timeline: &Timeline,
4795) {
4796 let running = software_audio.as_ref().map(|audio| audio.plan);
4797 if running == wanted && !restart {
4798 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4799 return;
4800 }
4801 if running.is_some() {
4802 timeline.record("software audio", "stopping");
4803 }
4804 *software_audio = None;
4805 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
4806 let Some(plan) = wanted else {
4807 restore_device_track(factory, input, peer, device_track, timeline);
4808 control.send(CallUpdate::ShareSound(false));
4809 crate::noise_stage::apply_for_outgoing(mic_settings, true);
4810 return;
4811 };
4812 let started = SoftwareAudio::start(
4813 factory,
4814 options.audio,
4815 options.tone_hz,
4816 input,
4817 plan,
4818 muted,
4819 remote_audio,
4820 )
4821 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4822 match started {
4823 Ok(audio) => {
4824 timeline.record(
4825 "software audio",
4826 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4827 );
4828 if let Some(source) = &audio.microphone_source {
4829 timeline.record("mic capture", source.clone());
4830 }
4831 if audio.microphone_source.is_some() {
4832 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4833 factory.set_adm_recording_enabled(false);
4834 }
4835 if let Some(warning) = &audio.warning {
4836 timeline.record("computer sound warning", warning.clone());
4837 }
4838 control.send(CallUpdate::ShareSound(plan.computer_sound));
4839 if let Some(notice) = audio.microphone_notice {
4840 control.send(CallUpdate::Notice(notice.into()));
4841 }
4842 *software_audio = Some(audio);
4843 }
4844 Err(error) => {
4845 timeline.record("software audio failed", error.to_string());
4846 restore_device_track(factory, input, peer, device_track, timeline);
4847 if was_sharing_sound || plan.computer_sound {
4848 control.send(CallUpdate::ShareSound(false));
4849 }
4850 let notice = if plan.computer_sound {
4851 "Computer sound could not start, sharing without it"
4852 } else {
4853 "Microphone processing could not start, using the standard microphone"
4854 };
4855 control.send(CallUpdate::Notice(notice.into()));
4856 }
4857 }
4858 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4859}
4860
4861async fn stop_local_publish(
4862 local_video: &mut LocalVideo,
4863 remote: &RemoteCall,
4864 media_links: &BTreeMap<String, String>,
4865 request_id: &mut u32,
4866 control: &CallControl,
4867 timeline: &Timeline,
4868) {
4869 let camera_mid = local_video.camera_mid();
4870 let share_mid = local_video.share_mid();
4871 let was_sharing = local_video.sharing();
4872 let was_camera = local_video.camera_on() || local_video.camera_previewing();
4873 if was_sharing {
4874 local_video.stop_share();
4875 clear_share(control);
4876 }
4877 if was_camera {
4878 local_video.stop_camera();
4879 control.send(CallUpdate::Camera(false));
4880 }
4881 local_video.clear_lines();
4882 let Some(url) = media_links.get("updateMediaDescriptions").cloned() else {
4883 return;
4884 };
4885 let mut descriptions = Vec::new();
4886 if was_camera {
4887 descriptions.push(MediaDescription::camera_line(
4888 camera_mid.unwrap_or_else(|| CAMERA_MID.to_owned()),
4889 false,
4890 ));
4891 }
4892 if was_sharing {
4893 descriptions.push(MediaDescription::share_line(
4894 share_mid.unwrap_or_else(|| SHARE_MID.to_owned()),
4895 false,
4896 ));
4897 }
4898 if descriptions.is_empty() {
4899 return;
4900 }
4901 *request_id += 1;
4902 let id = *request_id;
4903 match remote
4904 .signaling
4905 .update_media_descriptions(&url, &descriptions, id)
4906 .await
4907 {
4908 Ok(()) => timeline.record(
4909 "updateMediaDescriptions",
4910 format!("publish off before leave, request {id}"),
4911 ),
4912 Err(error) => timeline.record(
4913 "updateMediaDescriptions failed",
4914 format!("publish off before leave: {error}"),
4915 ),
4916 }
4917}
4918
4919async fn tear_down(
4920 mut live: Live,
4921 inner: &Inner,
4922 timeline: &Timeline,
4923 report: &mut CallReport,
4924 cancelled: bool,
4925) {
4926 if crate::noise_stage::overloaded() {
4927 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
4928 }
4929 crate::noise_stage::clear();
4930 // Stop keep-alive / broker first so Teams does not see us as still present.
4931 live.broker_running.store(false, Ordering::SeqCst);
4932 if let Some(broker) = live.broker.take() {
4933 broker.abort();
4934 }
4935 if let Some(audio) = live.audio.take() {
4936 audio.stop().await;
4937 }
4938 // Leave and drop call legs while peers are still open, then close media.
4939 if !live.skip_leave
4940 && let Some(remote) = &live.remote
4941 {
4942 let reason = if cancelled {
4943 LeaveReason::Cancel
4944 } else {
4945 LeaveReason::Hangup
4946 };
4947 match remote
4948 .signaling
4949 .leave(&remote.conversation, &remote.participant, reason)
4950 .await
4951 {
4952 Ok(()) => report.left_cleanly = true,
4953 Err(error) => timeline.record("leave failed", error.to_string()),
4954 }
4955 for call_leg in &live.call_legs {
4956 if let Err(error) = remote.signaling.end_call_leg(call_leg).await {
4957 timeline.record("callLeg end failed", error.to_string());
4958 }
4959 }
4960 }
4961 if report.end.is_none()
4962 && let Some(callbacks) = live.callbacks.as_mut()
4963 && live.remote.is_some()
4964 {
4965 let waited = timeout(END_CALLBACK_WAIT, async {
4966 while let Some(callback) = callbacks.recv().await {
4967 let event = handle_callback(&callback, timeline);
4968 if let Ok(CallEvent::End(end)) = event {
4969 return Some(end);
4970 }
4971 }
4972 None
4973 })
4974 .await;
4975 report.end = waited.ok().flatten();
4976 }
4977 for peer in &live.peers {
4978 peer.close();
4979 }
4980 for task in live.video_tasks.drain(..) {
4981 task.abort();
4982 }
4983 if let Some(route_id) = &live.route_id {
4984 inner.unregister_route(route_id);
4985 }
4986 timeline.record("closed", "peer closed, call route removed");
4987}
4988
4989fn setup_end_kind(end: &CallEnd) -> EndKind {
4990 match end.kind() {
4991 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
4992 kind => kind,
4993 }
4994}
4995
4996fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
4997 let body = decode_body(callback)?;
4998 let (_, event) = classify(&callback.path, body)?;
4999 let detail = match &event {
5000 CallEvent::Acceptance(acceptance) => format!(
5001 "answer sdp {} bytes, fromMixer={}",
5002 acceptance.sdp.len(),
5003 acceptance.from_mixer
5004 ),
5005 CallEvent::End(end) => format!(
5006 "code={} subCode={} phrase={}",
5007 end.code, end.sub_code, end.phrase
5008 ),
5009 CallEvent::Progress(status) => format!("{status:?}"),
5010 CallEvent::ConversationEnd(body)
5011 | CallEvent::Rejection(body)
5012 | CallEvent::AddParticipantFailure(body)
5013 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
5014 CallEvent::ControlVideoStreaming(body) => parse_request(body)
5015 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
5016 CallEvent::MediaAcknowledgement(ack) => {
5017 let names = ack.links.keys().cloned().collect::<Vec<_>>().join(",");
5018 if names.is_empty() {
5019 format!("links=none keys={}", ack.keys)
5020 } else {
5021 format!("links={names}")
5022 }
5023 }
5024 _ => String::new(),
5025 };
5026 timeline.record(format!("Trouter {}", event.name()), detail);
5027 match &event {
5028 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
5029 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
5030 CallEvent::MediaRenegotiation(renegotiation) => {
5031 timeline.record_sdp("remote offer", &renegotiation.sdp);
5032 let names = renegotiation
5033 .links
5034 .keys()
5035 .cloned()
5036 .collect::<Vec<_>>()
5037 .join(",");
5038 timeline.record(
5039 "renegotiation links",
5040 if names.is_empty() {
5041 "none".to_owned()
5042 } else {
5043 names
5044 },
5045 );
5046 }
5047 _ => {}
5048 }
5049 Ok(event)
5050}
5051
5052async fn apply_answer(
5053 peer: &PeerConnection,
5054 teams_answer: &str,
5055 signaled: &SignaledOffer,
5056 browser_offer: &str,
5057) -> Result<()> {
5058 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
5059 set_browser_answer(peer, &answer).await
5060}
5061
5062/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
5063async fn apply_hold_answer(
5064 peer: &PeerConnection,
5065 teams_answer: &str,
5066 signaled: &SignaledOffer,
5067 browser_offer: &str,
5068) -> Result<()> {
5069 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
5070 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
5071}
5072
5073async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
5074 let description = parse_sdp(answer, SdpType::Answer)?;
5075 peer.set_remote_description(description)
5076 .await
5077 .map_err(|error| Error::Webrtc(error.to_string()))
5078}
5079
5080/// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
5081fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
5082 let Some(directory) = &options.sdp_dump_dir else {
5083 return;
5084 };
5085 let masked: Vec<String> = sdp
5086 .lines()
5087 .map(|line| {
5088 for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] {
5089 if line.starts_with(prefix) {
5090 return format!("{prefix}<masked>");
5091 }
5092 }
5093 line.split(' ')
5094 .map(mask_address)
5095 .collect::<Vec<_>>()
5096 .join(" ")
5097 })
5098 .collect();
5099 let _ = std::fs::create_dir_all(directory);
5100 let _ = std::fs::write(directory.join(name), masked.join("\n"));
5101}
5102
5103fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {
5104 let Some(directory) = &options.sdp_dump_dir else {
5105 return;
5106 };
5107 let mut lines: Vec<String> = timeline
5108 .entries()
5109 .iter()
5110 .map(|entry| {
5111 format!(
5112 "{:>6} ms {} {}",
5113 entry.elapsed_ms, entry.label, entry.detail
5114 )
5115 })
5116 .collect();
5117 lines.push(match failure {
5118 Some(error) => format!("failed: {error}"),
5119 None => "ended without error".to_owned(),
5120 });
5121 let _ = std::fs::create_dir_all(directory);
5122 let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));
5123}
5124
5125fn mask_address(token: &str) -> String {
5126 let dotted_quad =
5127 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
5128 let colon_address =
5129 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
5130 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
5131 || colon_address
5132 {
5133 "<addr>".to_owned()
5134 } else {
5135 token.to_owned()
5136 }
5137}
5138
5139async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) {
5140 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
5141 while let Some(frame) = stream.next().await {
5142 let mut recording = recording.lock().await;
5143 recording.samples.extend_from_slice(&frame.data);
5144 recording.current_second.extend_from_slice(&frame.data);
5145 if recording.current_second.len() >= SAMPLE_RATE as usize {
5146 let second: Vec<i16> = std::mem::take(&mut recording.current_second);
5147 let summary = (rms(&second), tone_ratio(&second, tone_hz));
5148 recording.per_second.push(summary);
5149 }
5150 }
5151}
5152
5153async fn poll_broker(
5154 signaling: Arc<Signaling>,
5155 conversation: Conversation,
5156 running: Arc<AtomicBool>,
5157) {
5158 let Ok(first) = conversation.link("subscribe") else {
5159 return;
5160 };
5161 let mut url = first.to_owned();
5162 while running.load(Ordering::SeqCst) {
5163 match signaling.poll_broker(&url).await {
5164 Ok(Some(next)) => url = next,
5165 Ok(None) => tokio::time::sleep(BROKER_IDLE_WAIT).await,
5166 Err(_) => tokio::time::sleep(BROKER_RETRY_WAIT).await,
5167 }
5168 }
5169}
5170
5171#[derive(Debug, Default)]
5172struct StatsSnapshot {
5173 inbound_packets: u64,
5174 inbound_bytes: u64,
5175 outbound_packets: u64,
5176 outbound_bytes: u64,
5177 source_levels: Vec<String>,
5178 video_senders: Vec<String>,
5179 audio_level: f64,
5180 local_level: f64,
5181 echo_return_loss_enhancement: f64,
5182 video: VideoReport,
5183 camera_target_bitrate: u64,
5184 share_inbound_packets: u64,
5185 share_outbound_packets: u64,
5186 share_receive: Option<ShareReceive>,
5187 dtls_state: String,
5188 tls_version: String,
5189 dtls_cipher: String,
5190 srtp_cipher: String,
5191 selected_pair: Option<String>,
5192 health: HealthCounters,
5193 transport: TransportDetails,
5194}
5195
5196#[derive(Debug, Default)]
5197struct ShareReceive {
5198 frames_decoded: u32,
5199 key_frames_decoded: u32,
5200 width: u32,
5201 height: u32,
5202 frames_per_second: f64,
5203 pli_count: u32,
5204 fir_count: u32,
5205 freeze_count: u32,
5206 qp_sum: u64,
5207 bytes_received: u64,
5208}
5209
5210impl ShareReceive {
5211 fn average_qp(&self) -> u64 {
5212 self.qp_sum
5213 .checked_div(u64::from(self.frames_decoded))
5214 .unwrap_or(0)
5215 }
5216
5217 fn summary(&self) -> String {
5218 format!(
5219 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
5220 self.frames_decoded,
5221 self.key_frames_decoded,
5222 self.width,
5223 self.height,
5224 self.frames_per_second,
5225 self.average_qp(),
5226 self.bytes_received,
5227 self.pli_count,
5228 self.fir_count,
5229 self.freeze_count
5230 )
5231 }
5232}
5233
5234async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSnapshot {
5235 let Ok(stats) = peer.get_stats().await else {
5236 return StatsSnapshot::default();
5237 };
5238 let mut snapshot = StatsSnapshot::default();
5239 (snapshot.health, snapshot.transport) = health_from_stats(&stats);
5240 let mut selected_pair_id = None;
5241 for entry in &stats {
5242 match entry {
5243 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => {
5244 snapshot.inbound_packets += inbound.received.packets_received;
5245 snapshot.inbound_bytes += inbound.inbound.bytes_received;
5246 snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level);
5247 }
5248 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
5249 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
5250 snapshot.source_levels.push(format!(
5251 "{}={:.3}",
5252 source.source.track_identifier, source.audio.audio_level
5253 ));
5254 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
5255 }
5256 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
5257 snapshot.outbound_packets += outbound.sent.packets_sent;
5258 snapshot.outbound_bytes += outbound.sent.bytes_sent;
5259 }
5260 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
5261 snapshot.video.inbound_packets += inbound.received.packets_received;
5262 if share_mids.contains(&inbound.inbound.mid) {
5263 snapshot.share_inbound_packets += inbound.received.packets_received;
5264 snapshot.share_receive = Some(ShareReceive {
5265 frames_decoded: inbound.inbound.frames_decoded,
5266 key_frames_decoded: inbound.inbound.key_frames_decoded,
5267 width: inbound.inbound.frame_width,
5268 height: inbound.inbound.frame_height,
5269 frames_per_second: inbound.inbound.frames_per_second,
5270 pli_count: inbound.inbound.pli_count,
5271 fir_count: inbound.inbound.fir_count,
5272 freeze_count: inbound.inbound.freeze_count,
5273 qp_sum: inbound.inbound.qp_sum,
5274 bytes_received: inbound.inbound.bytes_received,
5275 });
5276 }
5277 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
5278 snapshot.video.inbound_width = snapshot
5279 .video
5280 .inbound_width
5281 .max(inbound.inbound.frame_width);
5282 snapshot.video.inbound_height = snapshot
5283 .video
5284 .inbound_height
5285 .max(inbound.inbound.frame_height);
5286 }
5287 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
5288 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
5289 snapshot.video.remote_round_trip_ms = snapshot
5290 .video
5291 .remote_round_trip_ms
5292 .max(remote.remote_inbound.round_trip_time * 1000.0);
5293 }
5294 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
5295 snapshot.video.outbound_packets += outbound.sent.packets_sent;
5296 if share_mids.contains(&outbound.outbound.mid) {
5297 snapshot.share_outbound_packets += outbound.sent.packets_sent;
5298 } else if outbound.outbound.active {
5299 snapshot.camera_target_bitrate = snapshot
5300 .camera_target_bitrate
5301 .max(outbound.outbound.target_bitrate as u64);
5302 }
5303 snapshot.video.outbound_frames_encoded +=
5304 u64::from(outbound.outbound.frames_encoded);
5305 snapshot.video_senders.push(format!(
5306 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
5307 outbound.outbound.mid,
5308 outbound.sent.packets_sent,
5309 outbound.outbound.key_frames_encoded,
5310 outbound.outbound.pli_count,
5311 outbound.outbound.fir_count,
5312 outbound.outbound.nack_count,
5313 outbound.outbound.target_bitrate / 1000.0,
5314 outbound.outbound.quality_limitation_reason,
5315 outbound.outbound.active
5316 ));
5317 snapshot.video.outbound_width = snapshot
5318 .video
5319 .outbound_width
5320 .max(outbound.outbound.frame_width);
5321 snapshot.video.outbound_height = snapshot
5322 .video
5323 .outbound_height
5324 .max(outbound.outbound.frame_height);
5325 }
5326 RtcStats::Transport(transport) => {
5327 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
5328 snapshot.tls_version = transport.transport.tls_version.clone();
5329 snapshot.dtls_cipher = transport.transport.dtls_cipher.clone();
5330 snapshot.srtp_cipher = transport.transport.srtp_cipher.clone();
5331 if !transport.transport.selected_candidate_pair_id.is_empty() {
5332 selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone());
5333 }
5334 }
5335 _ => {}
5336 }
5337 }
5338 if let Some(pair_id) = selected_pair_id {
5339 let pair = stats.iter().find_map(|entry| match entry {
5340 RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair),
5341 _ => None,
5342 });
5343 if let Some(pair) = pair {
5344 let describe = |candidate_id: &str| {
5345 stats
5346 .iter()
5347 .find_map(|entry| match entry {
5348 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
5349 Some(&local.local_candidate)
5350 }
5351 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
5352 Some(&remote.remote_candidate)
5353 }
5354 _ => None,
5355 })
5356 .map(|candidate| {
5357 let kind = candidate
5358 .candidate_type
5359 .map(|kind| format!("{kind:?}"))
5360 .unwrap_or_default();
5361 let relay = candidate
5362 .relay_protocol
5363 .map(|relay| format!(" via {relay:?}"))
5364 .unwrap_or_default();
5365 format!("{kind}/{}{relay}", candidate.protocol)
5366 })
5367 .unwrap_or_else(|| "?".into())
5368 };
5369 snapshot.selected_pair = Some(format!(
5370 "local {} <-> remote {}",
5371 describe(&pair.candidate_pair.local_candidate_id),
5372 describe(&pair.candidate_pair.remote_candidate_id)
5373 ));
5374 }
5375 }
5376 snapshot
5377}
5378
5379#[cfg(test)]
3007#[cfg(test)]
5380mod tests {
3008mod tests {
5381 #[test]
3009 #[test]
@@ -5552,7 +3180,7 @@ mod tests {
5552 .unwrap();
3180 .unwrap();
5553 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3181 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
5554 let track = factory.create_audio_track("microphone", source);
3182 let track = factory.create_audio_track("microphone", source);
5555 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3183 let offer = include_str!("../../tests/fixtures/teams_p2p_offer.sdp");
5556 let answered = answer_offer(
3184 let answered = answer_offer(
5557 &peer,
3185 &peer,
5558 Some(&track),
3186 Some(&track),
crates/calling/src/call/peer_sdp.rs added +812 −0
@@ -0,0 +1,812 @@
1 use super::*;
2
3 pub(super) enum PeerEvent {
4 Ice(IceConnectionState),
5 Connection(PeerConnectionState),
6 Track(RtcAudioTrack),
7 VideoTrack { mid: String, track: RtcVideoTrack },
8 Data(Vec<u8>),
9 }
10
11 pub(super) struct PeerSession {
12 pub(super) peer: PeerConnection,
13 pub(super) events: mpsc::UnboundedReceiver<PeerEvent>,
14 pub(super) _data_channel: Option<DataChannel>,
15 pub(super) gathered: Gathered,
16 }
17
18 #[derive(Clone, Default)]
19 pub(super) struct Gathered {
20 pub(super) candidates: Arc<std::sync::Mutex<Vec<String>>>,
21 pub(super) complete: Arc<AtomicBool>,
22 pub(super) relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
23 pub(super) waited_ms: Arc<AtomicU64>,
24 }
25
26 /// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
27 pub(super) fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
28 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
29 }
30
31 impl Gathered {
32 pub(super) fn settled(&self) -> bool {
33 let since_udp_relay = self
34 .relay_seen_at
35 .lock()
36 .expect("relay time lock")
37 .map(|at| at.elapsed());
38 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
39 }
40
41 pub(super) async fn candidates(&self) -> Vec<String> {
42 let waited = Instant::now();
43 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
44 tokio::time::sleep(GATHERING_POLL).await;
45 }
46 self.complete.store(true, Ordering::SeqCst);
47 self.waited_ms
48 .store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
49 self.candidates.lock().expect("candidates lock").clone()
50 }
51
52 pub(super) fn summary(&self) -> String {
53 let count = self.candidates.lock().expect("candidates lock").len();
54 format!(
55 "{count} candidate(s) after {} ms",
56 self.waited_ms.load(Ordering::SeqCst)
57 )
58 }
59 }
60
61 pub(super) async fn direct_sdp(
62 teams_sdp: &str,
63 gathered: Option<&Gathered>,
64 kind: SdpKind,
65 ) -> Result<String> {
66 match gathered {
67 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
68 None => Ok(teams_sdp.to_owned()),
69 }
70 }
71
72 pub(super) struct OfferedMedia {
73 pub(super) browser_offer: String,
74 pub(super) signaled: SignaledOffer,
75 pub(super) video: VideoLines,
76 pub(super) plan: OfferPlan,
77 pub(super) modalities: Vec<String>,
78 }
79
80 #[derive(Clone, Copy)]
81 pub(super) enum AnswerVideo<'a> {
82 Reject,
83 Receive,
84 Send(&'a RtcVideoTrack),
85 }
86
87 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
88 pub(super) enum Change {
89 Hold(bool),
90 Camera(bool),
91 Share(bool),
92 }
93
94 pub(super) struct SamePeerOffer {
95 pub(super) browser_offer: String,
96 pub(super) signaled: SignaledOffer,
97 pub(super) change: Change,
98 pub(super) reply_tags: Vec<String>,
99 }
100
101 pub(super) struct GlareResend {
102 pub(super) change: Change,
103 pub(super) reply_tags: Vec<String>,
104 pub(super) at: Instant,
105 }
106
107 /// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced.
108 pub(super) fn replace_leg_media_links(
109 media_links: &mut BTreeMap<String, String>,
110 leg_links: &BTreeMap<String, String>,
111 ) {
112 media_links.extend(leg_links.clone());
113 }
114
115 pub(super) fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
116 match callback_tag(callback_path) {
117 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
118 _ => true,
119 }
120 }
121
122 pub(super) fn open_peer(
123 factory: &PeerConnectionFactory,
124 grant: &RelayGrant,
125 relay_host: &str,
126 with_data_channel: bool,
127 ) -> Result<PeerSession> {
128 let mut configuration = RtcConfiguration::default();
129 configuration.ice_servers = vec![grant.ice_server(relay_host)];
130 let peer = factory
131 .create_peer_connection(configuration)
132 .map_err(|error| Error::Webrtc(error.to_string()))?;
133 let (sender, events) = mpsc::unbounded_channel();
134 let data_channel = with_data_channel
135 .then(|| open_data_channel(&peer, sender.clone()))
136 .transpose()?;
137 let gathered = Gathered::default();
138 let candidate_sink = gathered.candidates.clone();
139 let relay_seen_at = gathered.relay_seen_at.clone();
140 peer.on_ice_candidate(Some(Box::new(move |candidate| {
141 if candidate.sdp_mline_index() == 0 {
142 let text = candidate.candidate();
143 if is_udp_relay(&text) {
144 relay_seen_at
145 .lock()
146 .expect("relay time lock")
147 .get_or_insert_with(Instant::now);
148 }
149 candidate_sink.lock().expect("candidates lock").push(text);
150 }
151 })));
152 let gathering_done = gathered.complete.clone();
153 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
154 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
155 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
156 IceGatheringState::New => {}
157 })));
158 let ice_sender = sender.clone();
159 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
160 let _ = ice_sender.send(PeerEvent::Ice(state));
161 })));
162 let connection_sender = sender.clone();
163 peer.on_connection_state_change(Some(Box::new(move |state| {
164 let _ = connection_sender.send(PeerEvent::Connection(state));
165 })));
166 peer.on_track(Some(Box::new(move |event| match event.track {
167 MediaStreamTrack::Audio(track) => {
168 let _ = sender.send(PeerEvent::Track(track));
169 }
170 MediaStreamTrack::Video(track) => {
171 let mid = event.transceiver.mid().unwrap_or_default();
172 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
173 }
174 })));
175 Ok(PeerSession {
176 peer,
177 events,
178 _data_channel: data_channel,
179 gathered,
180 })
181 }
182
183 pub(super) fn open_data_channel(
184 peer: &PeerConnection,
185 sender: mpsc::UnboundedSender<PeerEvent>,
186 ) -> Result<DataChannel> {
187 let channel = peer
188 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
189 .map_err(|error| Error::Webrtc(error.to_string()))?;
190 channel.on_message(Some(Box::new(move |buffer| {
191 let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));
192 })));
193 Ok(channel)
194 }
195
196 pub(super) fn one_to_one_directions<'a>(
197 camera: bool,
198 share: bool,
199 camera_mid: &'a str,
200 share_mid: Option<&'a str>,
201 remote_shares: bool,
202 ) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
203 move |line| match line.kind {
204 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
205 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
206 (true, true) => "sendrecv",
207 (true, false) => "sendonly",
208 (false, true) => "recvonly",
209 (false, false) => INACTIVE,
210 }),
211 _ => None,
212 }
213 }
214
215 pub(super) fn share_mid_in(offer_text: &str) -> Option<String> {
216 let mut mid = None;
217 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
218 if line.starts_with("m=") {
219 mid = None;
220 } else if let Some(value) = line.strip_prefix("a=mid:") {
221 mid = Some(value.to_owned());
222 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
223 return mid;
224 }
225 }
226 None
227 }
228
229 #[allow(clippy::too_many_arguments)]
230 pub(super) fn directions_for(
231 layout: Layout,
232 hold: bool,
233 camera: bool,
234 share: bool,
235 camera_mid: &str,
236 share_mid: Option<&str>,
237 remote_shares: bool,
238 text: &str,
239 ) -> String {
240 match (hold, layout) {
241 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
242 (false, Layout::OneToOne) => rewrite_directions(
243 text,
244 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
245 ),
246 (false, Layout::Conference) => text.to_owned(),
247 }
248 }
249
250 pub(super) async fn create_offer(
251 peer: &PeerConnection,
252 factory: &PeerConnectionFactory,
253 track: &RtcAudioTrack,
254 layout: Layout,
255 gathered: Option<&Gathered>,
256 ) -> Result<OfferedMedia> {
257 let transceiver_init = RtpTransceiverInit {
258 direction: RtpTransceiverDirection::SendRecv,
259 stream_ids: vec![MIC_STREAM.into()],
260 send_encodings: Vec::new(),
261 };
262 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
263 .map_err(|error| Error::Webrtc(error.to_string()))?;
264 let (video, plan) = match layout {
265 Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),
266 Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),
267 };
268 let offer = peer
269 .create_offer(OfferOptions {
270 offer_to_receive_audio: true,
271 offer_to_receive_video: true,
272 ..OfferOptions::default()
273 })
274 .await
275 .map_err(|error| Error::Webrtc(error.to_string()))?;
276 let browser_offer = directions_for(
277 layout,
278 false,
279 false,
280 false,
281 CAMERA_MID,
282 Some(ONE_TO_ONE_SHARE_MID),
283 false,
284 &offer.to_string(),
285 );
286 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
287 peer.set_local_description(description)
288 .await
289 .map_err(|error| Error::Webrtc(error.to_string()))?;
290 let mut numbers = random_u32;
291 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
292 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
293 Ok(OfferedMedia {
294 browser_offer,
295 signaled,
296 video,
297 plan,
298 modalities: accepted_modalities(false),
299 })
300 }
301
302 pub(super) struct AnsweredMedia {
303 pub(super) remote: RemoteOffer,
304 pub(super) offer_sdp: String,
305 pub(super) answer_sdp: String,
306 pub(super) camera_mid: Option<String>,
307 pub(super) receiving_share_mid: Option<String>,
308 }
309
310 pub(super) fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
311 let main: Vec<_> = remote
312 .lines
313 .iter()
314 .filter(|line| line.role == LineRole::MainVideo)
315 .filter_map(|line| line.browser_mids.first().cloned())
316 .collect();
317 main.iter()
318 .find(|mid| {
319 matches!(
320 direction_of(&remote.browser_sdp, mid).as_deref(),
321 Some("sendrecv" | "recvonly")
322 )
323 })
324 .cloned()
325 .or_else(|| main.into_iter().next())
326 }
327
328 pub(super) fn share_mids(remote: &RemoteOffer) -> Vec<String> {
329 remote
330 .lines
331 .iter()
332 .filter(|line| line.role == LineRole::ScreenShare)
333 .flat_map(|line| line.browser_mids.iter().cloned())
334 .collect()
335 }
336
337 pub(super) fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> {
338 remote
339 .lines
340 .iter()
341 .find(|line| line.role == LineRole::ScreenShare)
342 .and_then(|line| line.browser_mids.last().cloned())
343 }
344
345 pub(super) async fn answer_offer(
346 peer: &PeerConnection,
347 track: Option<&RtcAudioTrack>,
348 teams_offer: &str,
349 video: AnswerVideo<'_>,
350 sending_share_mid: Option<String>,
351 camera_on: bool,
352 gathered: Option<&Gathered>,
353 ) -> Result<AnsweredMedia> {
354 answer_offer_with(
355 peer,
356 track,
357 teams_offer,
358 video,
359 sending_share_mid,
360 None,
361 camera_on,
362 gathered,
363 false,
364 false,
365 )
366 .await
367 }
368
369 #[allow(clippy::too_many_arguments)]
370 pub(super) async fn answer_offer_with(
371 peer: &PeerConnection,
372 track: Option<&RtcAudioTrack>,
373 teams_offer: &str,
374 video: AnswerVideo<'_>,
375 sending_share_mid: Option<String>,
376 share_track: Option<&RtcVideoTrack>,
377 camera_on: bool,
378 gathered: Option<&Gathered>,
379 keep_receive_slots: bool,
380 mixer: bool,
381 ) -> Result<AnsweredMedia> {
382 let remote = from_teams_offer(teams_offer)?;
383 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
384 peer.set_remote_description(description)
385 .await
386 .map_err(|error| {
387 let lines: Vec<String> = remote
388 .lines
389 .iter()
390 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
391 .collect();
392 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
393 })?;
394 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
395 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
396 Vec::new()
397 } else {
398 share_mids(&remote)
399 };
400 if !keep_receive_slots {
401 for transceiver in peer.transceivers() {
402 let is_video = matches!(
403 transceiver.receiver().track(),
404 Some(MediaStreamTrack::Video(_))
405 );
406 let unused = transceiver.mid().is_some_and(|mid| {
407 Some(&mid) != camera_mid.as_ref()
408 && !kept_share_mids.contains(&mid)
409 && Some(&mid) != sending_share_mid.as_ref()
410 });
411 if is_video && unused {
412 let _ = transceiver.stop();
413 }
414 }
415 }
416 if let Some(track) = track {
417 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
418 .map_err(|error| Error::Webrtc(error.to_string()))?;
419 }
420 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
421 if mixer {
422 // Keep camera sendrecv so a later set_track / updateMediaDescriptions
423 // can start sending without renegotiation. Do NOT force folded
424 // x-multi-stream share lines to sendrecv: Teams rejects that answer
425 // with SdpParsingFailure (301000); starting share upgrades the peer.
426 if let Some(mid) = camera_mid.as_deref()
427 && let Some(camera) = peer_transceiver(peer, mid)
428 {
429 let _ = camera.set_direction(RtpTransceiverDirection::SendRecv);
430 if let AnswerVideo::Send(track) = video {
431 let _ = camera
432 .sender()
433 .set_track(Some(MediaStreamTrack::Video(track.clone())));
434 }
435 }
436 if let Some(mid) = sending_share_mid.as_deref()
437 && let Some(share) = peer_transceiver(peer, mid)
438 {
439 let _ = share.set_direction(RtpTransceiverDirection::SendRecv);
440 if let Some(track) = share_track {
441 let _ = share
442 .sender()
443 .set_track(Some(MediaStreamTrack::Video(track.clone())));
444 }
445 }
446 } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
447 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
448 .map_err(|error| Error::Webrtc(error.to_string()))?;
449 }
450 let answer = peer
451 .create_answer(AnswerOptions::default())
452 .await
453 .map_err(|error| Error::Webrtc(error.to_string()))?;
454 let mut answer_text = answer.to_string();
455 for mid in kept_share_mids
456 .iter()
457 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
458 {
459 answer_text = stop_sending_on(&answer_text, mid);
460 }
461 if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
462 answer_text = stop_sending_on(&answer_text, mid);
463 }
464 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
465 .await
466 .map_err(|error| Error::Webrtc(error.to_string()))?;
467 if mixer
468 && !sends_camera
469 && let Some(mid) = camera_mid.as_deref()
470 && let Some(camera) = peer_transceiver(peer, mid)
471 {
472 let _ = LocalVideo::set_sender_active(&camera.sender(), false);
473 }
474 let receiving_share_mid = share_carrier_mid(&remote)
475 .into_iter()
476 .chain(kept_share_mids)
477 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
478 .find(|mid| {
479 matches!(
480 direction_of(&answer_text, mid).as_deref(),
481 Some("recvonly" | "sendrecv")
482 )
483 });
484 let mut numbers = random_u32;
485 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
486 Ok(AnsweredMedia {
487 remote,
488 offer_sdp: teams_offer.to_owned(),
489 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
490 camera_mid,
491 receiving_share_mid,
492 })
493 }
494
495 pub(super) fn new_media_leg_id() -> String {
496 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
497 }
498
499 pub(super) fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
500 peer.transceivers()
501 .into_iter()
502 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
503 }
504
505 #[allow(clippy::too_many_arguments)]
506 pub(super) async fn offer_same_peer(
507 peer: &PeerConnection,
508 gathered: &Gathered,
509 own_share_mid: Option<String>,
510 plan: &OfferPlan,
511 layout: Layout,
512 camera_mid: &str,
513 hold: bool,
514 camera: bool,
515 share: bool,
516 remote: &RemoteCall,
517 links: &CallbackLinks,
518 media_leg_id: &str,
519 media_links: &BTreeMap<String, String>,
520 negotiator: &mut MediaNegotiator,
521 ) -> Result<(String, SignaledOffer, Vec<String>)> {
522 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
523 let url = media_links
524 .get("mediaRenegotiation")
525 .cloned()
526 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
527 if !negotiator.begin_same_peer_offer() {
528 return Err(Error::Signaling(
529 "another media negotiation is running".into(),
530 ));
531 }
532 let offered = build_same_peer_offer(
533 peer,
534 plan,
535 layout,
536 hold,
537 camera,
538 share,
539 camera_mid,
540 own_share_mid,
541 direct.then_some(gathered),
542 )
543 .await;
544 let (text, signaled) = match offered {
545 Ok(offered) => offered,
546 Err(error) => {
547 negotiator.same_peer_offer_failed();
548 return Err(error);
549 }
550 };
551 let modalities = offer_modalities(
552 layout == Layout::OneToOne && camera && !hold,
553 share && !hold,
554 );
555 let body = renegotiation_body(
556 &remote.participant,
557 links,
558 &signaled.sdp,
559 media_leg_id,
560 &modalities,
561 false,
562 direct,
563 );
564 let reply_tags = offer_reply_tags(&body);
565 if let Err(error) = remote
566 .signaling
567 .post_json("POST mediaRenegotiation (same peer)", &url, body)
568 .await
569 {
570 negotiator.same_peer_offer_failed();
571 rollback_offer(peer).await;
572 return Err(error);
573 }
574 Ok((text, signaled, reply_tags))
575 }
576
577 #[allow(clippy::too_many_arguments)]
578 pub(super) async fn build_same_peer_offer(
579 peer: &PeerConnection,
580 plan: &OfferPlan,
581 layout: Layout,
582 hold: bool,
583 camera: bool,
584 share: bool,
585 camera_mid: &str,
586 own_share_mid: Option<String>,
587 gathered: Option<&Gathered>,
588 ) -> Result<(String, SignaledOffer)> {
589 let offer = peer
590 .create_offer(OfferOptions {
591 offer_to_receive_audio: true,
592 offer_to_receive_video: true,
593 ..OfferOptions::default()
594 })
595 .await
596 .map_err(|error| Error::Webrtc(error.to_string()))?;
597 let offer_text = offer.to_string();
598 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
599 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
600 peer.current_remote_description()
601 .and_then(|remote| direction_of(&remote.to_string(), mid))
602 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
603 });
604 let text = directions_for(
605 layout,
606 false,
607 camera,
608 share,
609 camera_mid,
610 share_mid.as_deref(),
611 remote_shares,
612 &offer_text,
613 );
614 let description = parse_sdp(&text, SdpType::Offer)?;
615 peer.set_local_description(description)
616 .await
617 .map_err(|error| Error::Webrtc(error.to_string()))?;
618 let mut numbers = random_u32;
619 let mut plan = plan.clone();
620 if let Some(mid) = share_mid
621 .as_ref()
622 .filter(|mid| !plan.screen_share_mids.contains(mid))
623 {
624 plan.screen_share_mids.push(mid.clone());
625 }
626 let mut signaled = to_teams_offer(
627 &directions_for(
628 layout,
629 hold,
630 camera,
631 share,
632 camera_mid,
633 share_mid.as_deref(),
634 remote_shares,
635 &text,
636 ),
637 &plan,
638 &mut numbers,
639 )?;
640 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
641 if gathered.is_some()
642 && let Some(role) = negotiated_setup(
643 peer.current_local_description()
644 .map(|local| local.to_string())
645 .as_deref(),
646 peer.current_remote_description()
647 .map(|remote| remote.to_string())
648 .as_deref(),
649 )
650 {
651 signaled.sdp = signaled
652 .sdp
653 .replace("a=setup:actpass", &format!("a=setup:{role}"));
654 }
655 Ok((text, signaled))
656 }
657
658 /// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
659 pub(super) fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
660 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
661 Ok(Ok(description)) => Ok(description),
662 Ok(Err(error)) => Err(Error::Sdp(format!(
663 "{kind:?} rejected: {}",
664 error.description
665 ))),
666 Err(_) => Err(Error::Sdp(format!(
667 "{kind:?} rejected, libwebrtc gave no readable reason"
668 ))),
669 }
670 }
671
672 pub(super) async fn rollback_offer(peer: &PeerConnection) {
673 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
674 let _ = peer.set_local_description(rollback).await;
675 }
676 }
677
678 pub(super) async fn rollback_remote_offer(peer: &PeerConnection) {
679 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
680 let _ = peer.set_remote_description(rollback).await;
681 }
682 }
683
684 pub(super) fn is_glare_rejection(body: &serde_json::Value) -> bool {
685 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
686 }
687
688 pub(super) fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
689 let links = &body["mediaNegotiation"]["links"];
690 ["mediaAnswer", "rejection"]
691 .iter()
692 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
693 .collect()
694 }
695
696 #[cfg(test)]
697 mod reply_tag_tests {
698 use super::*;
699
700 #[test]
701 fn answers_and_rejections_match_the_offer_by_tag() {
702 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
703 assert!(answers_offer(
704 "callAgent/c/aaaa1111/call/mediaAnswer/",
705 &tags
706 ));
707 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
708 assert!(!answers_offer(
709 "callAgent/c/cccc3333/call/mediaAnswer/",
710 &tags
711 ));
712 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
713 }
714
715 #[test]
716 fn an_offer_names_both_reply_tags() {
717 let body = serde_json::json!({"mediaNegotiation": {"links": {
718 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
719 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
720 assert_eq!(
721 offer_reply_tags(&body),
722 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
723 );
724 }
725 }
726
727 pub(super) async fn apply_answer(
728 peer: &PeerConnection,
729 teams_answer: &str,
730 signaled: &SignaledOffer,
731 browser_offer: &str,
732 ) -> Result<()> {
733 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
734 set_browser_answer(peer, &answer).await
735 }
736
737 /// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
738 pub(super) async fn apply_hold_answer(
739 peer: &PeerConnection,
740 teams_answer: &str,
741 signaled: &SignaledOffer,
742 browser_offer: &str,
743 ) -> Result<()> {
744 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
745 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
746 }
747
748 pub(super) async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
749 let description = parse_sdp(answer, SdpType::Answer)?;
750 peer.set_remote_description(description)
751 .await
752 .map_err(|error| Error::Webrtc(error.to_string()))
753 }
754
755 /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
756 pub(super) fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
757 let Some(directory) = &options.sdp_dump_dir else {
758 return;
759 };
760 let masked: Vec<String> = sdp
761 .lines()
762 .map(|line| {
763 for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] {
764 if line.starts_with(prefix) {
765 return format!("{prefix}<masked>");
766 }
767 }
768 line.split(' ')
769 .map(mask_address)
770 .collect::<Vec<_>>()
771 .join(" ")
772 })
773 .collect();
774 let _ = std::fs::create_dir_all(directory);
775 let _ = std::fs::write(directory.join(name), masked.join("\n"));
776 }
777
778 pub(super) fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {
779 let Some(directory) = &options.sdp_dump_dir else {
780 return;
781 };
782 let mut lines: Vec<String> = timeline
783 .entries()
784 .iter()
785 .map(|entry| {
786 format!(
787 "{:>6} ms {} {}",
788 entry.elapsed_ms, entry.label, entry.detail
789 )
790 })
791 .collect();
792 lines.push(match failure {
793 Some(error) => format!("failed: {error}"),
794 None => "ended without error".to_owned(),
795 });
796 let _ = std::fs::create_dir_all(directory);
797 let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));
798 }
799
800 pub(super) fn mask_address(token: &str) -> String {
801 let dotted_quad =
802 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
803 let colon_address =
804 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
805 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
806 || colon_address
807 {
808 "<addr>".to_owned()
809 } else {
810 token.to_owned()
811 }
812 }
@@ -0,0 +1,812 @@
1use super::*;
2
3pub(super) enum PeerEvent {
4 Ice(IceConnectionState),
5 Connection(PeerConnectionState),
6 Track(RtcAudioTrack),
7 VideoTrack { mid: String, track: RtcVideoTrack },
8 Data(Vec<u8>),
9}
10
11pub(super) struct PeerSession {
12 pub(super) peer: PeerConnection,
13 pub(super) events: mpsc::UnboundedReceiver<PeerEvent>,
14 pub(super) _data_channel: Option<DataChannel>,
15 pub(super) gathered: Gathered,
16}
17
18#[derive(Clone, Default)]
19pub(super) struct Gathered {
20 pub(super) candidates: Arc<std::sync::Mutex<Vec<String>>>,
21 pub(super) complete: Arc<AtomicBool>,
22 pub(super) relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>,
23 pub(super) waited_ms: Arc<AtomicU64>,
24}
25
26/// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough.
27pub(super) fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool {
28 complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE)
29}
30
31impl Gathered {
32 pub(super) fn settled(&self) -> bool {
33 let since_udp_relay = self
34 .relay_seen_at
35 .lock()
36 .expect("relay time lock")
37 .map(|at| at.elapsed());
38 gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay)
39 }
40
41 pub(super) async fn candidates(&self) -> Vec<String> {
42 let waited = Instant::now();
43 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
44 tokio::time::sleep(GATHERING_POLL).await;
45 }
46 self.complete.store(true, Ordering::SeqCst);
47 self.waited_ms
48 .store(waited.elapsed().as_millis() as u64, Ordering::SeqCst);
49 self.candidates.lock().expect("candidates lock").clone()
50 }
51
52 pub(super) fn summary(&self) -> String {
53 let count = self.candidates.lock().expect("candidates lock").len();
54 format!(
55 "{count} candidate(s) after {} ms",
56 self.waited_ms.load(Ordering::SeqCst)
57 )
58 }
59}
60
61pub(super) async fn direct_sdp(
62 teams_sdp: &str,
63 gathered: Option<&Gathered>,
64 kind: SdpKind,
65) -> Result<String> {
66 match gathered {
67 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
68 None => Ok(teams_sdp.to_owned()),
69 }
70}
71
72pub(super) struct OfferedMedia {
73 pub(super) browser_offer: String,
74 pub(super) signaled: SignaledOffer,
75 pub(super) video: VideoLines,
76 pub(super) plan: OfferPlan,
77 pub(super) modalities: Vec<String>,
78}
79
80#[derive(Clone, Copy)]
81pub(super) enum AnswerVideo<'a> {
82 Reject,
83 Receive,
84 Send(&'a RtcVideoTrack),
85}
86
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub(super) enum Change {
89 Hold(bool),
90 Camera(bool),
91 Share(bool),
92}
93
94pub(super) struct SamePeerOffer {
95 pub(super) browser_offer: String,
96 pub(super) signaled: SignaledOffer,
97 pub(super) change: Change,
98 pub(super) reply_tags: Vec<String>,
99}
100
101pub(super) struct GlareResend {
102 pub(super) change: Change,
103 pub(super) reply_tags: Vec<String>,
104 pub(super) at: Instant,
105}
106
107/// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced.
108pub(super) fn replace_leg_media_links(
109 media_links: &mut BTreeMap<String, String>,
110 leg_links: &BTreeMap<String, String>,
111) {
112 media_links.extend(leg_links.clone());
113}
114
115pub(super) fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
116 match callback_tag(callback_path) {
117 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
118 _ => true,
119 }
120}
121
122pub(super) fn open_peer(
123 factory: &PeerConnectionFactory,
124 grant: &RelayGrant,
125 relay_host: &str,
126 with_data_channel: bool,
127) -> Result<PeerSession> {
128 let mut configuration = RtcConfiguration::default();
129 configuration.ice_servers = vec![grant.ice_server(relay_host)];
130 let peer = factory
131 .create_peer_connection(configuration)
132 .map_err(|error| Error::Webrtc(error.to_string()))?;
133 let (sender, events) = mpsc::unbounded_channel();
134 let data_channel = with_data_channel
135 .then(|| open_data_channel(&peer, sender.clone()))
136 .transpose()?;
137 let gathered = Gathered::default();
138 let candidate_sink = gathered.candidates.clone();
139 let relay_seen_at = gathered.relay_seen_at.clone();
140 peer.on_ice_candidate(Some(Box::new(move |candidate| {
141 if candidate.sdp_mline_index() == 0 {
142 let text = candidate.candidate();
143 if is_udp_relay(&text) {
144 relay_seen_at
145 .lock()
146 .expect("relay time lock")
147 .get_or_insert_with(Instant::now);
148 }
149 candidate_sink.lock().expect("candidates lock").push(text);
150 }
151 })));
152 let gathering_done = gathered.complete.clone();
153 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
154 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
155 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
156 IceGatheringState::New => {}
157 })));
158 let ice_sender = sender.clone();
159 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
160 let _ = ice_sender.send(PeerEvent::Ice(state));
161 })));
162 let connection_sender = sender.clone();
163 peer.on_connection_state_change(Some(Box::new(move |state| {
164 let _ = connection_sender.send(PeerEvent::Connection(state));
165 })));
166 peer.on_track(Some(Box::new(move |event| match event.track {
167 MediaStreamTrack::Audio(track) => {
168 let _ = sender.send(PeerEvent::Track(track));
169 }
170 MediaStreamTrack::Video(track) => {
171 let mid = event.transceiver.mid().unwrap_or_default();
172 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
173 }
174 })));
175 Ok(PeerSession {
176 peer,
177 events,
178 _data_channel: data_channel,
179 gathered,
180 })
181}
182
183pub(super) fn open_data_channel(
184 peer: &PeerConnection,
185 sender: mpsc::UnboundedSender<PeerEvent>,
186) -> Result<DataChannel> {
187 let channel = peer
188 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
189 .map_err(|error| Error::Webrtc(error.to_string()))?;
190 channel.on_message(Some(Box::new(move |buffer| {
191 let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));
192 })));
193 Ok(channel)
194}
195
196pub(super) fn one_to_one_directions<'a>(
197 camera: bool,
198 share: bool,
199 camera_mid: &'a str,
200 share_mid: Option<&'a str>,
201 remote_shares: bool,
202) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
203 move |line| match line.kind {
204 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
205 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
206 (true, true) => "sendrecv",
207 (true, false) => "sendonly",
208 (false, true) => "recvonly",
209 (false, false) => INACTIVE,
210 }),
211 _ => None,
212 }
213}
214
215pub(super) fn share_mid_in(offer_text: &str) -> Option<String> {
216 let mut mid = None;
217 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
218 if line.starts_with("m=") {
219 mid = None;
220 } else if let Some(value) = line.strip_prefix("a=mid:") {
221 mid = Some(value.to_owned());
222 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
223 return mid;
224 }
225 }
226 None
227}
228
229#[allow(clippy::too_many_arguments)]
230pub(super) fn directions_for(
231 layout: Layout,
232 hold: bool,
233 camera: bool,
234 share: bool,
235 camera_mid: &str,
236 share_mid: Option<&str>,
237 remote_shares: bool,
238 text: &str,
239) -> String {
240 match (hold, layout) {
241 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
242 (false, Layout::OneToOne) => rewrite_directions(
243 text,
244 one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares),
245 ),
246 (false, Layout::Conference) => text.to_owned(),
247 }
248}
249
250pub(super) async fn create_offer(
251 peer: &PeerConnection,
252 factory: &PeerConnectionFactory,
253 track: &RtcAudioTrack,
254 layout: Layout,
255 gathered: Option<&Gathered>,
256) -> Result<OfferedMedia> {
257 let transceiver_init = RtpTransceiverInit {
258 direction: RtpTransceiverDirection::SendRecv,
259 stream_ids: vec![MIC_STREAM.into()],
260 send_encodings: Vec::new(),
261 };
262 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
263 .map_err(|error| Error::Webrtc(error.to_string()))?;
264 let (video, plan) = match layout {
265 Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),
266 Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),
267 };
268 let offer = peer
269 .create_offer(OfferOptions {
270 offer_to_receive_audio: true,
271 offer_to_receive_video: true,
272 ..OfferOptions::default()
273 })
274 .await
275 .map_err(|error| Error::Webrtc(error.to_string()))?;
276 let browser_offer = directions_for(
277 layout,
278 false,
279 false,
280 false,
281 CAMERA_MID,
282 Some(ONE_TO_ONE_SHARE_MID),
283 false,
284 &offer.to_string(),
285 );
286 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
287 peer.set_local_description(description)
288 .await
289 .map_err(|error| Error::Webrtc(error.to_string()))?;
290 let mut numbers = random_u32;
291 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
292 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
293 Ok(OfferedMedia {
294 browser_offer,
295 signaled,
296 video,
297 plan,
298 modalities: accepted_modalities(false),
299 })
300}
301
302pub(super) struct AnsweredMedia {
303 pub(super) remote: RemoteOffer,
304 pub(super) offer_sdp: String,
305 pub(super) answer_sdp: String,
306 pub(super) camera_mid: Option<String>,
307 pub(super) receiving_share_mid: Option<String>,
308}
309
310pub(super) fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
311 let main: Vec<_> = remote
312 .lines
313 .iter()
314 .filter(|line| line.role == LineRole::MainVideo)
315 .filter_map(|line| line.browser_mids.first().cloned())
316 .collect();
317 main.iter()
318 .find(|mid| {
319 matches!(
320 direction_of(&remote.browser_sdp, mid).as_deref(),
321 Some("sendrecv" | "recvonly")
322 )
323 })
324 .cloned()
325 .or_else(|| main.into_iter().next())
326}
327
328pub(super) fn share_mids(remote: &RemoteOffer) -> Vec<String> {
329 remote
330 .lines
331 .iter()
332 .filter(|line| line.role == LineRole::ScreenShare)
333 .flat_map(|line| line.browser_mids.iter().cloned())
334 .collect()
335}
336
337pub(super) fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> {
338 remote
339 .lines
340 .iter()
341 .find(|line| line.role == LineRole::ScreenShare)
342 .and_then(|line| line.browser_mids.last().cloned())
343}
344
345pub(super) async fn answer_offer(
346 peer: &PeerConnection,
347 track: Option<&RtcAudioTrack>,
348 teams_offer: &str,
349 video: AnswerVideo<'_>,
350 sending_share_mid: Option<String>,
351 camera_on: bool,
352 gathered: Option<&Gathered>,
353) -> Result<AnsweredMedia> {
354 answer_offer_with(
355 peer,
356 track,
357 teams_offer,
358 video,
359 sending_share_mid,
360 None,
361 camera_on,
362 gathered,
363 false,
364 false,
365 )
366 .await
367}
368
369#[allow(clippy::too_many_arguments)]
370pub(super) async fn answer_offer_with(
371 peer: &PeerConnection,
372 track: Option<&RtcAudioTrack>,
373 teams_offer: &str,
374 video: AnswerVideo<'_>,
375 sending_share_mid: Option<String>,
376 share_track: Option<&RtcVideoTrack>,
377 camera_on: bool,
378 gathered: Option<&Gathered>,
379 keep_receive_slots: bool,
380 mixer: bool,
381) -> Result<AnsweredMedia> {
382 let remote = from_teams_offer(teams_offer)?;
383 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
384 peer.set_remote_description(description)
385 .await
386 .map_err(|error| {
387 let lines: Vec<String> = remote
388 .lines
389 .iter()
390 .map(|line| format!("{:?}{:?}", line.role, line.browser_mids))
391 .collect();
392 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
393 })?;
394 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
395 let kept_share_mids = if matches!(video, AnswerVideo::Reject) {
396 Vec::new()
397 } else {
398 share_mids(&remote)
399 };
400 if !keep_receive_slots {
401 for transceiver in peer.transceivers() {
402 let is_video = matches!(
403 transceiver.receiver().track(),
404 Some(MediaStreamTrack::Video(_))
405 );
406 let unused = transceiver.mid().is_some_and(|mid| {
407 Some(&mid) != camera_mid.as_ref()
408 && !kept_share_mids.contains(&mid)
409 && Some(&mid) != sending_share_mid.as_ref()
410 });
411 if is_video && unused {
412 let _ = transceiver.stop();
413 }
414 }
415 }
416 if let Some(track) = track {
417 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
418 .map_err(|error| Error::Webrtc(error.to_string()))?;
419 }
420 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
421 if mixer {
422 // Keep camera sendrecv so a later set_track / updateMediaDescriptions
423 // can start sending without renegotiation. Do NOT force folded
424 // x-multi-stream share lines to sendrecv: Teams rejects that answer
425 // with SdpParsingFailure (301000); starting share upgrades the peer.
426 if let Some(mid) = camera_mid.as_deref()
427 && let Some(camera) = peer_transceiver(peer, mid)
428 {
429 let _ = camera.set_direction(RtpTransceiverDirection::SendRecv);
430 if let AnswerVideo::Send(track) = video {
431 let _ = camera
432 .sender()
433 .set_track(Some(MediaStreamTrack::Video(track.clone())));
434 }
435 }
436 if let Some(mid) = sending_share_mid.as_deref()
437 && let Some(share) = peer_transceiver(peer, mid)
438 {
439 let _ = share.set_direction(RtpTransceiverDirection::SendRecv);
440 if let Some(track) = share_track {
441 let _ = share
442 .sender()
443 .set_track(Some(MediaStreamTrack::Video(track.clone())));
444 }
445 }
446 } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
447 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
448 .map_err(|error| Error::Webrtc(error.to_string()))?;
449 }
450 let answer = peer
451 .create_answer(AnswerOptions::default())
452 .await
453 .map_err(|error| Error::Webrtc(error.to_string()))?;
454 let mut answer_text = answer.to_string();
455 for mid in kept_share_mids
456 .iter()
457 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
458 {
459 answer_text = stop_sending_on(&answer_text, mid);
460 }
461 if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
462 answer_text = stop_sending_on(&answer_text, mid);
463 }
464 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
465 .await
466 .map_err(|error| Error::Webrtc(error.to_string()))?;
467 if mixer
468 && !sends_camera
469 && let Some(mid) = camera_mid.as_deref()
470 && let Some(camera) = peer_transceiver(peer, mid)
471 {
472 let _ = LocalVideo::set_sender_active(&camera.sender(), false);
473 }
474 let receiving_share_mid = share_carrier_mid(&remote)
475 .into_iter()
476 .chain(kept_share_mids)
477 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
478 .find(|mid| {
479 matches!(
480 direction_of(&answer_text, mid).as_deref(),
481 Some("recvonly" | "sendrecv")
482 )
483 });
484 let mut numbers = random_u32;
485 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
486 Ok(AnsweredMedia {
487 remote,
488 offer_sdp: teams_offer.to_owned(),
489 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
490 camera_mid,
491 receiving_share_mid,
492 })
493}
494
495pub(super) fn new_media_leg_id() -> String {
496 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
497}
498
499pub(super) fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
500 peer.transceivers()
501 .into_iter()
502 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
503}
504
505#[allow(clippy::too_many_arguments)]
506pub(super) async fn offer_same_peer(
507 peer: &PeerConnection,
508 gathered: &Gathered,
509 own_share_mid: Option<String>,
510 plan: &OfferPlan,
511 layout: Layout,
512 camera_mid: &str,
513 hold: bool,
514 camera: bool,
515 share: bool,
516 remote: &RemoteCall,
517 links: &CallbackLinks,
518 media_leg_id: &str,
519 media_links: &BTreeMap<String, String>,
520 negotiator: &mut MediaNegotiator,
521) -> Result<(String, SignaledOffer, Vec<String>)> {
522 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
523 let url = media_links
524 .get("mediaRenegotiation")
525 .cloned()
526 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
527 if !negotiator.begin_same_peer_offer() {
528 return Err(Error::Signaling(
529 "another media negotiation is running".into(),
530 ));
531 }
532 let offered = build_same_peer_offer(
533 peer,
534 plan,
535 layout,
536 hold,
537 camera,
538 share,
539 camera_mid,
540 own_share_mid,
541 direct.then_some(gathered),
542 )
543 .await;
544 let (text, signaled) = match offered {
545 Ok(offered) => offered,
546 Err(error) => {
547 negotiator.same_peer_offer_failed();
548 return Err(error);
549 }
550 };
551 let modalities = offer_modalities(
552 layout == Layout::OneToOne && camera && !hold,
553 share && !hold,
554 );
555 let body = renegotiation_body(
556 &remote.participant,
557 links,
558 &signaled.sdp,
559 media_leg_id,
560 &modalities,
561 false,
562 direct,
563 );
564 let reply_tags = offer_reply_tags(&body);
565 if let Err(error) = remote
566 .signaling
567 .post_json("POST mediaRenegotiation (same peer)", &url, body)
568 .await
569 {
570 negotiator.same_peer_offer_failed();
571 rollback_offer(peer).await;
572 return Err(error);
573 }
574 Ok((text, signaled, reply_tags))
575}
576
577#[allow(clippy::too_many_arguments)]
578pub(super) async fn build_same_peer_offer(
579 peer: &PeerConnection,
580 plan: &OfferPlan,
581 layout: Layout,
582 hold: bool,
583 camera: bool,
584 share: bool,
585 camera_mid: &str,
586 own_share_mid: Option<String>,
587 gathered: Option<&Gathered>,
588) -> Result<(String, SignaledOffer)> {
589 let offer = peer
590 .create_offer(OfferOptions {
591 offer_to_receive_audio: true,
592 offer_to_receive_video: true,
593 ..OfferOptions::default()
594 })
595 .await
596 .map_err(|error| Error::Webrtc(error.to_string()))?;
597 let offer_text = offer.to_string();
598 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
599 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
600 peer.current_remote_description()
601 .and_then(|remote| direction_of(&remote.to_string(), mid))
602 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
603 });
604 let text = directions_for(
605 layout,
606 false,
607 camera,
608 share,
609 camera_mid,
610 share_mid.as_deref(),
611 remote_shares,
612 &offer_text,
613 );
614 let description = parse_sdp(&text, SdpType::Offer)?;
615 peer.set_local_description(description)
616 .await
617 .map_err(|error| Error::Webrtc(error.to_string()))?;
618 let mut numbers = random_u32;
619 let mut plan = plan.clone();
620 if let Some(mid) = share_mid
621 .as_ref()
622 .filter(|mid| !plan.screen_share_mids.contains(mid))
623 {
624 plan.screen_share_mids.push(mid.clone());
625 }
626 let mut signaled = to_teams_offer(
627 &directions_for(
628 layout,
629 hold,
630 camera,
631 share,
632 camera_mid,
633 share_mid.as_deref(),
634 remote_shares,
635 &text,
636 ),
637 &plan,
638 &mut numbers,
639 )?;
640 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
641 if gathered.is_some()
642 && let Some(role) = negotiated_setup(
643 peer.current_local_description()
644 .map(|local| local.to_string())
645 .as_deref(),
646 peer.current_remote_description()
647 .map(|remote| remote.to_string())
648 .as_deref(),
649 )
650 {
651 signaled.sdp = signaled
652 .sdp
653 .replace("a=setup:actpass", &format!("a=setup:{role}"));
654 }
655 Ok((text, signaled))
656}
657
658/// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
659pub(super) fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
660 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
661 Ok(Ok(description)) => Ok(description),
662 Ok(Err(error)) => Err(Error::Sdp(format!(
663 "{kind:?} rejected: {}",
664 error.description
665 ))),
666 Err(_) => Err(Error::Sdp(format!(
667 "{kind:?} rejected, libwebrtc gave no readable reason"
668 ))),
669 }
670}
671
672pub(super) async fn rollback_offer(peer: &PeerConnection) {
673 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
674 let _ = peer.set_local_description(rollback).await;
675 }
676}
677
678pub(super) async fn rollback_remote_offer(peer: &PeerConnection) {
679 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
680 let _ = peer.set_remote_description(rollback).await;
681 }
682}
683
684pub(super) fn is_glare_rejection(body: &serde_json::Value) -> bool {
685 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
686}
687
688pub(super) fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
689 let links = &body["mediaNegotiation"]["links"];
690 ["mediaAnswer", "rejection"]
691 .iter()
692 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
693 .collect()
694}
695
696#[cfg(test)]
697mod reply_tag_tests {
698 use super::*;
699
700 #[test]
701 fn answers_and_rejections_match_the_offer_by_tag() {
702 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
703 assert!(answers_offer(
704 "callAgent/c/aaaa1111/call/mediaAnswer/",
705 &tags
706 ));
707 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
708 assert!(!answers_offer(
709 "callAgent/c/cccc3333/call/mediaAnswer/",
710 &tags
711 ));
712 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
713 }
714
715 #[test]
716 fn an_offer_names_both_reply_tags() {
717 let body = serde_json::json!({"mediaNegotiation": {"links": {
718 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
719 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
720 assert_eq!(
721 offer_reply_tags(&body),
722 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
723 );
724 }
725}
726
727pub(super) async fn apply_answer(
728 peer: &PeerConnection,
729 teams_answer: &str,
730 signaled: &SignaledOffer,
731 browser_offer: &str,
732) -> Result<()> {
733 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
734 set_browser_answer(peer, &answer).await
735}
736
737/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
738pub(super) async fn apply_hold_answer(
739 peer: &PeerConnection,
740 teams_answer: &str,
741 signaled: &SignaledOffer,
742 browser_offer: &str,
743) -> Result<()> {
744 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
745 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
746}
747
748pub(super) async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
749 let description = parse_sdp(answer, SdpType::Answer)?;
750 peer.set_remote_description(description)
751 .await
752 .map_err(|error| Error::Webrtc(error.to_string()))
753}
754
755/// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
756pub(super) fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
757 let Some(directory) = &options.sdp_dump_dir else {
758 return;
759 };
760 let masked: Vec<String> = sdp
761 .lines()
762 .map(|line| {
763 for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] {
764 if line.starts_with(prefix) {
765 return format!("{prefix}<masked>");
766 }
767 }
768 line.split(' ')
769 .map(mask_address)
770 .collect::<Vec<_>>()
771 .join(" ")
772 })
773 .collect();
774 let _ = std::fs::create_dir_all(directory);
775 let _ = std::fs::write(directory.join(name), masked.join("\n"));
776}
777
778pub(super) fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {
779 let Some(directory) = &options.sdp_dump_dir else {
780 return;
781 };
782 let mut lines: Vec<String> = timeline
783 .entries()
784 .iter()
785 .map(|entry| {
786 format!(
787 "{:>6} ms {} {}",
788 entry.elapsed_ms, entry.label, entry.detail
789 )
790 })
791 .collect();
792 lines.push(match failure {
793 Some(error) => format!("failed: {error}"),
794 None => "ended without error".to_owned(),
795 });
796 let _ = std::fs::create_dir_all(directory);
797 let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));
798}
799
800pub(super) fn mask_address(token: &str) -> String {
801 let dotted_quad =
802 token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
803 let colon_address =
804 token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
805 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1")
806 || colon_address
807 {
808 "<addr>".to_owned()
809 } else {
810 token.to_owned()
811 }
812}
crates/calling/src/call/stats.rs added +209 −0
@@ -0,0 +1,209 @@
1 use super::*;
2
3 #[derive(Debug, Default)]
4 pub(super) struct StatsSnapshot {
5 pub(super) inbound_packets: u64,
6 pub(super) inbound_bytes: u64,
7 pub(super) outbound_packets: u64,
8 pub(super) outbound_bytes: u64,
9 pub(super) source_levels: Vec<String>,
10 pub(super) video_senders: Vec<String>,
11 pub(super) audio_level: f64,
12 pub(super) local_level: f64,
13 pub(super) echo_return_loss_enhancement: f64,
14 pub(super) video: VideoReport,
15 pub(super) camera_target_bitrate: u64,
16 pub(super) share_inbound_packets: u64,
17 pub(super) share_outbound_packets: u64,
18 pub(super) share_receive: Option<ShareReceive>,
19 pub(super) dtls_state: String,
20 pub(super) tls_version: String,
21 pub(super) dtls_cipher: String,
22 pub(super) srtp_cipher: String,
23 pub(super) selected_pair: Option<String>,
24 pub(super) health: HealthCounters,
25 pub(super) transport: TransportDetails,
26 }
27
28 #[derive(Debug, Default)]
29 pub(super) struct ShareReceive {
30 pub(super) frames_decoded: u32,
31 pub(super) key_frames_decoded: u32,
32 pub(super) width: u32,
33 pub(super) height: u32,
34 pub(super) frames_per_second: f64,
35 pub(super) pli_count: u32,
36 pub(super) fir_count: u32,
37 pub(super) freeze_count: u32,
38 pub(super) qp_sum: u64,
39 pub(super) bytes_received: u64,
40 }
41
42 impl ShareReceive {
43 pub(super) fn average_qp(&self) -> u64 {
44 self.qp_sum
45 .checked_div(u64::from(self.frames_decoded))
46 .unwrap_or(0)
47 }
48
49 pub(super) fn summary(&self) -> String {
50 format!(
51 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
52 self.frames_decoded,
53 self.key_frames_decoded,
54 self.width,
55 self.height,
56 self.frames_per_second,
57 self.average_qp(),
58 self.bytes_received,
59 self.pli_count,
60 self.fir_count,
61 self.freeze_count
62 )
63 }
64 }
65
66 pub(super) async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSnapshot {
67 let Ok(stats) = peer.get_stats().await else {
68 return StatsSnapshot::default();
69 };
70 let mut snapshot = StatsSnapshot::default();
71 (snapshot.health, snapshot.transport) = health_from_stats(&stats);
72 let mut selected_pair_id = None;
73 for entry in &stats {
74 match entry {
75 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => {
76 snapshot.inbound_packets += inbound.received.packets_received;
77 snapshot.inbound_bytes += inbound.inbound.bytes_received;
78 snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level);
79 }
80 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
81 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
82 snapshot.source_levels.push(format!(
83 "{}={:.3}",
84 source.source.track_identifier, source.audio.audio_level
85 ));
86 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
87 }
88 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
89 snapshot.outbound_packets += outbound.sent.packets_sent;
90 snapshot.outbound_bytes += outbound.sent.bytes_sent;
91 }
92 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
93 snapshot.video.inbound_packets += inbound.received.packets_received;
94 if share_mids.contains(&inbound.inbound.mid) {
95 snapshot.share_inbound_packets += inbound.received.packets_received;
96 snapshot.share_receive = Some(ShareReceive {
97 frames_decoded: inbound.inbound.frames_decoded,
98 key_frames_decoded: inbound.inbound.key_frames_decoded,
99 width: inbound.inbound.frame_width,
100 height: inbound.inbound.frame_height,
101 frames_per_second: inbound.inbound.frames_per_second,
102 pli_count: inbound.inbound.pli_count,
103 fir_count: inbound.inbound.fir_count,
104 freeze_count: inbound.inbound.freeze_count,
105 qp_sum: inbound.inbound.qp_sum,
106 bytes_received: inbound.inbound.bytes_received,
107 });
108 }
109 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
110 snapshot.video.inbound_width = snapshot
111 .video
112 .inbound_width
113 .max(inbound.inbound.frame_width);
114 snapshot.video.inbound_height = snapshot
115 .video
116 .inbound_height
117 .max(inbound.inbound.frame_height);
118 }
119 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
120 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
121 snapshot.video.remote_round_trip_ms = snapshot
122 .video
123 .remote_round_trip_ms
124 .max(remote.remote_inbound.round_trip_time * 1000.0);
125 }
126 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
127 snapshot.video.outbound_packets += outbound.sent.packets_sent;
128 if share_mids.contains(&outbound.outbound.mid) {
129 snapshot.share_outbound_packets += outbound.sent.packets_sent;
130 } else if outbound.outbound.active {
131 snapshot.camera_target_bitrate = snapshot
132 .camera_target_bitrate
133 .max(outbound.outbound.target_bitrate as u64);
134 }
135 snapshot.video.outbound_frames_encoded +=
136 u64::from(outbound.outbound.frames_encoded);
137 snapshot.video_senders.push(format!(
138 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
139 outbound.outbound.mid,
140 outbound.sent.packets_sent,
141 outbound.outbound.key_frames_encoded,
142 outbound.outbound.pli_count,
143 outbound.outbound.fir_count,
144 outbound.outbound.nack_count,
145 outbound.outbound.target_bitrate / 1000.0,
146 outbound.outbound.quality_limitation_reason,
147 outbound.outbound.active
148 ));
149 snapshot.video.outbound_width = snapshot
150 .video
151 .outbound_width
152 .max(outbound.outbound.frame_width);
153 snapshot.video.outbound_height = snapshot
154 .video
155 .outbound_height
156 .max(outbound.outbound.frame_height);
157 }
158 RtcStats::Transport(transport) => {
159 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
160 snapshot.tls_version = transport.transport.tls_version.clone();
161 snapshot.dtls_cipher = transport.transport.dtls_cipher.clone();
162 snapshot.srtp_cipher = transport.transport.srtp_cipher.clone();
163 if !transport.transport.selected_candidate_pair_id.is_empty() {
164 selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone());
165 }
166 }
167 _ => {}
168 }
169 }
170 if let Some(pair_id) = selected_pair_id {
171 let pair = stats.iter().find_map(|entry| match entry {
172 RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair),
173 _ => None,
174 });
175 if let Some(pair) = pair {
176 let describe = |candidate_id: &str| {
177 stats
178 .iter()
179 .find_map(|entry| match entry {
180 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
181 Some(&local.local_candidate)
182 }
183 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
184 Some(&remote.remote_candidate)
185 }
186 _ => None,
187 })
188 .map(|candidate| {
189 let kind = candidate
190 .candidate_type
191 .map(|kind| format!("{kind:?}"))
192 .unwrap_or_default();
193 let relay = candidate
194 .relay_protocol
195 .map(|relay| format!(" via {relay:?}"))
196 .unwrap_or_default();
197 format!("{kind}/{}{relay}", candidate.protocol)
198 })
199 .unwrap_or_else(|| "?".into())
200 };
201 snapshot.selected_pair = Some(format!(
202 "local {} <-> remote {}",
203 describe(&pair.candidate_pair.local_candidate_id),
204 describe(&pair.candidate_pair.remote_candidate_id)
205 ));
206 }
207 }
208 snapshot
209 }
@@ -0,0 +1,209 @@
1use super::*;
2
3#[derive(Debug, Default)]
4pub(super) struct StatsSnapshot {
5 pub(super) inbound_packets: u64,
6 pub(super) inbound_bytes: u64,
7 pub(super) outbound_packets: u64,
8 pub(super) outbound_bytes: u64,
9 pub(super) source_levels: Vec<String>,
10 pub(super) video_senders: Vec<String>,
11 pub(super) audio_level: f64,
12 pub(super) local_level: f64,
13 pub(super) echo_return_loss_enhancement: f64,
14 pub(super) video: VideoReport,
15 pub(super) camera_target_bitrate: u64,
16 pub(super) share_inbound_packets: u64,
17 pub(super) share_outbound_packets: u64,
18 pub(super) share_receive: Option<ShareReceive>,
19 pub(super) dtls_state: String,
20 pub(super) tls_version: String,
21 pub(super) dtls_cipher: String,
22 pub(super) srtp_cipher: String,
23 pub(super) selected_pair: Option<String>,
24 pub(super) health: HealthCounters,
25 pub(super) transport: TransportDetails,
26}
27
28#[derive(Debug, Default)]
29pub(super) struct ShareReceive {
30 pub(super) frames_decoded: u32,
31 pub(super) key_frames_decoded: u32,
32 pub(super) width: u32,
33 pub(super) height: u32,
34 pub(super) frames_per_second: f64,
35 pub(super) pli_count: u32,
36 pub(super) fir_count: u32,
37 pub(super) freeze_count: u32,
38 pub(super) qp_sum: u64,
39 pub(super) bytes_received: u64,
40}
41
42impl ShareReceive {
43 pub(super) fn average_qp(&self) -> u64 {
44 self.qp_sum
45 .checked_div(u64::from(self.frames_decoded))
46 .unwrap_or(0)
47 }
48
49 pub(super) fn summary(&self) -> String {
50 format!(
51 " share in decoded={} keyframes={} {}x{} fps={:.0} qp={} bytes={} pli={} fir={} freezes={}",
52 self.frames_decoded,
53 self.key_frames_decoded,
54 self.width,
55 self.height,
56 self.frames_per_second,
57 self.average_qp(),
58 self.bytes_received,
59 self.pli_count,
60 self.fir_count,
61 self.freeze_count
62 )
63 }
64}
65
66pub(super) async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSnapshot {
67 let Ok(stats) = peer.get_stats().await else {
68 return StatsSnapshot::default();
69 };
70 let mut snapshot = StatsSnapshot::default();
71 (snapshot.health, snapshot.transport) = health_from_stats(&stats);
72 let mut selected_pair_id = None;
73 for entry in &stats {
74 match entry {
75 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => {
76 snapshot.inbound_packets += inbound.received.packets_received;
77 snapshot.inbound_bytes += inbound.inbound.bytes_received;
78 snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level);
79 }
80 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
81 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
82 snapshot.source_levels.push(format!(
83 "{}={:.3}",
84 source.source.track_identifier, source.audio.audio_level
85 ));
86 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
87 }
88 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
89 snapshot.outbound_packets += outbound.sent.packets_sent;
90 snapshot.outbound_bytes += outbound.sent.bytes_sent;
91 }
92 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
93 snapshot.video.inbound_packets += inbound.received.packets_received;
94 if share_mids.contains(&inbound.inbound.mid) {
95 snapshot.share_inbound_packets += inbound.received.packets_received;
96 snapshot.share_receive = Some(ShareReceive {
97 frames_decoded: inbound.inbound.frames_decoded,
98 key_frames_decoded: inbound.inbound.key_frames_decoded,
99 width: inbound.inbound.frame_width,
100 height: inbound.inbound.frame_height,
101 frames_per_second: inbound.inbound.frames_per_second,
102 pli_count: inbound.inbound.pli_count,
103 fir_count: inbound.inbound.fir_count,
104 freeze_count: inbound.inbound.freeze_count,
105 qp_sum: inbound.inbound.qp_sum,
106 bytes_received: inbound.inbound.bytes_received,
107 });
108 }
109 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
110 snapshot.video.inbound_width = snapshot
111 .video
112 .inbound_width
113 .max(inbound.inbound.frame_width);
114 snapshot.video.inbound_height = snapshot
115 .video
116 .inbound_height
117 .max(inbound.inbound.frame_height);
118 }
119 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
120 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
121 snapshot.video.remote_round_trip_ms = snapshot
122 .video
123 .remote_round_trip_ms
124 .max(remote.remote_inbound.round_trip_time * 1000.0);
125 }
126 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
127 snapshot.video.outbound_packets += outbound.sent.packets_sent;
128 if share_mids.contains(&outbound.outbound.mid) {
129 snapshot.share_outbound_packets += outbound.sent.packets_sent;
130 } else if outbound.outbound.active {
131 snapshot.camera_target_bitrate = snapshot
132 .camera_target_bitrate
133 .max(outbound.outbound.target_bitrate as u64);
134 }
135 snapshot.video.outbound_frames_encoded +=
136 u64::from(outbound.outbound.frames_encoded);
137 snapshot.video_senders.push(format!(
138 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
139 outbound.outbound.mid,
140 outbound.sent.packets_sent,
141 outbound.outbound.key_frames_encoded,
142 outbound.outbound.pli_count,
143 outbound.outbound.fir_count,
144 outbound.outbound.nack_count,
145 outbound.outbound.target_bitrate / 1000.0,
146 outbound.outbound.quality_limitation_reason,
147 outbound.outbound.active
148 ));
149 snapshot.video.outbound_width = snapshot
150 .video
151 .outbound_width
152 .max(outbound.outbound.frame_width);
153 snapshot.video.outbound_height = snapshot
154 .video
155 .outbound_height
156 .max(outbound.outbound.frame_height);
157 }
158 RtcStats::Transport(transport) => {
159 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
160 snapshot.tls_version = transport.transport.tls_version.clone();
161 snapshot.dtls_cipher = transport.transport.dtls_cipher.clone();
162 snapshot.srtp_cipher = transport.transport.srtp_cipher.clone();
163 if !transport.transport.selected_candidate_pair_id.is_empty() {
164 selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone());
165 }
166 }
167 _ => {}
168 }
169 }
170 if let Some(pair_id) = selected_pair_id {
171 let pair = stats.iter().find_map(|entry| match entry {
172 RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair),
173 _ => None,
174 });
175 if let Some(pair) = pair {
176 let describe = |candidate_id: &str| {
177 stats
178 .iter()
179 .find_map(|entry| match entry {
180 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => {
181 Some(&local.local_candidate)
182 }
183 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => {
184 Some(&remote.remote_candidate)
185 }
186 _ => None,
187 })
188 .map(|candidate| {
189 let kind = candidate
190 .candidate_type
191 .map(|kind| format!("{kind:?}"))
192 .unwrap_or_default();
193 let relay = candidate
194 .relay_protocol
195 .map(|relay| format!(" via {relay:?}"))
196 .unwrap_or_default();
197 format!("{kind}/{}{relay}", candidate.protocol)
198 })
199 .unwrap_or_else(|| "?".into())
200 };
201 snapshot.selected_pair = Some(format!(
202 "local {} <-> remote {}",
203 describe(&pair.candidate_pair.local_candidate_id),
204 describe(&pair.candidate_pair.remote_candidate_id)
205 ));
206 }
207 }
208 snapshot
209}
crates/calling/src/call/teardown.rs added +237 −0
@@ -0,0 +1,237 @@
1 use super::*;
2
3 #[derive(Clone)]
4 pub(super) struct RemoteCall {
5 pub(super) signaling: Arc<Signaling>,
6 pub(super) conversation: Conversation,
7 pub(super) participant: Participant,
8 pub(super) threadless: bool,
9 }
10
11 #[derive(Default)]
12 pub(super) struct Live {
13 pub(super) peers: Vec<PeerConnection>,
14 pub(super) audio: Option<AudioSetup>,
15 pub(super) remote: Option<RemoteCall>,
16 pub(super) broker: Option<JoinHandle<()>>,
17 pub(super) broker_running: Arc<AtomicBool>,
18 pub(super) callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
19 pub(super) route_id: Option<String>,
20 pub(super) call_legs: Vec<String>,
21 pub(super) skip_leave: bool,
22 pub(super) cancel_leave: bool,
23 pub(super) video_tasks: Vec<JoinHandle<()>>,
24 pub(super) video_counters: Arc<VideoCounters>,
25 }
26
27 pub(super) async fn stop_local_publish(
28 local_video: &mut LocalVideo,
29 remote: &RemoteCall,
30 media_links: &BTreeMap<String, String>,
31 request_id: &mut u32,
32 control: &CallControl,
33 timeline: &Timeline,
34 ) {
35 let camera_mid = local_video.camera_mid();
36 let share_mid = local_video.share_mid();
37 let was_sharing = local_video.sharing();
38 let was_camera = local_video.camera_on() || local_video.camera_previewing();
39 if was_sharing {
40 local_video.stop_share();
41 clear_share(control);
42 }
43 if was_camera {
44 local_video.stop_camera();
45 control.send(CallUpdate::Camera(false));
46 }
47 local_video.clear_lines();
48 let Some(url) = media_links.get("updateMediaDescriptions").cloned() else {
49 return;
50 };
51 let mut descriptions = Vec::new();
52 if was_camera {
53 descriptions.push(MediaDescription::camera_line(
54 camera_mid.unwrap_or_else(|| CAMERA_MID.to_owned()),
55 false,
56 ));
57 }
58 if was_sharing {
59 descriptions.push(MediaDescription::share_line(
60 share_mid.unwrap_or_else(|| SHARE_MID.to_owned()),
61 false,
62 ));
63 }
64 if descriptions.is_empty() {
65 return;
66 }
67 *request_id += 1;
68 let id = *request_id;
69 match remote
70 .signaling
71 .update_media_descriptions(&url, &descriptions, id)
72 .await
73 {
74 Ok(()) => timeline.record(
75 "updateMediaDescriptions",
76 format!("publish off before leave, request {id}"),
77 ),
78 Err(error) => timeline.record(
79 "updateMediaDescriptions failed",
80 format!("publish off before leave: {error}"),
81 ),
82 }
83 }
84
85 pub(super) async fn tear_down(
86 mut live: Live,
87 inner: &Inner,
88 timeline: &Timeline,
89 report: &mut CallReport,
90 cancelled: bool,
91 ) {
92 if crate::noise_stage::overloaded() {
93 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
94 }
95 crate::noise_stage::clear();
96 // Stop keep-alive / broker first so Teams does not see us as still present.
97 live.broker_running.store(false, Ordering::SeqCst);
98 if let Some(broker) = live.broker.take() {
99 broker.abort();
100 }
101 if let Some(audio) = live.audio.take() {
102 audio.stop().await;
103 }
104 // Leave and drop call legs while peers are still open, then close media.
105 if !live.skip_leave
106 && let Some(remote) = &live.remote
107 {
108 let reason = if cancelled {
109 LeaveReason::Cancel
110 } else {
111 LeaveReason::Hangup
112 };
113 match remote
114 .signaling
115 .leave(&remote.conversation, &remote.participant, reason)
116 .await
117 {
118 Ok(()) => report.left_cleanly = true,
119 Err(error) => timeline.record("leave failed", error.to_string()),
120 }
121 for call_leg in &live.call_legs {
122 if let Err(error) = remote.signaling.end_call_leg(call_leg).await {
123 timeline.record("callLeg end failed", error.to_string());
124 }
125 }
126 }
127 if report.end.is_none()
128 && let Some(callbacks) = live.callbacks.as_mut()
129 && live.remote.is_some()
130 {
131 let waited = timeout(END_CALLBACK_WAIT, async {
132 while let Some(callback) = callbacks.recv().await {
133 let event = handle_callback(&callback, timeline);
134 if let Ok(CallEvent::End(end)) = event {
135 return Some(end);
136 }
137 }
138 None
139 })
140 .await;
141 report.end = waited.ok().flatten();
142 }
143 for peer in &live.peers {
144 peer.close();
145 }
146 for task in live.video_tasks.drain(..) {
147 task.abort();
148 }
149 if let Some(route_id) = &live.route_id {
150 inner.unregister_route(route_id);
151 }
152 timeline.record("closed", "peer closed, call route removed");
153 }
154
155 pub(super) fn setup_end_kind(end: &CallEnd) -> EndKind {
156 match end.kind() {
157 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
158 kind => kind,
159 }
160 }
161
162 pub(super) fn handle_callback(
163 callback: &TrouterCallback,
164 timeline: &Timeline,
165 ) -> Result<CallEvent> {
166 let body = decode_body(callback)?;
167 let (_, event) = classify(&callback.path, body)?;
168 let detail = match &event {
169 CallEvent::Acceptance(acceptance) => format!(
170 "answer sdp {} bytes, fromMixer={}",
171 acceptance.sdp.len(),
172 acceptance.from_mixer
173 ),
174 CallEvent::End(end) => format!(
175 "code={} subCode={} phrase={}",
176 end.code, end.sub_code, end.phrase
177 ),
178 CallEvent::Progress(status) => format!("{status:?}"),
179 CallEvent::ConversationEnd(body)
180 | CallEvent::Rejection(body)
181 | CallEvent::AddParticipantFailure(body)
182 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
183 CallEvent::ControlVideoStreaming(body) => parse_request(body)
184 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
185 CallEvent::MediaAcknowledgement(ack) => {
186 let names = ack.links.keys().cloned().collect::<Vec<_>>().join(",");
187 if names.is_empty() {
188 format!("links=none keys={}", ack.keys)
189 } else {
190 format!("links={names}")
191 }
192 }
193 _ => String::new(),
194 };
195 timeline.record(format!("Trouter {}", event.name()), detail);
196 match &event {
197 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
198 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
199 CallEvent::MediaRenegotiation(renegotiation) => {
200 timeline.record_sdp("remote offer", &renegotiation.sdp);
201 let names = renegotiation
202 .links
203 .keys()
204 .cloned()
205 .collect::<Vec<_>>()
206 .join(",");
207 timeline.record(
208 "renegotiation links",
209 if names.is_empty() {
210 "none".to_owned()
211 } else {
212 names
213 },
214 );
215 }
216 _ => {}
217 }
218 Ok(event)
219 }
220
221 pub(super) async fn poll_broker(
222 signaling: Arc<Signaling>,
223 conversation: Conversation,
224 running: Arc<AtomicBool>,
225 ) {
226 let Ok(first) = conversation.link("subscribe") else {
227 return;
228 };
229 let mut url = first.to_owned();
230 while running.load(Ordering::SeqCst) {
231 match signaling.poll_broker(&url).await {
232 Ok(Some(next)) => url = next,
233 Ok(None) => tokio::time::sleep(BROKER_IDLE_WAIT).await,
234 Err(_) => tokio::time::sleep(BROKER_RETRY_WAIT).await,
235 }
236 }
237 }
@@ -0,0 +1,237 @@
1use super::*;
2
3#[derive(Clone)]
4pub(super) struct RemoteCall {
5 pub(super) signaling: Arc<Signaling>,
6 pub(super) conversation: Conversation,
7 pub(super) participant: Participant,
8 pub(super) threadless: bool,
9}
10
11#[derive(Default)]
12pub(super) struct Live {
13 pub(super) peers: Vec<PeerConnection>,
14 pub(super) audio: Option<AudioSetup>,
15 pub(super) remote: Option<RemoteCall>,
16 pub(super) broker: Option<JoinHandle<()>>,
17 pub(super) broker_running: Arc<AtomicBool>,
18 pub(super) callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
19 pub(super) route_id: Option<String>,
20 pub(super) call_legs: Vec<String>,
21 pub(super) skip_leave: bool,
22 pub(super) cancel_leave: bool,
23 pub(super) video_tasks: Vec<JoinHandle<()>>,
24 pub(super) video_counters: Arc<VideoCounters>,
25}
26
27pub(super) async fn stop_local_publish(
28 local_video: &mut LocalVideo,
29 remote: &RemoteCall,
30 media_links: &BTreeMap<String, String>,
31 request_id: &mut u32,
32 control: &CallControl,
33 timeline: &Timeline,
34) {
35 let camera_mid = local_video.camera_mid();
36 let share_mid = local_video.share_mid();
37 let was_sharing = local_video.sharing();
38 let was_camera = local_video.camera_on() || local_video.camera_previewing();
39 if was_sharing {
40 local_video.stop_share();
41 clear_share(control);
42 }
43 if was_camera {
44 local_video.stop_camera();
45 control.send(CallUpdate::Camera(false));
46 }
47 local_video.clear_lines();
48 let Some(url) = media_links.get("updateMediaDescriptions").cloned() else {
49 return;
50 };
51 let mut descriptions = Vec::new();
52 if was_camera {
53 descriptions.push(MediaDescription::camera_line(
54 camera_mid.unwrap_or_else(|| CAMERA_MID.to_owned()),
55 false,
56 ));
57 }
58 if was_sharing {
59 descriptions.push(MediaDescription::share_line(
60 share_mid.unwrap_or_else(|| SHARE_MID.to_owned()),
61 false,
62 ));
63 }
64 if descriptions.is_empty() {
65 return;
66 }
67 *request_id += 1;
68 let id = *request_id;
69 match remote
70 .signaling
71 .update_media_descriptions(&url, &descriptions, id)
72 .await
73 {
74 Ok(()) => timeline.record(
75 "updateMediaDescriptions",
76 format!("publish off before leave, request {id}"),
77 ),
78 Err(error) => timeline.record(
79 "updateMediaDescriptions failed",
80 format!("publish off before leave: {error}"),
81 ),
82 }
83}
84
85pub(super) async fn tear_down(
86 mut live: Live,
87 inner: &Inner,
88 timeline: &Timeline,
89 report: &mut CallReport,
90 cancelled: bool,
91) {
92 if crate::noise_stage::overloaded() {
93 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
94 }
95 crate::noise_stage::clear();
96 // Stop keep-alive / broker first so Teams does not see us as still present.
97 live.broker_running.store(false, Ordering::SeqCst);
98 if let Some(broker) = live.broker.take() {
99 broker.abort();
100 }
101 if let Some(audio) = live.audio.take() {
102 audio.stop().await;
103 }
104 // Leave and drop call legs while peers are still open, then close media.
105 if !live.skip_leave
106 && let Some(remote) = &live.remote
107 {
108 let reason = if cancelled {
109 LeaveReason::Cancel
110 } else {
111 LeaveReason::Hangup
112 };
113 match remote
114 .signaling
115 .leave(&remote.conversation, &remote.participant, reason)
116 .await
117 {
118 Ok(()) => report.left_cleanly = true,
119 Err(error) => timeline.record("leave failed", error.to_string()),
120 }
121 for call_leg in &live.call_legs {
122 if let Err(error) = remote.signaling.end_call_leg(call_leg).await {
123 timeline.record("callLeg end failed", error.to_string());
124 }
125 }
126 }
127 if report.end.is_none()
128 && let Some(callbacks) = live.callbacks.as_mut()
129 && live.remote.is_some()
130 {
131 let waited = timeout(END_CALLBACK_WAIT, async {
132 while let Some(callback) = callbacks.recv().await {
133 let event = handle_callback(&callback, timeline);
134 if let Ok(CallEvent::End(end)) = event {
135 return Some(end);
136 }
137 }
138 None
139 })
140 .await;
141 report.end = waited.ok().flatten();
142 }
143 for peer in &live.peers {
144 peer.close();
145 }
146 for task in live.video_tasks.drain(..) {
147 task.abort();
148 }
149 if let Some(route_id) = &live.route_id {
150 inner.unregister_route(route_id);
151 }
152 timeline.record("closed", "peer closed, call route removed");
153}
154
155pub(super) fn setup_end_kind(end: &CallEnd) -> EndKind {
156 match end.kind() {
157 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
158 kind => kind,
159 }
160}
161
162pub(super) fn handle_callback(
163 callback: &TrouterCallback,
164 timeline: &Timeline,
165) -> Result<CallEvent> {
166 let body = decode_body(callback)?;
167 let (_, event) = classify(&callback.path, body)?;
168 let detail = match &event {
169 CallEvent::Acceptance(acceptance) => format!(
170 "answer sdp {} bytes, fromMixer={}",
171 acceptance.sdp.len(),
172 acceptance.from_mixer
173 ),
174 CallEvent::End(end) => format!(
175 "code={} subCode={} phrase={}",
176 end.code, end.sub_code, end.phrase
177 ),
178 CallEvent::Progress(status) => format!("{status:?}"),
179 CallEvent::ConversationEnd(body)
180 | CallEvent::Rejection(body)
181 | CallEvent::AddParticipantFailure(body)
182 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
183 CallEvent::ControlVideoStreaming(body) => parse_request(body)
184 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
185 CallEvent::MediaAcknowledgement(ack) => {
186 let names = ack.links.keys().cloned().collect::<Vec<_>>().join(",");
187 if names.is_empty() {
188 format!("links=none keys={}", ack.keys)
189 } else {
190 format!("links={names}")
191 }
192 }
193 _ => String::new(),
194 };
195 timeline.record(format!("Trouter {}", event.name()), detail);
196 match &event {
197 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
198 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
199 CallEvent::MediaRenegotiation(renegotiation) => {
200 timeline.record_sdp("remote offer", &renegotiation.sdp);
201 let names = renegotiation
202 .links
203 .keys()
204 .cloned()
205 .collect::<Vec<_>>()
206 .join(",");
207 timeline.record(
208 "renegotiation links",
209 if names.is_empty() {
210 "none".to_owned()
211 } else {
212 names
213 },
214 );
215 }
216 _ => {}
217 }
218 Ok(event)
219}
220
221pub(super) async fn poll_broker(
222 signaling: Arc<Signaling>,
223 conversation: Conversation,
224 running: Arc<AtomicBool>,
225) {
226 let Ok(first) = conversation.link("subscribe") else {
227 return;
228 };
229 let mut url = first.to_owned();
230 while running.load(Ordering::SeqCst) {
231 match signaling.poll_broker(&url).await {
232 Ok(Some(next)) => url = next,
233 Ok(None) => tokio::time::sleep(BROKER_IDLE_WAIT).await,
234 Err(_) => tokio::time::sleep(BROKER_RETRY_WAIT).await,
235 }
236 }
237}
docs/research/internal-endpoints.md +1 −1
@@ -146,7 +146,7 @@ Token audiences (not requests): `crates/session/src/scope.rs` - `ic3.teams.offic
146 146 | `api-emea.flightproxy.teams.microsoft.com/api/v2/epconv` | POST | `crates/calling/src/signaling.rs` | create conversation, subscribe meeting, resolve meeting id | W | no - `/communications/calls` is app-only (bot registration), not a user client |
147 147 | `api.flightproxy.teams.microsoft.com/api/v2/ep/{cc or conv host}/{path}` | as link | `crates/calling/src/signaling.rs` (`routed_url`) | transport for every `*.cc.skype.com` / `*.conv.skype.com` link | R/W | no |
148 148 | conversation controller links (server-provided): join, end for all, broker poll, updateEndpointState, publishState, removeState, sendMessage, addParticipant(AndModality), updateEndpointMetadata, admit, removeParticipant, mute, updateMeetingSettings, updateParticipantRole, notificationLinks, leave, transfer | POST, PUT, GET, DELETE | `crates/calling/src/signaling.rs` | meeting join, roster, hand raise, spotlight, reactions, invite, lobby, mute, lock, roles, keep-alive, leave, transfer | R/W | no - no user-token call control in Graph; `updateMeetingSettings` partly via onlineMeeting PATCH |
149 | call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call.rs`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, hangup, keep-alive, renegotiation, video layout | W | no |
149 | call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call/`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, hangup, keep-alive, renegotiation, video layout | W | no |
150 150 | recording / caption bot command URL (from roster) | POST | `crates/calling/src/signaling.rs`, `crates/calling/assets/caption_command.js` | recording start / stop, captions on / off, caption language | W | no - Graph only has post-meeting recordings and transcripts |
151 151 | `teams.cloud.microsoft/api/authsvc/v1.0/authz` | POST | `crates/calling/assets/caption_command.js` | Skype token for the bot command | R | no |
152 152 | `teams.microsoft.com/trap/tokens` | GET | `crates/calling/src/relay.rs` | TURN credentials | R | no |
@@ -146,7 +146,7 @@ Token audiences (not requests): `crates/session/src/scope.rs` - `ic3.teams.offic
146| `api-emea.flightproxy.teams.microsoft.com/api/v2/epconv` | POST | `crates/calling/src/signaling.rs` | create conversation, subscribe meeting, resolve meeting id | W | no - `/communications/calls` is app-only (bot registration), not a user client |
146| `api-emea.flightproxy.teams.microsoft.com/api/v2/epconv` | POST | `crates/calling/src/signaling.rs` | create conversation, subscribe meeting, resolve meeting id | W | no - `/communications/calls` is app-only (bot registration), not a user client |
147| `api.flightproxy.teams.microsoft.com/api/v2/ep/{cc or conv host}/{path}` | as link | `crates/calling/src/signaling.rs` (`routed_url`) | transport for every `*.cc.skype.com` / `*.conv.skype.com` link | R/W | no |
147| `api.flightproxy.teams.microsoft.com/api/v2/ep/{cc or conv host}/{path}` | as link | `crates/calling/src/signaling.rs` (`routed_url`) | transport for every `*.cc.skype.com` / `*.conv.skype.com` link | R/W | no |
148| conversation controller links (server-provided): join, end for all, broker poll, updateEndpointState, publishState, removeState, sendMessage, addParticipant(AndModality), updateEndpointMetadata, admit, removeParticipant, mute, updateMeetingSettings, updateParticipantRole, notificationLinks, leave, transfer | POST, PUT, GET, DELETE | `crates/calling/src/signaling.rs` | meeting join, roster, hand raise, spotlight, reactions, invite, lobby, mute, lock, roles, keep-alive, leave, transfer | R/W | no - no user-token call control in Graph; `updateMeetingSettings` partly via onlineMeeting PATCH |
148| conversation controller links (server-provided): join, end for all, broker poll, updateEndpointState, publishState, removeState, sendMessage, addParticipant(AndModality), updateEndpointMetadata, admit, removeParticipant, mute, updateMeetingSettings, updateParticipantRole, notificationLinks, leave, transfer | POST, PUT, GET, DELETE | `crates/calling/src/signaling.rs` | meeting join, roster, hand raise, spotlight, reactions, invite, lobby, mute, lock, roles, keep-alive, leave, transfer | R/W | no - no user-token call control in Graph; `updateMeetingSettings` partly via onlineMeeting PATCH |
149| call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call.rs`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, hangup, keep-alive, renegotiation, video layout | W | no |
149| call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call/`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, hangup, keep-alive, renegotiation, video layout | W | no |
150| recording / caption bot command URL (from roster) | POST | `crates/calling/src/signaling.rs`, `crates/calling/assets/caption_command.js` | recording start / stop, captions on / off, caption language | W | no - Graph only has post-meeting recordings and transcripts |
150| recording / caption bot command URL (from roster) | POST | `crates/calling/src/signaling.rs`, `crates/calling/assets/caption_command.js` | recording start / stop, captions on / off, caption language | W | no - Graph only has post-meeting recordings and transcripts |
151| `teams.cloud.microsoft/api/authsvc/v1.0/authz` | POST | `crates/calling/assets/caption_command.js` | Skype token for the bot command | R | no |
151| `teams.cloud.microsoft/api/authsvc/v1.0/authz` | POST | `crates/calling/assets/caption_command.js` | Skype token for the bot command | R | no |
152| `teams.microsoft.com/trap/tokens` | GET | `crates/calling/src/relay.rs` | TURN credentials | R | no |
152| `teams.microsoft.com/trap/tokens` | GET | `crates/calling/src/relay.rs` | TURN credentials | R | no |