Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion docs/rwi.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ Some commands support aliases for convenience:
| `call.set_userdata` / `call.get_userdata` | Replace / read the session user data object (see below) |
| `call.send_dtmf` | Send DTMF digits to the remote party |
| `dtmf.collect` | Collect a multi-digit DTMF string |
| `call.leg_add` / `call.leg_remove` | Dynamically add / remove a call leg |
| `call.leg_add` / `call.leg_remove` | Dynamically add / remove a call leg (dialed, or answered from an SDP offer) |
| `call.app_start` / `call.app_stop` | Start / stop a call application on the session |
| `call.resume` | Resume receiving events for a call after re-attach |
| `app.chain` | Chain into another call application |
Expand Down Expand Up @@ -309,6 +309,31 @@ without changing other legs. `call.hangup` still ends the whole call. Unbridge
leaves the legs alive and disconnected; subsequent leg state changes do not
select a replacement pair automatically. Caller hangup still ends the session.

**Add a leg from an SDP offer (WebRTC join):**

Instead of a `target`, `call.leg_add` may carry an `offer`: an SDP offer from
a client that joins the call directly, such as a browser or a WebRTC agent
whose controller relays signaling over RWI. The session creates the leg's media
peer from the offer (ICE + DTLS → WebRTC, the same transport WebRTC SIP callers
use), answers it, and returns the SDP answer with the leg ID. `target` and
`offer` are exclusive.

```json
{"action":"call.leg_add","action_id":"join-1","params":{"call_id":"session-1","leg_id":"0192f0c4a8e47b3c9d2e5f6a7b8c9d0e","offer":"v=0\r\n..."}}
{"type":"command_completed","action_id":"join-1","status":"success","data":{"leg_id":"0192f0c4a8e47b3c9d2e5f6a7b8c9d0e","answer":"v=0\r\n..."}}
```

Unlike a dialed leg, the command completes after the answer is ready (ICE
candidates gathered, at most 10 s), and the leg is connected at once: it emits a
leg-scoped `call_answered` with no `call_ringing`. The answer prefers the
caller's negotiated codec when the offer carries it, so the bridge passes audio
through; otherwise it follows the codec policy (G.711 when none is configured)
and transcodes. ICE uses the media `external_ip`, `webrtc_port_start`/`end` and
`ice_servers` settings. The leg has no SIP dialog: bridge it with `call.bridge`,
end it with `call.leg_remove`, and it ends with the call. `call.bridge` checks
leg IDs before dispatch and accepts `caller`, `callee`, `consult*` or at least
32 hex characters, so give the leg such an ID.

**Reject call:**

```json
Expand Down
13 changes: 12 additions & 1 deletion docs/rwi_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ RWI 命令使用 JSON 带标签联合格式。`action` 标识命令类型,`par
| `call.set_userdata` / `call.get_userdata` | 全量替换/读取会话用户数据对象(见下) |
| `call.send_dtmf` | 向远端发送 DTMF 数字 |
| `dtmf.collect` | 收集多位 DTMF 字符串 |
| `call.leg_add` / `call.leg_remove` | 动态添加/移除通话腿 |
| `call.leg_add` / `call.leg_remove` | 动态添加/移除通话腿(拨号,或由 SDP offer 应答) |
| `call.app_start` / `call.app_stop` | 在会话上启动/停止通话应用 |
| `call.resume` | 重新附着后恢复接收某通通话事件 |
| `app.chain` | 串联进入另一个通话应用 |
Expand Down Expand Up @@ -268,6 +268,17 @@ RWI 命令使用 JSON 带标签联合格式。`action` 标识命令类型,`par

有效 `reason` 值:`busy`、`forbidden`、`not_found`。

**由 SDP offer 添加通话腿(WebRTC 加入):**

`call.leg_add` 可以不带 `target`,改带 `offer`:由直接加入通话的客户端(如浏览器,或经控制方通过 RWI 中转信令的 WebRTC 坐席)生成的 SDP offer。会话按 offer 创建该腿的媒体端点(ICE + DTLS → WebRTC,与 WebRTC SIP 主叫相同的传输),生成应答,并随腿 ID 返回 SDP answer。`target` 与 `offer` 互斥。

```json
{"action":"call.leg_add","action_id":"join-1","params":{"call_id":"session-1","leg_id":"0192f0c4a8e47b3c9d2e5f6a7b8c9d0e","offer":"v=0\r\n..."}}
{"type":"command_completed","action_id":"join-1","status":"success","data":{"leg_id":"0192f0c4a8e47b3c9d2e5f6a7b8c9d0e","answer":"v=0\r\n..."}}
```

与拨号腿不同,命令在应答就绪(ICE 候选收集完成,最长 10 秒)后才完成,且该腿立即处于已接通状态:发出带 `leg_id` 的 `call_answered`,不发 `call_ringing`。若 offer 含主叫已协商的编解码,应答优先使用它,桥接时音频直通;否则按编解码策略(未配置时为 G.711)协商并转码。ICE 使用媒体配置中的 `external_ip`、`webrtc_port_start`/`end` 与 `ice_servers`。该腿没有 SIP 对话:用 `call.bridge` 桥接,用 `call.leg_remove` 结束,通话结束时随之结束。`call.bridge` 在派发前校验腿 ID,只接受 `caller`、`callee`、`consult*` 或至少 32 位十六进制字符,因此请为该腿使用这样的 ID。

**设置会话用户数据**(全量替换——旧对象整体丢弃):

```json
Expand Down
14 changes: 14 additions & 0 deletions src/call/domain/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -762,6 +762,20 @@ pub enum CallCommand {
purpose: Option<LegPurpose>,
},

/// Add a leg whose media peer answers a remote SDP offer (e.g. a WebRTC
/// client joining over RWI) instead of dialing SIP. The leg is connected
/// once the local answer is committed and is never bridged implicitly.
/// Internal request/reply command, never serialized.
#[serde(skip)]
LegAddOffer {
/// Optional leg ID (auto-generated if not provided)
leg_id: Option<LegId>,
/// Remote SDP offer
offer: String,
/// The added leg and the local SDP answer, or why the leg was refused
reply: oneshot::Sender<std::result::Result<(LegId, String), String>>,
},

/// Remove a leg from the session
LegRemove {
/// Leg ID to remove
Expand Down
133 changes: 133 additions & 0 deletions src/proxy/proxy_call/sip_session/session.rs
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,30 @@ impl SipSessionHandle {
.map_err(|_| anyhow::anyhow!("session closed before answering recorder query"))?
}

/// Add a leg answering `offer` and return its ID with the local SDP
/// answer. ICE gathering runs before the answer is returned, so this
/// waits up to ten seconds for the session to finish it.
pub async fn add_offer_leg(
&self,
leg_id: Option<LegId>,
offer: String,
) -> Result<(LegId, String), String> {
const OFFER_LEG_TIMEOUT: Duration = Duration::from_secs(10);
let (reply, response) = oneshot::channel();
self.cmd_tx
.send(self.sourced_command(CallCommand::LegAddOffer {
leg_id,
offer,
reply,
}))
.await
.map_err(|_| "session closed".to_string())?;
tokio::time::timeout(OFFER_LEG_TIMEOUT, response)
.await
.map_err(|_| "timed out waiting for the leg answer".to_string())?
.map_err(|_| "session closed before answering the offer".to_string())?
}

/// Query the owning session and queue loops; no cached snapshot is consulted.
pub async fn queue_dispatch_diagnostic(
&self,
Expand Down Expand Up @@ -11928,6 +11952,20 @@ impl SipSession {
}
}

CallCommand::LegAddOffer {
leg_id,
offer,
reply,
} => {
let added = self.handle_add_offer_leg(leg_id, &offer).await;
let result = match &added {
Ok((leg_id, _)) => CommandResult::success_with_leg(leg_id.clone()),
Err(error) => CommandResult::failure(error.to_string()),
};
let _ = reply.send(added.map_err(|error| error.to_string()));
result
}

CallCommand::LegRemove { leg_id, reason } => {
Self::ok_or_failure(self.handle_remove_leg(leg_id, reason).await)
}
Expand Down Expand Up @@ -13831,6 +13869,101 @@ impl SipSession {
Ok(location)
}

/// Add a leg whose media peer answers `offer` directly, with no SIP
/// dialog. The transport follows the offer (ICE + DTLS → WebRTC), so a
/// browser or WebRTC agent can join the call through its controller. The
/// leg is connected once the answer is committed; like `call.leg_add`, it
/// joins media only through an explicit bridge and ends through leg
/// removal or session hangup.
pub(super) async fn handle_add_offer_leg(
&mut self,
leg_id: Option<LegId>,
offer: &str,
) -> Result<(LegId, String)> {
let leg_id = leg_id.unwrap_or_else(|| LegId::new(format!("leg-{}", uuid::Uuid::new_v4())));
if self
.legs
.get(&leg_id)
.is_some_and(|leg| leg.state != LegState::Ended)
{
return Err(anyhow!("Leg already exists: {}", leg_id));
}
let transport = Self::sdp_transport_mode(offer);
let codecs = self.offer_leg_codecs(offer);
let video = self.video_caps_from_sdp(offer);
let cfg = self.build_leg_config(&leg_id, transport.clone(), codecs, video);
let peer = crate::media::create_leg(
leg_id.as_str(),
&cfg,
self.media.recording.capture_sender(),
crate::media::CaptureRoute::Deferred,
)?;
let answer = async {
peer.apply_remote_sdp(offer, rustrtc::SdpType::Offer)
.await?;
let mut answer = peer.prepare_answer().await?.to_sdp_string();
if !self.video_relay_enabled()
&& let Some(stripped) = MediaNegotiator::strip_video_from_sdp(&answer)
{
answer = stripped;
}
peer.commit_local_answer(&answer, rustrtc::SdpType::Answer)
.await
}
.await;
let answer = match answer {
Ok(answer) => answer,
Err(error) => {
peer.stop();
return Err(error);
}
};
peer.accept();
info!(session_id = %self.id, %leg_id, transport = ?transport, "Adding offer-answered leg to session");
self.legs.insert(
leg_id.clone(),
crate::call::domain::Leg::new(leg_id.clone()),
);
self.update_leg_state(&leg_id, LegState::Initializing);
self.record_leg_event(
&leg_id.0,
crate::callrecord::LegTimelineEventType::Added,
None,
None,
);
self.attach_media_leg(&leg_id, peer);
self.legs.set_transport(leg_id.clone(), transport);
self.legs.set_answer(leg_id.clone(), answer.clone());
self.update_leg_state(&leg_id, LegState::Connected);
self.update_media_path().await;
Ok((leg_id, answer))
}

/// Audio codecs for an offer-answered leg: the caller's negotiated codec
/// when offered, so a later bridge passes audio through untranscoded;
/// otherwise the effective codec policy (G.711 when none is configured),
/// falling back to the offerer's own order when nothing intersects.
fn offer_leg_codecs(&self, offer: &str) -> Vec<crate::media::negotiate::CodecInfo> {
let offered = MediaNegotiator::build_codec_list_from_offer(offer, &[]);
let caller_codec = self
.media_leg(&LegId::from("caller"))
.and_then(|peer| peer.negotiated())
.and_then(|profile| profile.audio.map(|audio| audio.codec))
.filter(|codec| offered.iter().any(|offered| offered.codec == *codec));
let policy = match caller_codec {
Some(codec) => vec![codec],
None => {
let configured = self.resolve_effective_codecs();
if configured.is_empty() {
vec![CodecType::PCMU, CodecType::PCMA]
} else {
configured
}
}
};
MediaNegotiator::build_codec_list_from_offer(offer, &policy)
}

/// Remove a leg from the session.
pub(super) async fn handle_remove_leg(
&mut self,
Expand Down
Loading
Loading