BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / call / audio_switch.rs

audio_switch.rs

audio_switch.rs 9.2 KiB Download Raw
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}