1use anyhow::Result;
2use rsipstack::dialog::{authenticate::Credential, invitation::InviteOption};
3use serde::{Deserialize, Serialize};
4use serde_with::skip_serializing_none;
5use std::collections::HashMap;
6
7use crate::{
8 media::{
9 agc::AGCOption, ambiance::AmbianceOption, recorder::RecorderOption,
10 track::media_pass::MediaPassOption, vad::VADOption,
11 },
12 synthesis::SynthesisOption,
13 transcription::TranscriptionOption,
14};
15
16pub mod app;
17pub mod call;
18pub mod callrecord;
19pub mod config;
20pub mod event;
21pub mod handler;
22pub mod locator;
23pub mod main_builder;
24pub mod media;
25pub mod net_tool;
26
27#[cfg(feature = "offline")]
28pub mod offline;
29
30pub mod playbook;
31pub mod sip_util;
32pub mod synthesis;
33pub mod transcription;
34pub mod useragent;
35
36#[derive(Debug, Deserialize, Serialize, Default, Clone)]
37#[serde(default)]
38pub struct SipOption {
39 pub username: Option<String>,
40 pub password: Option<String>,
41 pub realm: Option<String>,
42 pub contact: Option<String>,
43 pub headers: Option<HashMap<String, String>>,
44 pub hangup_headers: Option<HashMap<String, String>>,
45 pub extract_headers: Option<Vec<String>>,
46 pub enable_srtp: Option<bool>,
47}
48
49#[skip_serializing_none]
50#[derive(Debug, Deserialize, Serialize, Clone)]
51#[serde(rename_all = "camelCase")]
52pub struct CallOption {
53 pub denoise: Option<bool>,
54 pub agc: Option<AGCOption>,
55 pub offer: Option<String>,
56 pub callee: Option<String>,
57 pub caller: Option<String>,
58 pub recorder: Option<RecorderOption>,
59 pub vad: Option<VADOption>,
60 pub asr: Option<TranscriptionOption>,
61 pub tts: Option<SynthesisOption>,
62 pub media_pass: Option<MediaPassOption>,
63 pub handshake_timeout: Option<u64>,
65 pub enable_ipv6: Option<bool>,
66 pub inactivity_timeout: Option<u64>, pub sip: Option<SipOption>,
68 pub extra: Option<HashMap<String, String>>,
69 pub codec: Option<String>, pub ambiance: Option<AmbianceOption>,
71 pub eou: Option<EouOption>,
72 pub realtime: Option<RealtimeOption>,
73 pub subscribe: Option<bool>,
74 pub enable_ice_lite: Option<bool>,
75 pub ringback_detection: Option<RingbackDetectionOption>,
76}
77
78impl Default for CallOption {
79 fn default() -> Self {
80 Self {
81 denoise: None,
82 agc: None,
83 offer: None,
84 callee: None,
85 caller: None,
86 recorder: None,
87 asr: None,
88 vad: None,
89 tts: None,
90 media_pass: None,
91 handshake_timeout: None,
92 inactivity_timeout: Some(50), enable_ipv6: None,
94 sip: None,
95 extra: None,
96 codec: None,
97 ambiance: None,
98 eou: None,
99 realtime: None,
100 subscribe: None,
101 enable_ice_lite: None,
102 ringback_detection: None,
103 }
104 }
105}
106
107impl CallOption {
108 pub fn check_default(&mut self) {
109 if let Some(tts) = &mut self.tts {
110 tts.check_default();
111 }
112 if let Some(asr) = &mut self.asr {
113 asr.check_default();
114 }
115 if let Some(realtime) = &mut self.realtime {
116 realtime.check_default();
117 }
118 }
119
120 pub fn build_invite_option(&self) -> Result<InviteOption> {
121 let mut invite_option = InviteOption::default();
122 if let Some(offer) = &self.offer {
123 invite_option.offer = Some(offer.clone().into());
124 }
125 if let Some(callee) = &self.callee {
126 invite_option.callee = callee.clone().try_into()?;
127 }
128 let caller_uri = if let Some(caller) = &self.caller {
129 crate::sip_util::ensure_sip_scheme(caller.clone())
131 } else if let Some(username) = self.sip.as_ref().and_then(|sip| sip.username.as_ref()) {
132 let domain = self
135 .sip
136 .as_ref()
137 .and_then(|sip| sip.realm.as_ref())
138 .map(|s| s.as_str())
139 .unwrap_or("127.0.0.1");
140 format!("sip:{}@{}", username, domain)
141 } else {
142 "sip:active-call@127.0.0.1".to_string()
144 };
145 invite_option.caller = caller_uri.try_into()?;
146
147 if let Some(sip) = &self.sip {
148 invite_option.credential = Some(Credential {
149 username: sip.username.clone().unwrap_or_default(),
150 auth_username: None,
151 password: sip.password.clone().unwrap_or_default(),
152 realm: sip.realm.clone(),
153 });
154 invite_option.headers = sip
155 .headers
156 .as_ref()
157 .map(crate::sip_util::sip_headers_from_map);
158 sip.contact.as_ref().map(|c| match c.clone().try_into() {
159 Ok(u) => {
160 invite_option.contact = u;
161 }
162 Err(_) => {}
163 });
164 }
165 Ok(invite_option)
166 }
167}
168
169#[skip_serializing_none]
170#[derive(Debug, Deserialize, Serialize, Clone)]
171#[serde(rename_all = "camelCase")]
172pub struct ReferOption {
173 pub denoise: Option<bool>,
174 pub agc: Option<AGCOption>,
175 pub timeout: Option<u32>,
176 pub moh: Option<String>,
177 pub vad: Option<VADOption>,
178 pub asr: Option<TranscriptionOption>,
179 pub auto_hangup: Option<bool>,
181 pub sip: Option<SipOption>,
182 pub call_id: Option<String>,
183 pub pause_parent_asr: Option<bool>,
185 pub forward_dtmf: Option<bool>,
187}
188
189#[skip_serializing_none]
190#[derive(Clone, Debug, Deserialize, Serialize, Default)]
191#[serde(rename_all = "camelCase")]
192pub struct EouOption {
193 pub r#type: Option<String>,
194 pub endpoint: Option<String>,
195 #[serde(alias = "apiKey")]
196 pub secret_key: Option<String>,
197 pub secret_id: Option<String>,
198 pub timeout: Option<u32>,
200 pub extra: Option<HashMap<String, String>>,
201}
202
203#[skip_serializing_none]
204#[derive(Clone, Debug, Deserialize, Serialize, Default)]
205#[serde(rename_all = "camelCase")]
206pub struct RingbackDetectionOption {
207 pub enabled: Option<bool>,
208 pub model_weights_path: Option<String>,
210 pub min_buffer_secs: Option<f32>,
212 pub detection_interval_secs: Option<f32>,
214 pub confidence_threshold: Option<f32>,
216 pub on_state_change_only: Option<bool>,
218 pub sliding_window_size: Option<usize>,
220 pub final_confidence_threshold: Option<f32>,
222}
223
224#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
225pub enum RealtimeType {
226 #[serde(rename = "openai")]
227 OpenAI,
228 #[serde(rename = "azure")]
229 Azure,
230 Other(String),
231}
232
233impl<'de> Deserialize<'de> for RealtimeType {
234 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
235 where
236 D: serde::Deserializer<'de>,
237 {
238 let value = String::deserialize(deserializer)?;
239 match value.as_str() {
240 "openai" => Ok(RealtimeType::OpenAI),
241 "azure" => Ok(RealtimeType::Azure),
242 _ => Ok(RealtimeType::Other(value)),
243 }
244 }
245}
246
247#[skip_serializing_none]
248#[derive(Clone, Debug, Deserialize, Serialize, Default)]
249#[serde(rename_all = "camelCase")]
250pub struct RealtimeOption {
251 pub provider: Option<RealtimeType>,
252 pub model: Option<String>,
253 #[serde(alias = "apiKey")]
254 pub secret_key: Option<String>,
255 pub secret_id: Option<String>,
256 pub endpoint: Option<String>,
257 pub turn_detection: Option<serde_json::Value>,
258 pub tools: Option<Vec<serde_json::Value>>,
259 pub extra: Option<HashMap<String, String>>,
260}
261
262impl RealtimeOption {
263 pub fn check_default(&mut self) {
264 if self.secret_key.is_none() {
265 self.secret_key = std::env::var("OPENAI_API_KEY").ok();
266 }
267 }
268}
269
270pub type Spawner = fn(
271 std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
272) -> tokio::task::JoinHandle<()>;
273static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
274
275pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
276 EXTERNAL_SPAWNER.set(spawner)
277}
278
279pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
280where
281 F: std::future::Future<Output = ()> + Send + 'static,
282{
283 if let Some(spawner) = EXTERNAL_SPAWNER.get() {
284 spawner(Box::pin(future))
285 } else {
286 tokio::spawn(future)
287 }
288}