mirror of
https://github.com/VallierDev/uu-remote-linux.git
synced 2026-11-16 08:50:40 +01:00
Port mapping: advertise and accept 256 KB data-channel messages
The viewer assumed webrtc-rs's missing a=max-message-size meant 64 KB and refused larger port-mapping frames, stalling uploads after the first frame. Advertise 262144 in the answer sent to the viewer and vendor webrtc with a 256 KB data-channel receive buffer (upstream u16::MAX). Verified with the official Mac viewer: 20 MB upload 10 MB/s, 20 MB download and 5 concurrent downloads, checksums match. Docs and v0.1.4 notes. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
fe991c4a7d
commit
ebef246486
102 files changed
+25202
-5
No files matched your search
@@ -174,6 +174,13 @@ started a second full host server instead, so check that a subcommand exists in
|
||||
`operation_result`. Host root is shown as ":/" (此电脑); home is "~/".
|
||||
- Terminal: BINARY channel, RPC 28 check_env → 24; frames `"TERM"`, version 1, type (enum+1), 2 flag bytes,
|
||||
session u32 LE, length u32 LE, payload; JSON `{cols,rows,shell,option}`.
|
||||
- Port mapping (capture_type 9): Message 27 `PortMappingFrame {1 session_id, 2 rule_id, 3 stream_id, 4 type, 5 payload}`
|
||||
on FILE_DATA_CHANNEL only. Types SYN=0, FIN=1, DATA=2, SYN_ACK=3, DATA_ACK=4 (ignored by both sides). SYN payload
|
||||
JSON `{"version","target_host","target_port"}` → connect → SYN_ACK `{"version","ok","error"}`; DATA raw bytes both ways.
|
||||
Echo session/rule/stream ids with their original wire types. The viewer does not support TCP half-close.
|
||||
- SCTP message size: webrtc-rs omits `a=max-message-size`, so the viewer assumes 64 KB and refuses larger messages; the
|
||||
answer sent to the viewer adds `a=max-message-size:262144` (only the sent copy — webrtc-rs rejects a modified local
|
||||
description) and `vendor/webrtc` raises the data-channel receive buffer from 65535 to 262144 bytes.
|
||||
- Cursor shape = Message 15 SystemStateChange field 2. Audio: the viewer always offers an Opus m-line.
|
||||
- Login API: `/api/v1/device/windows/init` → device_id; `/qrcode/gen/login`; long-poll
|
||||
`/qrcode/login/status` (1 wait, 2 scanned, 4 confirmed); `/login/by_qrcode` → user token. QR expires after
|
||||
|
||||
Generated
-2
@@ -2782,8 +2782,6 @@ dependencies = [
|
||||
[[package]]
|
||||
name = "webrtc"
|
||||
version = "0.10.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "1fbdf025f0fa62f4bf252b2fb0cff0a04d3eac2021c440096649e62f4e48553d"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"async-trait",
|
||||
|
||||
@@ -47,3 +47,5 @@ cc = "1.0"
|
||||
|
||||
[patch.crates-io]
|
||||
webrtc-dtls = { path = "vendor/webrtc-dtls" }
|
||||
# Larger data-channel receive buffer (see vendor/webrtc/src/data_channel/mod.rs).
|
||||
webrtc = { path = "vendor/webrtc" }
|
||||
+2
-1
@@ -44,6 +44,7 @@
|
||||
| Lock after remote session | Stored on the host, so it still applies after reconnecting |
|
||||
| Mute host while controlled | Host speakers are muted while the viewer still hears the sound; the previous mute state is restored afterwards |
|
||||
| System actions | Lock, show desktop, task manager (system monitor), reboot, shut down |
|
||||
| Port mapping | The official "port mapping" tool: forwards a local port on the viewer to an address reachable from the Linux host (e.g. 127.0.0.1:22); `UU_PORT_MAPPING=0` disables it |
|
||||
| Reconnects | Every tool window has its own connection; they do not disturb each other |
|
||||
|
||||
## Supported Linux desktops
|
||||
@@ -77,7 +78,6 @@ permission; the permission is remembered once granted.
|
||||
| Microphone (viewer audio played on the host) | Not implemented (needs a virtual sound card) |
|
||||
| Plugins such as the WoW queue notifier | Not supported; the client is told that no plugins exist |
|
||||
| Access before login (greeter / no user logged in) | Not supported; only an already logged-in desktop session can be controlled |
|
||||
| Port mapping | Code exists, not yet accepted |
|
||||
| Relay connections on restrictive networks | Uses the ICE servers provided by the UU cloud; complex network setups are not thoroughly tested |
|
||||
| Acting as a viewer (controlling other machines from Linux) | Out of scope |
|
||||
|
||||
@@ -161,6 +161,7 @@ Common environment variables:
|
||||
| `UU_FFMPEG_ROOT` | Use FFmpeg from this prefix |
|
||||
| `UU_AUDIO=0` | Disable sound; `UU_AUDIO_SOURCE` picks the PulseAudio source |
|
||||
| `UU_LOGIN_WINDOW=0` | Do not open the login window automatically when credentials are missing |
|
||||
| `UU_PORT_MAPPING=0` | Disable port mapping (the official host's controlled-side switch) |
|
||||
|
||||
Host settings such as "lock after remote session" and "mute host" are stored in
|
||||
`~/.config/uuremote/host_settings.json`.
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
| 远程结束后自动锁屏 | 设置保存在本机,重连后依然生效 |
|
||||
| 被控端静音运行 | 主机扬声器静音,控制端照常能听到声音;结束后恢复原来的音量设置 |
|
||||
| 系统操作 | 锁屏、显示桌面、任务管理器(系统监视器)、重启、关机 |
|
||||
| 端口映射 | 官方「端口映射」工具:把控制端本地端口转发到 Linux 能访问到的地址(如 127.0.0.1:22);`UU_PORT_MAPPING=0` 可关闭 |
|
||||
| 多次重连 | 每个工具窗口独立连接,互不影响 |
|
||||
|
||||
## 支持的 Linux 桌面
|
||||
@@ -71,7 +72,6 @@ Wayland 下的限制:只支持单屏、固定分辨率;portal 后端暂不
|
||||
| 麦克风(控制端声音传到被控端) | 未实现(需要虚拟声卡) |
|
||||
| 魔兽世界排队提醒等插件 | 不支持,会明确告诉客户端「无插件」 |
|
||||
| 登录前(登录界面 / 无人登录)访问 | 不支持,只能控制已登录的桌面会话 |
|
||||
| 端口映射 | 有代码,未经验收 |
|
||||
| 跨运营商 / 受限网络的中继连接 | 已接入官方下发的 ICE 服务器,但复杂网络环境未充分测试 |
|
||||
| 作为控制端(在 Linux 上控制别的电脑) | 不在本项目范围 |
|
||||
|
||||
@@ -154,6 +154,7 @@ journalctl --user -u uuremote-native.service -f # 看到 availability=Some("re
|
||||
| `UU_FFMPEG_ROOT` | 使用指定目录下的 FFmpeg |
|
||||
| `UU_AUDIO=0` | 关闭声音转发;`UU_AUDIO_SOURCE` 指定 PulseAudio 采集源 |
|
||||
| `UU_LOGIN_WINDOW=0` | 凭证缺失时不自动弹出登录窗口 |
|
||||
| `UU_PORT_MAPPING=0` | 关闭端口映射(对应官方被控端的开关) |
|
||||
|
||||
「远程结束后自动锁屏」「静音运行」等设置保存在 `~/.config/uuremote/host_settings.json`。
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
新增端口映射。/ Adds port mapping.
|
||||
|
||||
### 新增 / Added
|
||||
- **端口映射**:支持官方客户端的「端口映射」工具。在控制端添加规则(本地端口 → 目标地址:端口),即可把控制端本地端口转发到
|
||||
Linux 被控端能访问到的地址,例如 `127.0.0.1:22`(SSH)或局域网里的其他服务。上传、下载、多连接并发均已用官方 Mac 客户端验收。
|
||||
设置 `UU_PORT_MAPPING=0` 可关闭。
|
||||
**Port mapping**: the official "port mapping" tool now works — forward a local port on the viewer to any address reachable
|
||||
from the Linux host (e.g. `127.0.0.1:22`). Upload, download and concurrent streams verified with the official Mac client.
|
||||
`UU_PORT_MAPPING=0` disables it.
|
||||
|
||||
### 修复 / Fixed
|
||||
- 数据通道单条消息上限从 64 KB 提升到 256 KB(与官方被控端一致)。此前控制端发送的大于 64 KB 的消息会被拒发,导致上传卡住。
|
||||
Data-channel messages up to 256 KB are now accepted (as the official host advertises); larger viewer messages were refused before.
|
||||
- 画质/帧率/分辨率切换时,旧编码器的帧可能插到新编码器的关键帧之后,导致画面花屏(#5,感谢 @BLACKIELF)。
|
||||
Encoder restart ordering on quality/fps/resolution changes (#5, thanks @BLACKIELF).
|
||||
|
||||
### 其他 / Other
|
||||
- 可选的进程内编码(`--features inproc-av`,默认关闭;Release 安装包不受影响)(#6,感谢 @ferstar)。
|
||||
Optional in-process encoding (`--features inproc-av`, off by default) (#6, thanks @ferstar).
|
||||
|
||||
### 已知问题 / Known issues
|
||||
- 控制端不支持 TCP 半关闭(发送方关闭写方向后会直接关闭整条连接);SSH、HTTP 等常见协议不受影响。
|
||||
The viewer does not support TCP half-close; common protocols such as SSH and HTTP are unaffected.
|
||||
- Wayland 仍为实验性;portal 下「Linux → 控制端」剪贴板和约 20 分钟后的云端断开仍在排查。
|
||||
|
||||
### 下载 / Download
|
||||
`uu-remote-linux-v0.1.4-x86_64-linux.tar.gz`:X11 版可执行文件(x86_64,glibc ≥ 2.35)。
|
||||
|
||||
**非官方项目,与网易无关。** / **Unofficial, not affiliated with NetEase.**
|
||||
+31
-1
@@ -865,7 +865,11 @@ impl WebRtcSession {
|
||||
.set_local_description(answer.clone())
|
||||
.await
|
||||
.map_err(|e| format!("Set local desc failed: {}", e))?;
|
||||
Ok(answer.sdp)
|
||||
// webrtc-rs omits a=max-message-size, so the viewer (libwebrtc) assumes 64 KB and refuses
|
||||
// larger data-channel messages (port-mapping uploads stalled after the first frame).
|
||||
// Only the copy sent to the viewer is amended: webrtc-rs rejects a local description that
|
||||
// differs from the answer it generated. Our receive buffer (1 MB) accepts 256 KB messages.
|
||||
Ok(with_max_message_size(&answer.sdp))
|
||||
}
|
||||
|
||||
/// 接收远端 ICE Candidate
|
||||
@@ -906,6 +910,23 @@ impl WebRtcSession {
|
||||
}
|
||||
|
||||
|
||||
/// Max SCTP message size we accept (libwebrtc's default, as the official host advertises).
|
||||
const MAX_MESSAGE_SIZE: usize = 262_144;
|
||||
|
||||
/// Adds `a=max-message-size` after `a=sctp-port` in the data-channel section if missing.
|
||||
fn with_max_message_size(sdp: &str) -> String {
|
||||
if sdp.contains("a=max-message-size:") { return sdp.to_owned(); }
|
||||
let eol = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
|
||||
let mut out = String::with_capacity(sdp.len() + 32);
|
||||
for line in sdp.split_inclusive('\n') {
|
||||
out.push_str(line);
|
||||
if line.trim_end().starts_with("a=sctp-port:") {
|
||||
out.push_str(&format!("a=max-message-size:{MAX_MESSAGE_SIZE}{eol}"));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn negotiated_bundle_media(sdp: &str) -> Option<(String, u16)> {
|
||||
let preferred: Vec<&str> = sdp.lines().find_map(|l| l.strip_prefix("a=group:BUNDLE "))?
|
||||
.split_whitespace().collect();
|
||||
@@ -931,6 +952,15 @@ fn negotiated_bundle_media(sdp: &str) -> Option<(String, u16)> {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::negotiated_bundle_media;
|
||||
#[test]
|
||||
fn advertises_max_message_size_once_in_the_data_channel_section() {
|
||||
use super::with_max_message_size;
|
||||
let sdp = "v=0\r\nm=application 9 UDP/DTLS/SCTP webrtc-datachannel\r\na=sctp-port:5000\r\n";
|
||||
let out = with_max_message_size(sdp);
|
||||
assert!(out.contains("a=sctp-port:5000\r\na=max-message-size:262144\r\n"));
|
||||
assert_eq!(with_max_message_size(&out), out);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_rejected_audio_for_ice_transport() {
|
||||
let sdp = "a=group:BUNDLE 1 2\r\nm=audio 0 RTP 0\r\na=mid:0\r\nm=video 9 RTP 98\r\na=mid:1\r\nm=application 9 SCTP 0\r\na=mid:2\r\n";
|
||||
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
{"v":1}
|
||||
Vendored
+6
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"git": {
|
||||
"sha1": "502671d8023141b70051e85aaf8748e86ea64dfd"
|
||||
},
|
||||
"path_in_vcs": "webrtc"
|
||||
}
|
||||
Vendored
+236
@@ -0,0 +1,236 @@
|
||||
# webrtc-rs changelog
|
||||
|
||||
## Unreleased
|
||||
|
||||
## v0.7.0
|
||||
|
||||
* Added support for insecure/deprecated signature verification algorithms, opt in via `SettingsEngine::allow_insecure_verification_algorithm` [#342](https://github.com/webrtc-rs/webrtc/pull/342).
|
||||
* Make RTCRtpCodecCapability::payloader_for_codec public API [#349](https://github.com/webrtc-rs/webrtc/pull/349).
|
||||
* Fixed a panic in `calculate_rtt_ms` [#350](https://github.com/webrtc-rs/webrtc/pull/350).
|
||||
* Fixed `TrackRemote` missing at least the first, sometimes more, RTP packet during probing. [#387](https://github.com/webrtc-rs/webrtc/pull/387)
|
||||
|
||||
### Breaking changes
|
||||
|
||||
* Change `RTCPeerConnection::on_track` callback signature to `|track: Arc<TrackRemote>, receiver: Arc<RTCRtpReceiver>, transceiver: Arc<RTCRtpTransceiver>|` [#355](https://github.com/webrtc-rs/webrtc/pull/355).
|
||||
|
||||
* Change `RTCRtpSender::new` signature to `|receive_mtu: usize, track: Option<Arc<dyn TrackLocal + Send + Sync>>, transport: Arc<RTCDtlsTransport>, media_engine: Arc<MediaEngine>, interceptor: Arc<dyn Interceptor + Send + Sync>, start_paused: bool,|` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `API::new_rtp_sender` signature to `|&self, track: Option<Arc<dyn TrackLocal + Send + Sync>>, transport: Arc<RTCDtlsTransport>, interceptor: Arc<dyn Interceptor + Send + Sync>,|` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCRtpTransceiver::sender` signature to `|&self| -> Arc<RTCRtpSender>` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCRtpTransceiver::set_sender_track` signature to `|self: &Arc<Self>, sender: Arc<RTCRtpSender>, track: Option<Arc<dyn TrackLocal + Send + Sync>>,|` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCRtpTransceiver::set_sender` signature to `|self: &Arc<Self>, s: Arc<RTCRtpSender>|` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCRtpTransceiver::receiver` signature to `|&self| -> Arc<RTCRtpReceiver>` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCRtpTransceiver::set_receiver` signature to `|&self, r: Arc<RTCRtpReceiver>|` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCPeerConnection::add_transceiver_from_kind` signature to `|&self, kind: RTPCodecType, init: Option<RTCRtpTransceiverInit>,|`, `RTCRtpTransceiver::RTCRtpSender` сreated without a track [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCPeerConnection::add_transceiver_from_track` signature to `|&self, track: Arc<dyn TrackLocal + Send + Sync>, init: Option<RTCRtpTransceiverInit>,|` [#377](https://github.com/webrtc-rs/webrtc/pull/377).
|
||||
|
||||
* Change `RTCPeerConnection::mid` return signature to `Option<String>` [#375](https://github.com/webrtc-rs/webrtc/pull/375).
|
||||
|
||||
* Make functions non-async [#402](https://github.com/webrtc-rs/webrtc/pull/402):
|
||||
- `MediaEngine`:
|
||||
- `get_codecs_by_kind`;
|
||||
- `get_rtp_parameters_by_kind`.
|
||||
- `RTCRtpTransceiver`:
|
||||
- `sender`;
|
||||
- `set_sender`;
|
||||
- `receiver`.
|
||||
- `RTPReceiverInternal`:
|
||||
- `set_transceiver_codecs`;
|
||||
- `get_codecs`.
|
||||
- `RTCRtpSender`:
|
||||
- `set_rtp_transceiver`;
|
||||
- `has_sent`.
|
||||
- `TrackRemote`:
|
||||
- `id`;
|
||||
- `set_id`;
|
||||
- `stream_id`;
|
||||
- `set_stream_id`;
|
||||
- `msid`;
|
||||
- `codec`;
|
||||
- `set_codec`;
|
||||
- `params`;
|
||||
- `set_params`;
|
||||
- `onmute`;
|
||||
- `onunmute`.
|
||||
|
||||
* Change `RTPReader::read` signature to `|&self, buf: &mut [u8], attributes: &Attributes| -> Result<(rtp::packet::Packet, Attributes)>` [#450](https://github.com/webrtc-rs/webrtc/pull/450).
|
||||
|
||||
* Change `RTCPReader::read` signature to `|&self, buf: &mut [u8], attributes: &Attributes| -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)>` [#450](https://github.com/webrtc-rs/webrtc/pull/450).
|
||||
|
||||
## v0.6.0
|
||||
|
||||
* Added more stats to `RemoteInboundRTPStats` and `RemoteOutboundRTPStats` [#282](https://github.com/webrtc-rs/webrtc/pull/282) by [@k0nserv](https://github.com/k0nserv).
|
||||
* Don't register `video/rtx` codecs in `MediaEngine::register_default_codecs`. These weren't actually support and prevented RTX in the existing RTP stream from being used. Long term we should support RTX via this method, this is tracked in [#295](https://github.com/webrtc-rs/webrtc/issues/295). [#294 Remove video/rtx codecs](https://github.com/webrtc-rs/webrtc/pull/294) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* Add IP filter to WebRTC `SettingEngine` [#306](https://github.com/webrtc-rs/webrtc/pull/306)
|
||||
* Stop sequence numbers from increasing in `TrackLocalStaticSample` while the bound `RTCRtpSender` have
|
||||
directions that should not send. [#316](https://github.com/webrtc-rs/webrtc/pull/316)
|
||||
* Add support for a mime type "audio/telephone-event" (rfc4733) [#322](https://github.com/webrtc-rs/webrtc/pull/322)
|
||||
* Fixed a panic that would sometimes happen when collecting stats. [#327](https://github.com/webrtc-rs/webrtc/pull/327) by [@k0nserv](https://github.com/k0nserv).
|
||||
* Added new extension marshaller/unmarshaller for VideoOrientation, and made marshallers serializable via serde [#331](https://github.com/webrtc-rs/webrtc/pull/331) [#332](https://github.com/webrtc-rs/webrtc/pull/332)
|
||||
* Updated minimum rust version to `1.60.0`
|
||||
* Added a new `write_rtp_with_extensions` method to `TrackLocalStaticSample` and `TrackLocalStaticRTP`. [#336](https://github.com/webrtc-rs/webrtc/pull/336) by [@k0nserv](https://github.com/k0nserv).
|
||||
* Added a new `sample_writer` helper to `TrackLocalStaticSample`. [#336](https://github.com/webrtc-rs/webrtc/pull/336) by [@k0nserv](https://github.com/k0nserv).
|
||||
* Increased minimum versions for sub-dependencies:
|
||||
* `webrtc-data` version to `0.6.0`.
|
||||
* `webrtc-ice` version to `0.9.0`.
|
||||
* `webrtc-media` version to `0.5.0`.
|
||||
* `webrtc-sctp` version to `0.7.0`.
|
||||
* `webrtc-util` version to `0.7.0`.
|
||||
|
||||
### Breaking changes
|
||||
|
||||
* Allowed one single direction for extmap matching. [#321](https://github.com/webrtc-rs/webrtc/pull/321). API change for `MediaEngine::register_header_extension`.
|
||||
* Removed support for Plan-B. All major implementations of WebRTC now support unified and continuing support for plan-b is an undue maintenance burden when unified can be used. See [“Unified Plan” Transition Guide (JavaScript)](https://docs.google.com/document/d/1-ZfikoUtoJa9k-GZG1daN0BU3IjIanQ_JSscHxQesvU/) for an overview of the changes required to migrate. [#320](https://github.com/webrtc-rs/webrtc/pull/320) by [@algesten](https://github.com/algesten).
|
||||
* Removed 2nd argument from `RTCCertificate::from_pem` and guard it with `pem` feature [#333]
|
||||
* Renamed `RTCCertificate::pem` to `serialize_pem` and guard it with `pem` feature [#333]
|
||||
* Removed `RTCCertificate::expires` [#333]
|
||||
* `RTCCertificate::get_fingerprints` no longer returns `Result` [#333]
|
||||
* Make functions non-async [#338](https://github.com/webrtc-rs/webrtc/pull/338):
|
||||
- `RTCDataChannel`:
|
||||
- `on_open`;
|
||||
- `on_close`;
|
||||
- `on_message`;
|
||||
- `on_error`.
|
||||
- `RTCDtlsTransport::on_state_change`;
|
||||
- `RTCIceCandidate::to_json`;
|
||||
- `RTCIceGatherer`:
|
||||
- `on_local_candidate`;
|
||||
- `on_state_change`;
|
||||
- `on_gathering_complete`.
|
||||
- `RTCIceTransport`:
|
||||
- `get_selected_candidate_pair`;
|
||||
- `on_selected_candidate_pair_change`;
|
||||
- `on_connection_state_change`.
|
||||
- `RTCPeerConnection`:
|
||||
- `on_signaling_state_change`;
|
||||
- `on_data_channel`;
|
||||
- `on_negotiation_needed`;
|
||||
- `on_ice_candidate`;
|
||||
- `on_ice_gathering_state_change`;
|
||||
- `on_track`;
|
||||
- `on_ice_connection_state_change`;
|
||||
- `on_peer_connection_state_change`.
|
||||
- `RTCSctpTransport`:
|
||||
- `on_error`;
|
||||
- `on_data_channel`;
|
||||
- `on_data_channel_opened`.
|
||||
|
||||
[#333]: https://github.com/webrtc-rs/webrtc/pull/333
|
||||
|
||||
## v0.5.1
|
||||
|
||||
* Promote agent lock in ice_gather.rs create_agent() to top level of the function to avoid a race condition. [#290 Promote create_agent lock to top of function, to avoid race condition](https://github.com/webrtc-rs/webrtc/pull/290) contributed by [efer-ms](https://github.com/efer-ms)
|
||||
|
||||
## v0.5.0
|
||||
|
||||
### Changes
|
||||
|
||||
#### Breaking changes
|
||||
|
||||
* The serialized format for `RTCIceCandidateInit` has changed to match what the specification i.e. keys are camelCase. [#153 Make RTCIceCandidateInit conform to WebRTC spec](https://github.com/webrtc-rs/webrtc/pull/153) contributed by [jmatss](https://github.com/jmatss).
|
||||
* Improved robustness when proposing RTP extension IDs and handling of collisions in these. This change is only breaking if you have assumed anything about the nature of these extension IDs. [#154 Fix RTP extension id collision](https://github.com/webrtc-rs/webrtc/pull/154) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* Transceivers will now not stop when either or both directions are disabled. That is, applying and SDP with `a=inactive` will not stop the transceiver, instead attached senders and receivers will pause. A transceiver can be resurrected by setting direction back to e.g. `a=sendrecv`. The desired direction can be controlled with the newly introduced public method `set_direction` on `RTCRtpTransceiver`.
|
||||
* [#201 Handle inactive transceivers more correctly](https://github.com/webrtc-rs/webrtc/pull/201) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#210 Rework transceiver direction support further](https://github.com/webrtc-rs/webrtc/pull/210) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#214 set_direction add missing Send + Sync bound](https://github.com/webrtc-rs/webrtc/pull/214) contributed by [algesten](https://github.com/algesten)
|
||||
* [#213 set_direction add missing Sync bound](https://github.com/webrtc-rs/webrtc/pull/213) contributed by [algesten](https://github.com/algesten)
|
||||
* [#212 Public RTCRtpTransceiver::set_direction](https://github.com/webrtc-rs/webrtc/pull/212) contributed by [algesten](https://github.com/algesten)
|
||||
* [#268 Fix current direction update when applying answer](https://github.com/webrtc-rs/webrtc/pull/268) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#236 Pause RTP writing if direction indicates it](https://github.com/webrtc-rs/webrtc/pull/236) contributed by [algesten](https://github.com/algesten)
|
||||
* Generated the `a=msid` line for `m=` line sections according to the specification. This might be break remote peers that relied on the previous, incorrect, behaviour. This also fixes a bug where an endless negotiation loop could happen. [#217 Correct msid handling for RtpSender](https://github.com/webrtc-rs/webrtc/pull/217) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* Improve data channel id negotiation. We've slightly adjust the public interface for creating pre-negotiated data channels. Instead of a separate `negotiated: Option<bool>` and `id: Option<u16>` in `RTCDataChannelInit` there's now a more idiomatic `negotiated: Option<u16>`. If you have a pre-negotiated data channel simply set `negotiated: Some(id)` when creating the data channel.
|
||||
* [#237 Fix datachannel id setting for 0.5.0 release](https://github.com/webrtc-rs/webrtc/pull/237) contributed by [stuqdog](https://github.com/stuqdog)
|
||||
* [#229 Revert "base id updating on whether it's been negotiated, not on its …](https://github.com/webrtc-rs/webrtc/pull/229) contributed by [melekes](https://github.com/melekes)
|
||||
|
||||
* [#226 base id updating on whether it's been finalized, not on its value](https://github.com/webrtc-rs/webrtc/pull/226) contributed by [stuqdog](https://github.com/stuqdog)
|
||||
|
||||
|
||||
#### Other improvememnts
|
||||
|
||||
We made various improvements and fixes since 0.4.0, including merging all subcrates into a single git repo. The old crate repos are archived and all development will now happen in https://github.com/webrtc-rs/webrtc/.
|
||||
|
||||
* We now provide stats reporting via the standardized `RTCPeerConnection::get_stats` method.
|
||||
* [#277 Implement Remote Inbound Stats](https://github.com/webrtc-rs/webrtc/pull/277) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#220 Make stats types pub so they can be used directly](https://github.com/webrtc-rs/webrtc/pull/220) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#225 Add RTP Stats to stats report](https://github.com/webrtc-rs/webrtc/pull/225) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#189 Serialize stats](https://github.com/webrtc-rs/webrtc/pull/189) contributed by [sax](https://github.com/sax)
|
||||
* [#180 Get stats from peer connection](https://github.com/webrtc-rs/webrtc/pull/180) contributed by [sax](https://github.com/sax)
|
||||
|
||||
* [#278 Fix async-global-executor](https://github.com/webrtc-rs/webrtc/pull/278) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#276 relax regex version requirement](https://github.com/webrtc-rs/webrtc/pull/276) contributed by [melekes](https://github.com/melekes)
|
||||
* [#244 Update README.md instructions after monorepo merge](https://github.com/webrtc-rs/webrtc/pull/244) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#241 move profile to workspace](https://github.com/webrtc-rs/webrtc/pull/241) contributed by [xnorpx](https://github.com/xnorpx)
|
||||
* [#240 Increase timeout to "fix" test breaking](https://github.com/webrtc-rs/webrtc/pull/240) contributed by [algesten](https://github.com/algesten)
|
||||
* [#239 One repo (again)](https://github.com/webrtc-rs/webrtc/pull/239) contributed by [algesten](https://github.com/algesten)
|
||||
* [#234 Fix recent clippy lints](https://github.com/webrtc-rs/webrtc/pull/234) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#224 update call to DataChannel::accept as per data pr #14](https://github.com/webrtc-rs/webrtc/pull/224) contributed by [melekes](https://github.com/melekes)
|
||||
* [#223 dtls_transport: always set remote certificate](https://github.com/webrtc-rs/webrtc/pull/223) contributed by [melekes](https://github.com/melekes)
|
||||
* [#216 Lower case mime types for comparison in fmpt lines](https://github.com/webrtc-rs/webrtc/pull/216) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#211 Helper to trigger negotiation_needed](https://github.com/webrtc-rs/webrtc/pull/211) contributed by [algesten](https://github.com/algesten)
|
||||
* [#209 MID generator feature](https://github.com/webrtc-rs/webrtc/pull/209) contributed by [algesten](https://github.com/algesten)
|
||||
* [#208 update deps + loosen some requirements](https://github.com/webrtc-rs/webrtc/pull/208) contributed by [melekes](https://github.com/melekes)
|
||||
* [#205 data_channel: handle stream EOF](https://github.com/webrtc-rs/webrtc/pull/205) contributed by [melekes](https://github.com/melekes)
|
||||
* [#204 [peer_connection] allow persistent certificates](https://github.com/webrtc-rs/webrtc/pull/204) contributed by [melekes](https://github.com/melekes)
|
||||
* [#202 bugfix-Udp connection not close (reopen #174) #195](https://github.com/webrtc-rs/webrtc/pull/202) contributed by [shiqifeng2000](https://github.com/shiqifeng2000)
|
||||
* [#199 Upgrade ICE to 0.7.0](https://github.com/webrtc-rs/webrtc/pull/199) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#194 Add AV1 MimeType and RtpCodecParameters](https://github.com/webrtc-rs/webrtc/pull/194) contributed by [billylindeman](https://github.com/billylindeman)
|
||||
* [#188 Improve operations debuggability](https://github.com/webrtc-rs/webrtc/pull/188) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#187 Fix SDP for rejected tracks to conform to RFC](https://github.com/webrtc-rs/webrtc/pull/187) contributed by [k0nserv](https://github.com/k0nserv)
|
||||
* [#185 Adding some debug and display traits](https://github.com/webrtc-rs/webrtc/pull/185) contributed by [sevensidedmarble](https://github.com/sevensidedmarble)
|
||||
* [#179 Fix example names in README](https://github.com/webrtc-rs/webrtc/pull/179) contributed by [ethagnawl](https://github.com/ethagnawl)
|
||||
* [#176 Time overflow armv7 workaround](https://github.com/webrtc-rs/webrtc/pull/176) contributed by [frjol](https://github.com/frjol)
|
||||
* [#171 close DTLS conn upon err](https://github.com/webrtc-rs/webrtc/pull/171) contributed by [melekes](https://github.com/melekes)
|
||||
* [#170 always start sctp](https://github.com/webrtc-rs/webrtc/pull/170) contributed by [melekes](https://github.com/melekes)
|
||||
* [#167 Add offer/answer/pranswer constructors for RTCSessionDescription](https://github.com/webrtc-rs/webrtc/pull/167) contributed by [sax](https://github.com/sax)
|
||||
|
||||
#### Subcrate updates
|
||||
|
||||
The various sub-crates have been updated as follows:
|
||||
|
||||
* util: 0.5.3 => 0.6.0
|
||||
* sdp: 0.5.1 => 0.5.2
|
||||
* mdns: 0.4.2 => 0.5.0
|
||||
* stun: 0.4.2 => 0.4.3
|
||||
* turn: 0.5.3 => 0.6.0
|
||||
* ice: 0.6.4 => 0.8.0
|
||||
* dtls: 0.5.2 => 0.6.0
|
||||
* rtcp: 0.6.5 => 0.7.0
|
||||
* rtp: 0.6.5 => 0.6.7
|
||||
* srtp: 0.8.9 => 0.9.0
|
||||
* scpt: 0.4.3 => 0.6.1
|
||||
* data: 0.3.3 => 0.5.0
|
||||
* interceptor: 0.7.6 => 0.8.0
|
||||
* media: 0.4.5 => 0.4.7
|
||||
|
||||
Their respective change logs are found in the old, now archived, repositories and within their respective `CHANGELOG.md` files in the monorepo.
|
||||
|
||||
### Contributors
|
||||
|
||||
A big thanks to all the contributors that have made this release happen:
|
||||
|
||||
* [morajabi](https://github.com/morajabi)
|
||||
* [sax](https://github.com/sax)
|
||||
* [ethagnawl](https://github.com/ethagnawl)
|
||||
* [xnorpx](https://github.com/xnorpx)
|
||||
* [frjol](https://github.com/frjol)
|
||||
* [algesten](https://github.com/algesten)
|
||||
* [shiqifeng2000](https://github.com/shiqifeng2000)
|
||||
* [billylindeman](https://github.com/billylindeman)
|
||||
* [sevensidedmarble](https://github.com/sevensidedmarble)
|
||||
* [k0nserv](https://github.com/k0nserv)
|
||||
* [stuqdog](https://github.com/stuqdog)
|
||||
* [neonphog](https://github.com/neonphog)
|
||||
* [melekes](https://github.com/melekes)
|
||||
* [jmatss](https://github.com/jmatss)
|
||||
|
||||
|
||||
## Prior to 0.5.0
|
||||
|
||||
Before 0.5.0 there was no changelog, previous changes are sometimes, but not always, available in the [GitHub Releases](https://github.com/webrtc-rs/webrtc/releases).
|
||||
Vendored
+161
@@ -0,0 +1,161 @@
|
||||
# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO
|
||||
#
|
||||
# When uploading crates to the registry Cargo will automatically
|
||||
# "normalize" Cargo.toml files for maximal compatibility
|
||||
# with all versions of Cargo and also rewrite `path` dependencies
|
||||
# to registry (e.g., crates.io) dependencies.
|
||||
#
|
||||
# If you are reading this file be aware that the original Cargo.toml
|
||||
# will likely look very different (and much more reasonable).
|
||||
# See Cargo.toml.orig for the original contents.
|
||||
|
||||
[package]
|
||||
edition = "2021"
|
||||
name = "webrtc"
|
||||
version = "0.10.1"
|
||||
authors = ["Rain Liu <[email protected]>"]
|
||||
description = "A pure Rust implementation of WebRTC API"
|
||||
homepage = "https://webrtc.rs"
|
||||
documentation = "https://docs.rs/webrtc"
|
||||
readme = "README.md"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/webrtc-rs/webrtc"
|
||||
|
||||
[dependencies.arc-swap]
|
||||
version = "1"
|
||||
|
||||
[dependencies.async-trait]
|
||||
version = "0.1"
|
||||
|
||||
[dependencies.bytes]
|
||||
version = "1"
|
||||
|
||||
[dependencies.cfg-if]
|
||||
version = "1"
|
||||
|
||||
[dependencies.data]
|
||||
version = "0.8.1"
|
||||
package = "webrtc-data"
|
||||
|
||||
[dependencies.dtls]
|
||||
version = "0.9.0"
|
||||
package = "webrtc-dtls"
|
||||
|
||||
[dependencies.hex]
|
||||
version = "0.4"
|
||||
|
||||
[dependencies.ice]
|
||||
version = "0.10.1"
|
||||
package = "webrtc-ice"
|
||||
|
||||
[dependencies.interceptor]
|
||||
version = "0.11.0"
|
||||
|
||||
[dependencies.lazy_static]
|
||||
version = "1.4"
|
||||
|
||||
[dependencies.log]
|
||||
version = "0.4"
|
||||
|
||||
[dependencies.mdns]
|
||||
version = "0.6.1"
|
||||
package = "webrtc-mdns"
|
||||
|
||||
[dependencies.media]
|
||||
version = "0.7.1"
|
||||
package = "webrtc-media"
|
||||
|
||||
[dependencies.pem]
|
||||
version = "3"
|
||||
optional = true
|
||||
|
||||
[dependencies.rand]
|
||||
version = "0.8"
|
||||
|
||||
[dependencies.rcgen]
|
||||
version = "0.11"
|
||||
features = [
|
||||
"pem",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[dependencies.regex]
|
||||
version = "1.9.5"
|
||||
|
||||
[dependencies.ring]
|
||||
version = "0.17"
|
||||
|
||||
[dependencies.rtcp]
|
||||
version = "0.10.1"
|
||||
|
||||
[dependencies.rtp]
|
||||
version = "0.10.0"
|
||||
|
||||
[dependencies.rustls]
|
||||
version = "0.21"
|
||||
features = ["dangerous_configuration"]
|
||||
|
||||
[dependencies.sctp]
|
||||
version = "0.9.1"
|
||||
package = "webrtc-sctp"
|
||||
|
||||
[dependencies.sdp]
|
||||
version = "0.6.1"
|
||||
|
||||
[dependencies.serde]
|
||||
version = "1"
|
||||
features = ["derive"]
|
||||
|
||||
[dependencies.serde_json]
|
||||
version = "1"
|
||||
|
||||
[dependencies.sha2]
|
||||
version = "0.10"
|
||||
|
||||
[dependencies.smol_str]
|
||||
version = "0.2"
|
||||
features = ["serde"]
|
||||
|
||||
[dependencies.srtp]
|
||||
version = "0.12.0"
|
||||
package = "webrtc-srtp"
|
||||
|
||||
[dependencies.stun]
|
||||
version = "0.5.1"
|
||||
|
||||
[dependencies.thiserror]
|
||||
version = "1"
|
||||
|
||||
[dependencies.time]
|
||||
version = "0.3"
|
||||
|
||||
[dependencies.tokio]
|
||||
version = "1.32.0"
|
||||
features = ["full"]
|
||||
|
||||
[dependencies.turn]
|
||||
version = "0.7.1"
|
||||
|
||||
[dependencies.url]
|
||||
version = "2"
|
||||
|
||||
[dependencies.util]
|
||||
version = "0.8.1"
|
||||
package = "webrtc-util"
|
||||
|
||||
[dependencies.waitgroup]
|
||||
version = "0.1"
|
||||
|
||||
[dev-dependencies.env_logger]
|
||||
version = "0.10"
|
||||
|
||||
[dev-dependencies.tokio-test]
|
||||
version = "0.4"
|
||||
|
||||
[features]
|
||||
openssl = ["srtp/openssl"]
|
||||
pem = [
|
||||
"dep:pem",
|
||||
"dtls/pem",
|
||||
]
|
||||
vendored-openssl = ["srtp/vendored-openssl"]
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
[package]
|
||||
name = "webrtc"
|
||||
version = "0.10.1"
|
||||
authors = ["Rain Liu <[email protected]>"]
|
||||
edition = "2021"
|
||||
description = "A pure Rust implementation of WebRTC API"
|
||||
license = "MIT OR Apache-2.0"
|
||||
documentation = "https://docs.rs/webrtc"
|
||||
homepage = "https://webrtc.rs"
|
||||
repository = "https://github.com/webrtc-rs/webrtc"
|
||||
readme = "../README.md"
|
||||
|
||||
[dependencies]
|
||||
data = { version = "0.8.1", path = "../data", package = "webrtc-data" }
|
||||
dtls = { version = "0.9.0", path = "../dtls", package = "webrtc-dtls" }
|
||||
ice = { version = "0.10.1", path = "../ice", package = "webrtc-ice" }
|
||||
interceptor = { version = "0.11.0", path = "../interceptor" }
|
||||
mdns = { version = "0.6.1", path = "../mdns", package = "webrtc-mdns" }
|
||||
media = { version = "0.7.1", path = "../media", package = "webrtc-media" }
|
||||
rtcp = { version = "0.10.1", path = "../rtcp" }
|
||||
rtp = { version = "0.10.0", path = "../rtp" }
|
||||
sctp = { version = "0.9.1", path = "../sctp", package = "webrtc-sctp" }
|
||||
sdp = { version = "0.6.1", path = "../sdp" }
|
||||
srtp = { version = "0.12.0", path = "../srtp", package = "webrtc-srtp" }
|
||||
stun = { version = "0.5.1", path = "../stun" }
|
||||
turn = { version = "0.7.1", path = "../turn" }
|
||||
util = { version = "0.8.1", path = "../util", package = "webrtc-util" }
|
||||
|
||||
arc-swap = "1"
|
||||
tokio = { version = "1.32.0", features = ["full"] }
|
||||
log = "0.4"
|
||||
async-trait = "0.1"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
rand = "0.8"
|
||||
bytes = "1"
|
||||
thiserror = "1"
|
||||
waitgroup = "0.1"
|
||||
regex = "1.9.5"
|
||||
smol_str = { version = "0.2", features = ["serde"] }
|
||||
url = "2"
|
||||
rustls = { version = "0.21", features = ["dangerous_configuration"]}
|
||||
rcgen = { version = "0.11", features = ["pem", "x509-parser"]}
|
||||
ring = "0.17"
|
||||
sha2 = "0.10"
|
||||
lazy_static = "1.4"
|
||||
hex = "0.4"
|
||||
pem = { version = "3", optional = true }
|
||||
time = "0.3"
|
||||
cfg-if = "1"
|
||||
|
||||
[dev-dependencies]
|
||||
tokio-test = "0.4"
|
||||
env_logger = "0.10"
|
||||
|
||||
[features]
|
||||
pem = ["dep:pem", "dtls/pem"]
|
||||
openssl = ["srtp/openssl"]
|
||||
vendored-openssl = ["srtp/vendored-openssl"]
|
||||
Vendored
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Vendored
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 WebRTC.rs
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
Vendored
+144
@@ -0,0 +1,144 @@
|
||||
<h1 align="center">
|
||||
<a href="https://webrtc.rs"><img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/webrtc.rs.png" alt="WebRTC.rs"></a>
|
||||
<br>
|
||||
</h1>
|
||||
<p align="center">
|
||||
<a href="https://github.com/webrtc-rs/webrtc/actions">
|
||||
<img src="https://github.com/webrtc-rs/webrtc/workflows/cargo/badge.svg?branch=master">
|
||||
</a>
|
||||
<a href="https://codecov.io/gh/webrtc-rs/webrtc">
|
||||
<img src="https://codecov.io/gh/webrtc-rs/webrtc/branch/master/graph/badge.svg">
|
||||
</a>
|
||||
<a href="https://deps.rs/repo/github/webrtc-rs/webrtc">
|
||||
<img src="https://deps.rs/repo/github/webrtc-rs/webrtc/status.svg">
|
||||
</a>
|
||||
<a href="https://crates.io/crates/webrtc">
|
||||
<img src="https://img.shields.io/crates/v/webrtc.svg">
|
||||
</a>
|
||||
<a href="https://docs.rs/webrtc">
|
||||
<img src="https://docs.rs/webrtc/badge.svg">
|
||||
</a>
|
||||
<a href="https://doc.rust-lang.org/1.6.0/complement-project-faq.html#why-dual-mitasl2-license">
|
||||
<img src="https://img.shields.io/badge/license-MIT%2FApache--2.0-blue" alt="License: MIT/Apache 2.0">
|
||||
</a>
|
||||
<a href="https://discord.gg/4Ju8UHdXMs">
|
||||
<img src="https://img.shields.io/discord/800204819540869120?logo=discord" alt="Discord">
|
||||
</a>
|
||||
<a href="https://twitter.com/WebRTCrs">
|
||||
<img src="https://img.shields.io/twitter/url/https/twitter.com/webrtcrs.svg?style=social&label=%40WebRTCrs" alt="Twitter">
|
||||
</a>
|
||||
</p>
|
||||
<p align="center">
|
||||
A pure Rust implementation of WebRTC stack. Rewrite <a href="http://Pion.ly">Pion</a> WebRTC stack in Rust
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<strong>Sponsored with 💖 by</strong><br>
|
||||
</p>
|
||||
<p align="center">
|
||||
<strong>Gold Sponsors:</strong><br>
|
||||
<a href="https://www.parity.io/" target="_blank">
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/parity.png" style="height:75px;" alt="Parity Technologies">
|
||||
</a><br>
|
||||
<p align="center">
|
||||
<strong>Silver Sponsors:</strong><br>
|
||||
<a href="https://getstream.io/video/voice-calling/?utm_source=https://github.com/webrtc-rs/webrtc&utm_medium=sponsorship&utm_content=&utm_campaign=webrtcRepo_July2023_video_klmh22" target="_blank">
|
||||
<img src="https://stream-blog-v2.imgix.net/blog/wp-content/uploads/f7401112f41742c4e173c30d4f318cb8/stream_logo_white.png?h=50" alt="Stream Chat">
|
||||
</a><br>
|
||||
<a href="https://kittycad.io/" target="_blank">
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/KittyCAD.png" alt="KittyCAD">
|
||||
</a><br>
|
||||
<strong>Bronze Sponsors:</strong><br>
|
||||
<a href="https://www.embark-studios.com/" target="_blank"><img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/embark.jpg" alt="embark"></a><br>
|
||||
<a href="https://github.com/AdrianEddy" target="_blank">AdrianEddy</a><br>
|
||||
</p>
|
||||
|
||||
<details>
|
||||
<summary><b>Table of Content</b></summary>
|
||||
|
||||
- [Overview](#overview)
|
||||
- [Features](#features)
|
||||
- [Building](#building)
|
||||
- [Toolchain](#toolchain)
|
||||
- [Monorepo Setup](#monorepo-setup)
|
||||
- [Open Source License](#open-source-license)
|
||||
- [Contributing](#contributing)
|
||||
|
||||
</details>
|
||||
|
||||
## Overview
|
||||
|
||||
WebRTC.rs is a pure Rust implementation of WebRTC stack, which rewrites <a href="https://github.com/pion/webrtc/releases/tag/v3.1.5">Pion</a> stack in Rust.
|
||||
This project is still in active and early development stage, please refer to the [Roadmap](https://github.com/webrtc-rs/webrtc/issues/1) to track the major milestones and releases.
|
||||
[Examples](https://github.com/webrtc-rs/webrtc/blob/master/examples/examples/README.md) provide code samples to show how to use webrtc-rs to build media and data channel applications.
|
||||
|
||||
## Features
|
||||
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">WebRTC<a href="https://crates.io/crates/webrtc"><img src="https://img.shields.io/crates/v/webrtc.svg"></a>
|
||||
<br>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">Media<a href="https://crates.io/crates/webrtc-media"><img src="https://img.shields.io/crates/v/webrtc-media.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">Interceptor<a href="https://crates.io/crates/interceptor"><img src="https://img.shields.io/crates/v/interceptor.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">Data<a href="https://crates.io/crates/webrtc-data"><img src="https://img.shields.io/crates/v/webrtc-data.svg"></a>
|
||||
<br>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">RTP<a href="https://crates.io/crates/rtp"><img src="https://img.shields.io/crates/v/rtp.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">RTCP<a href="https://crates.io/crates/rtcp"><img src="https://img.shields.io/crates/v/rtcp.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">SRTP<a href="https://crates.io/crates/webrtc-srtp"><img src="https://img.shields.io/crates/v/webrtc-srtp.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">SCTP<a href="https://crates.io/crates/webrtc-sctp"><img src="https://img.shields.io/crates/v/webrtc-sctp.svg"></a>
|
||||
<br>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">DTLS<a href="https://crates.io/crates/webrtc-dtls"><img src="https://img.shields.io/crates/v/webrtc-dtls.svg"></a>
|
||||
<br>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">mDNS<a href="https://crates.io/crates/webrtc-mdns"><img src="https://img.shields.io/crates/v/webrtc-mdns.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">STUN<a href="https://crates.io/crates/stun"><img src="https://img.shields.io/crates/v/stun.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">TURN<a href="https://crates.io/crates/turn"><img src="https://img.shields.io/crates/v/turn.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">ICE<a href="https://crates.io/crates/webrtc-ice"><img src="https://img.shields.io/crates/v/webrtc-ice.svg"></a>
|
||||
<br>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">SDP<a href="https://crates.io/crates/sdp"><img src="https://img.shields.io/crates/v/sdp.svg"></a>
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/check.png">Util<a href="https://crates.io/crates/webrtc-util"><img src="https://img.shields.io/crates/v/webrtc-util.svg"></a>
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/webrtc_crates_dep_graph.png" alt="WebRTC Crates Dependency Graph">
|
||||
</p>
|
||||
<p align="center">
|
||||
<img src="https://raw.githubusercontent.com/webrtc-rs/webrtc/master/doc/webrtc_stack.png" alt="WebRTC Stack">
|
||||
</p>
|
||||
|
||||
## Building
|
||||
|
||||
### Toolchain
|
||||
|
||||
**Minimum Supported Rust Version:** `1.65.0`
|
||||
|
||||
Our minimum supported rust version(MSRV) policy is to support versions of the compiler released within the last six months. We don't eagerly bump the minimum version we support, instead the minimum will be bumped on a needed by needed basis, usually because downstream dependencies force us to.
|
||||
|
||||
**Note:** Changes to the minimum supported version are not consider breaking from a [semver](https://semver.org/) perspective.
|
||||
|
||||
### Monorepo Setup
|
||||
|
||||
All webrtc dependent crates and examples are included in this repository at the top level in a Cargo workspace.
|
||||
|
||||
To build all webrtc examples:
|
||||
|
||||
```shell
|
||||
cd examples
|
||||
cargo test # build all examples (maybe very slow)
|
||||
#[ or just build single example (much faster)
|
||||
cargo build --example play-from-disk-vpx # build play-from-disk-vpx example only
|
||||
cargo build --example play-from-disk-h264 # build play-from-disk-h264 example only
|
||||
#...
|
||||
#]
|
||||
```
|
||||
|
||||
To build webrtc crate:
|
||||
|
||||
```shell
|
||||
cargo build [or clippy or test or fmt]
|
||||
```
|
||||
|
||||
## Open Source License
|
||||
|
||||
Dual licensing under both MIT and Apache-2.0 is the currently accepted standard by the Rust language community and has been used for both the compiler and many public libraries since (see <https://doc.rust-lang.org/1.6.0/complement-project-faq.html#why-dual-mitasl2-license>). In order to match the community standards, webrtc-rs is using the dual MIT+Apache-2.0 license.
|
||||
|
||||
## Contributing
|
||||
|
||||
Contributors or Pull Requests are Welcome!!!
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_api() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
s.detach_data_channels();
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
|
||||
let api = APIBuilder::new()
|
||||
.with_setting_engine(s)
|
||||
.with_media_engine(m)
|
||||
.build();
|
||||
|
||||
assert!(
|
||||
api.setting_engine.detach.data_channels,
|
||||
"Failed to set settings engine"
|
||||
);
|
||||
assert!(
|
||||
!api.media_engine.audio_codecs.is_empty(),
|
||||
"Failed to set media engine"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/*TODO:
|
||||
use super::*;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::Arc;
|
||||
|
||||
use interceptor::mock::mock_builder::MockBuilder;
|
||||
use interceptor::mock::mock_interceptor::MockInterceptor;
|
||||
use interceptor::stream_info::StreamInfo;
|
||||
use interceptor::{Attributes, Interceptor, RTPWriter, RTPWriterFn};
|
||||
|
||||
// E2E test of the features of Interceptors
|
||||
// * Assert an extension can be set on an outbound packet
|
||||
// * Assert an extension can be read on an outbound packet
|
||||
// * Assert that attributes set by an interceptor are returned to the Reader
|
||||
#[tokio::test]
|
||||
async fn test_peer_connection_interceptor() -> Result<()> {
|
||||
let create_pc = || async {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
|
||||
let mut ir = Registry::new();
|
||||
|
||||
let BindLocalStreamFn = |info: &StreamInfo,
|
||||
writer: Arc<dyn RTPWriter + Send + Sync>|
|
||||
-> Pin<
|
||||
Box<dyn Future<Output = Arc<dyn RTPWriter + Send + Sync>> + Send + Sync>,
|
||||
> {
|
||||
let writer2 = Arc::clone(&writer);
|
||||
Box::pin(async move {
|
||||
Arc::new(RTPWriterFn(Box::new(
|
||||
move |in_pkt: &rtp::packet::Packet,
|
||||
attributes: &Attributes|
|
||||
-> Pin<
|
||||
Box<
|
||||
dyn Future<Output = std::result::Result<usize, interceptor::Error>>
|
||||
+ Send
|
||||
+ Sync,
|
||||
>,
|
||||
> {
|
||||
let writer3 = Arc::clone(&writer2);
|
||||
let a = attributes.clone();
|
||||
// set extension on outgoing packet
|
||||
let mut out_pkt = in_pkt.clone();
|
||||
out_pkt.header.extension = true;
|
||||
out_pkt.header.extension_profile = 0xBEDE;
|
||||
|
||||
Box::pin(async move {
|
||||
out_pkt
|
||||
.header
|
||||
.set_extension(2, Bytes::from_static(b"foo"))?;
|
||||
//writer3.write(&out_pkt, &a).await
|
||||
Ok(0)
|
||||
})
|
||||
},
|
||||
))) as Arc<dyn RTPWriter + Send + Sync>
|
||||
})
|
||||
};
|
||||
|
||||
BindRemoteStreamFn: func(_ *interceptor.StreamInfo, reader interceptor.RTPReader) interceptor.RTPReader {
|
||||
return interceptor.RTPReaderFunc(func(b []byte, a interceptor.Attributes) (int, interceptor.Attributes, error) {
|
||||
if a == nil {
|
||||
a = interceptor.Attributes{}
|
||||
}
|
||||
|
||||
a.Set("attribute", "value")
|
||||
return reader.Read(b, a)
|
||||
})
|
||||
},
|
||||
let mock_builder = Box::new(MockBuilder {
|
||||
build:
|
||||
Box::new(
|
||||
|_: &str| -> std::result::Result<
|
||||
Arc<dyn Interceptor + Send + Sync>,
|
||||
interceptor::Error,
|
||||
> {
|
||||
Ok(Arc::new(MockInterceptor {
|
||||
..Default::default()
|
||||
}))
|
||||
},
|
||||
),
|
||||
});
|
||||
let mock_builder = MockBuilder::new(
|
||||
|_: &str| -> std::result::Result<
|
||||
Arc<dyn Interceptor + Send + Sync>,
|
||||
interceptor::Error,
|
||||
> {
|
||||
Ok(Arc::new(MockInterceptor {
|
||||
..Default::default()
|
||||
}))
|
||||
},
|
||||
);
|
||||
ir.add(Box::new(mock_builder));
|
||||
|
||||
let api = APIBuilder::new()
|
||||
.with_media_engine(m)
|
||||
.with_interceptor_registry(ir)
|
||||
.build();
|
||||
api.new_peer_connection(RTCConfiguration::default()).await
|
||||
};
|
||||
|
||||
let offerer = create_pc().await?;
|
||||
let answerer = create_pc().await?;
|
||||
|
||||
track, err := NewTrackLocalStaticSample(RTPCodecCapability{MimeType: MimeTypeVP8}, "video", "pion")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = offerer.AddTrack(track)
|
||||
assert.NoError(t, err)
|
||||
|
||||
seenRTP, seenRTPCancel := context.WithCancel(context.Background())
|
||||
answerer.OnTrack(func(track *TrackRemote, receiver *RTPReceiver) {
|
||||
p, attributes, readErr := track.ReadRTP()
|
||||
assert.NoError(t, readErr)
|
||||
|
||||
assert.Equal(t, p.Extension, true)
|
||||
assert.Equal(t, "foo", string(p.GetExtension(2)))
|
||||
assert.Equal(t, "value", attributes.Get("attribute"))
|
||||
|
||||
seenRTPCancel()
|
||||
})
|
||||
|
||||
assert.NoError(t, signalPair(offerer, answerer))
|
||||
|
||||
func() {
|
||||
ticker := time.NewTicker(time.Millisecond * 20)
|
||||
for {
|
||||
select {
|
||||
case <-seenRTP.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
assert.NoError(t, track.WriteSample(media.Sample{Data: []byte{0x00}, Duration: time.Second}))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
closePairNow(t, offerer, answerer)
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
func Test_Interceptor_BindUnbind(t *testing.T) {
|
||||
lim := test.TimeOut(time.Second * 10)
|
||||
defer lim.Stop()
|
||||
|
||||
report := test.CheckRoutines(t)
|
||||
defer report()
|
||||
|
||||
m := &MediaEngine{}
|
||||
assert.NoError(t, m.RegisterDefaultCodecs())
|
||||
|
||||
var (
|
||||
cntBindRTCPReader uint32
|
||||
cntBindRTCPWriter uint32
|
||||
cntBindLocalStream uint32
|
||||
cntUnbindLocalStream uint32
|
||||
cntBindRemoteStream uint32
|
||||
cntUnbindRemoteStream uint32
|
||||
cntClose uint32
|
||||
)
|
||||
mockInterceptor := &mock_interceptor.Interceptor{
|
||||
BindRTCPReaderFn: func(reader interceptor.RTCPReader) interceptor.RTCPReader {
|
||||
atomic.AddUint32(&cntBindRTCPReader, 1)
|
||||
return reader
|
||||
},
|
||||
BindRTCPWriterFn: func(writer interceptor.RTCPWriter) interceptor.RTCPWriter {
|
||||
atomic.AddUint32(&cntBindRTCPWriter, 1)
|
||||
return writer
|
||||
},
|
||||
BindLocalStreamFn: func(i *interceptor.StreamInfo, writer interceptor.RTPWriter) interceptor.RTPWriter {
|
||||
atomic.AddUint32(&cntBindLocalStream, 1)
|
||||
return writer
|
||||
},
|
||||
UnbindLocalStreamFn: func(i *interceptor.StreamInfo) {
|
||||
atomic.AddUint32(&cntUnbindLocalStream, 1)
|
||||
},
|
||||
BindRemoteStreamFn: func(i *interceptor.StreamInfo, reader interceptor.RTPReader) interceptor.RTPReader {
|
||||
atomic.AddUint32(&cntBindRemoteStream, 1)
|
||||
return reader
|
||||
},
|
||||
UnbindRemoteStreamFn: func(i *interceptor.StreamInfo) {
|
||||
atomic.AddUint32(&cntUnbindRemoteStream, 1)
|
||||
},
|
||||
CloseFn: func() error {
|
||||
atomic.AddUint32(&cntClose, 1)
|
||||
return nil
|
||||
},
|
||||
}
|
||||
ir := &interceptor.Registry{}
|
||||
ir.Add(&mock_interceptor.Factory{
|
||||
NewInterceptorFn: func(_ string) (interceptor.Interceptor, error) { return mockInterceptor, nil },
|
||||
})
|
||||
|
||||
sender, receiver, err := NewAPI(WithMediaEngine(m), WithInterceptorRegistry(ir)).newPair(Configuration{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
track, err := NewTrackLocalStaticSample(RTPCodecCapability{MimeType: MimeTypeVP8}, "video", "pion")
|
||||
assert.NoError(t, err)
|
||||
|
||||
_, err = sender.AddTrack(track)
|
||||
assert.NoError(t, err)
|
||||
|
||||
receiverReady, receiverReadyFn := context.WithCancel(context.Background())
|
||||
receiver.OnTrack(func(track *TrackRemote, _ *RTPReceiver) {
|
||||
_, _, readErr := track.ReadRTP()
|
||||
assert.NoError(t, readErr)
|
||||
receiverReadyFn()
|
||||
})
|
||||
|
||||
assert.NoError(t, signalPair(sender, receiver))
|
||||
|
||||
ticker := time.NewTicker(time.Millisecond * 20)
|
||||
defer ticker.Stop()
|
||||
func() {
|
||||
for {
|
||||
select {
|
||||
case <-receiverReady.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
// Send packet to make receiver track actual creates RTPReceiver.
|
||||
assert.NoError(t, track.WriteSample(media.Sample{Data: []byte{0xAA}, Duration: time.Second}))
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
closePairNow(t, sender, receiver)
|
||||
|
||||
// Bind/UnbindLocal/RemoteStream should be called from one side.
|
||||
if cnt := atomic.LoadUint32(&cntBindLocalStream); cnt != 1 {
|
||||
t.Errorf("BindLocalStreamFn is expected to be called once, but called %d times", cnt)
|
||||
}
|
||||
if cnt := atomic.LoadUint32(&cntUnbindLocalStream); cnt != 1 {
|
||||
t.Errorf("UnbindLocalStreamFn is expected to be called once, but called %d times", cnt)
|
||||
}
|
||||
if cnt := atomic.LoadUint32(&cntBindRemoteStream); cnt != 1 {
|
||||
t.Errorf("BindRemoteStreamFn is expected to be called once, but called %d times", cnt)
|
||||
}
|
||||
if cnt := atomic.LoadUint32(&cntUnbindRemoteStream); cnt != 1 {
|
||||
t.Errorf("UnbindRemoteStreamFn is expected to be called once, but called %d times", cnt)
|
||||
}
|
||||
|
||||
// BindRTCPWriter/Reader and Close should be called from both side.
|
||||
if cnt := atomic.LoadUint32(&cntBindRTCPWriter); cnt != 2 {
|
||||
t.Errorf("BindRTCPWriterFn is expected to be called twice, but called %d times", cnt)
|
||||
}
|
||||
if cnt := atomic.LoadUint32(&cntBindRTCPReader); cnt != 2 {
|
||||
t.Errorf("BindRTCPReaderFn is expected to be called twice, but called %d times", cnt)
|
||||
}
|
||||
if cnt := atomic.LoadUint32(&cntClose); cnt != 2 {
|
||||
t.Errorf("CloseFn is expected to be called twice, but called %d times", cnt)
|
||||
}
|
||||
}
|
||||
|
||||
func Test_InterceptorRegistry_Build(t *testing.T) {
|
||||
registryBuildCount := 0
|
||||
|
||||
ir := &interceptor.Registry{}
|
||||
ir.Add(&mock_interceptor.Factory{
|
||||
NewInterceptorFn: func(_ string) (interceptor.Interceptor, error) {
|
||||
registryBuildCount++
|
||||
return &interceptor.NoOp{}, nil
|
||||
},
|
||||
})
|
||||
|
||||
peerConnectionA, err := NewAPI(WithInterceptorRegistry(ir)).NewPeerConnection(Configuration{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
peerConnectionB, err := NewAPI(WithInterceptorRegistry(ir)).NewPeerConnection(Configuration{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 2, registryBuildCount)
|
||||
closePairNow(t, peerConnectionA, peerConnectionB)
|
||||
}
|
||||
*/
|
||||
+171
@@ -0,0 +1,171 @@
|
||||
#[cfg(test)]
|
||||
mod interceptor_registry_test;
|
||||
|
||||
use interceptor::nack::generator::Generator;
|
||||
use interceptor::nack::responder::Responder;
|
||||
use interceptor::registry::Registry;
|
||||
use interceptor::report::receiver::ReceiverReport;
|
||||
use interceptor::report::sender::SenderReport;
|
||||
use interceptor::twcc::receiver::Receiver;
|
||||
use interceptor::twcc::sender::Sender;
|
||||
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::error::Result;
|
||||
use crate::rtp_transceiver::rtp_codec::{RTCRtpHeaderExtensionCapability, RTPCodecType};
|
||||
use crate::rtp_transceiver::{RTCPFeedback, TYPE_RTCP_FB_TRANSPORT_CC};
|
||||
|
||||
/// register_default_interceptors will register some useful interceptors.
|
||||
/// If you want to customize which interceptors are loaded, you should copy the
|
||||
/// code from this method and remove unwanted interceptors.
|
||||
pub fn register_default_interceptors(
|
||||
mut registry: Registry,
|
||||
media_engine: &mut MediaEngine,
|
||||
) -> Result<Registry> {
|
||||
registry = configure_nack(registry, media_engine);
|
||||
|
||||
registry = configure_rtcp_reports(registry);
|
||||
|
||||
registry = configure_twcc_receiver_only(registry, media_engine)?;
|
||||
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
/// configure_rtcp_reports will setup everything necessary for generating Sender and Receiver Reports
|
||||
pub fn configure_rtcp_reports(mut registry: Registry) -> Registry {
|
||||
let receiver = Box::new(ReceiverReport::builder());
|
||||
let sender = Box::new(SenderReport::builder());
|
||||
registry.add(receiver);
|
||||
registry.add(sender);
|
||||
registry
|
||||
}
|
||||
|
||||
/// configure_nack will setup everything necessary for handling generating/responding to nack messages.
|
||||
pub fn configure_nack(mut registry: Registry, media_engine: &mut MediaEngine) -> Registry {
|
||||
media_engine.register_feedback(
|
||||
RTCPFeedback {
|
||||
typ: "nack".to_owned(),
|
||||
parameter: "".to_owned(),
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
);
|
||||
media_engine.register_feedback(
|
||||
RTCPFeedback {
|
||||
typ: "nack".to_owned(),
|
||||
parameter: "pli".to_owned(),
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
);
|
||||
|
||||
let generator = Box::new(Generator::builder());
|
||||
let responder = Box::new(Responder::builder());
|
||||
registry.add(responder);
|
||||
registry.add(generator);
|
||||
registry
|
||||
}
|
||||
|
||||
/// configure_twcc will setup everything necessary for adding
|
||||
/// a TWCC header extension to outgoing RTP packets and generating TWCC reports.
|
||||
pub fn configure_twcc(mut registry: Registry, media_engine: &mut MediaEngine) -> Result<Registry> {
|
||||
media_engine.register_feedback(
|
||||
RTCPFeedback {
|
||||
typ: TYPE_RTCP_FB_TRANSPORT_CC.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
);
|
||||
media_engine.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::TRANSPORT_CC_URI.to_owned(),
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
None,
|
||||
)?;
|
||||
|
||||
media_engine.register_feedback(
|
||||
RTCPFeedback {
|
||||
typ: TYPE_RTCP_FB_TRANSPORT_CC.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
);
|
||||
media_engine.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::TRANSPORT_CC_URI.to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
|
||||
let sender = Box::new(Sender::builder());
|
||||
let receiver = Box::new(Receiver::builder());
|
||||
registry.add(sender);
|
||||
registry.add(receiver);
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
/// configure_twcc_sender will setup everything necessary for adding
|
||||
/// a TWCC header extension to outgoing RTP packets. This will allow the remote peer to generate TWCC reports.
|
||||
pub fn configure_twcc_sender_only(
|
||||
mut registry: Registry,
|
||||
media_engine: &mut MediaEngine,
|
||||
) -> Result<Registry> {
|
||||
media_engine.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::TRANSPORT_CC_URI.to_owned(),
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
None,
|
||||
)?;
|
||||
|
||||
media_engine.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::TRANSPORT_CC_URI.to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
|
||||
let sender = Box::new(Sender::builder());
|
||||
registry.add(sender);
|
||||
Ok(registry)
|
||||
}
|
||||
|
||||
/// configure_twcc_receiver will setup everything necessary for generating TWCC reports.
|
||||
pub fn configure_twcc_receiver_only(
|
||||
mut registry: Registry,
|
||||
media_engine: &mut MediaEngine,
|
||||
) -> Result<Registry> {
|
||||
media_engine.register_feedback(
|
||||
RTCPFeedback {
|
||||
typ: TYPE_RTCP_FB_TRANSPORT_CC.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
);
|
||||
media_engine.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::TRANSPORT_CC_URI.to_owned(),
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
None,
|
||||
)?;
|
||||
|
||||
media_engine.register_feedback(
|
||||
RTCPFeedback {
|
||||
typ: TYPE_RTCP_FB_TRANSPORT_CC.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
);
|
||||
media_engine.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::TRANSPORT_CC_URI.to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
|
||||
let receiver = Box::new(Receiver::builder());
|
||||
registry.add(receiver);
|
||||
Ok(registry)
|
||||
}
|
||||
@@ -0,0 +1,780 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use regex::Regex;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::MIME_TYPE_OPUS;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_opus_case() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
pc.add_transceiver_from_kind(RTPCodecType::Audio, None)
|
||||
.await?;
|
||||
|
||||
let offer = pc.create_offer(None).await?;
|
||||
|
||||
let re = Regex::new(r"(?m)^a=rtpmap:\d+ opus/48000/2").unwrap();
|
||||
assert!(re.is_match(offer.sdp.as_str()));
|
||||
|
||||
pc.close().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_video_case() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
pc.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let offer = pc.create_offer(None).await?;
|
||||
|
||||
let re = Regex::new(r"(?m)^a=rtpmap:\d+ H264/90000").unwrap();
|
||||
assert!(re.is_match(offer.sdp.as_str()));
|
||||
let re = Regex::new(r"(?m)^a=rtpmap:\d+ VP8/90000").unwrap();
|
||||
assert!(re.is_match(offer.sdp.as_str()));
|
||||
let re = Regex::new(r"(?m)^a=rtpmap:\d+ VP9/90000").unwrap();
|
||||
assert!(re.is_match(offer.sdp.as_str()));
|
||||
|
||||
pc.close().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_media_engine_remote_description() -> Result<()> {
|
||||
let must_parse = |raw: &str| -> Result<SessionDescription> {
|
||||
let mut reader = Cursor::new(raw.as_bytes());
|
||||
Ok(SessionDescription::unmarshal(&mut reader)?)
|
||||
};
|
||||
|
||||
//"No Media"
|
||||
{
|
||||
const NO_MEDIA: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.update_from_remote_description(&must_parse(NO_MEDIA)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(!m.negotiated_audio.load(Ordering::SeqCst));
|
||||
}
|
||||
|
||||
//"Enable Opus"
|
||||
{
|
||||
const OPUS_SAME_PAYLOAD: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 111
|
||||
a=rtpmap:111 opus/48000/2
|
||||
a=fmtp:111 minptime=10; useinbandfec=1
|
||||
";
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.update_from_remote_description(&must_parse(OPUS_SAME_PAYLOAD)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let (opus_codec, _) = m.get_codec_by_payload(111).await?;
|
||||
assert_eq!(opus_codec.capability.mime_type, MIME_TYPE_OPUS);
|
||||
}
|
||||
|
||||
//"Change Payload Type"
|
||||
{
|
||||
const OPUS_SAME_PAYLOAD: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 112
|
||||
a=rtpmap:112 opus/48000/2
|
||||
a=fmtp:112 minptime=10; useinbandfec=1
|
||||
";
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.update_from_remote_description(&must_parse(OPUS_SAME_PAYLOAD)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let result = m.get_codec_by_payload(111).await;
|
||||
assert!(result.is_err());
|
||||
|
||||
let (opus_codec, _) = m.get_codec_by_payload(112).await?;
|
||||
assert_eq!(opus_codec.capability.mime_type, MIME_TYPE_OPUS);
|
||||
}
|
||||
|
||||
//"Case Insensitive"
|
||||
{
|
||||
const OPUS_UPCASE: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 111
|
||||
a=rtpmap:111 OPUS/48000/2
|
||||
a=fmtp:111 minptime=10; useinbandfec=1
|
||||
";
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.update_from_remote_description(&must_parse(OPUS_UPCASE)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let (opus_codec, _) = m.get_codec_by_payload(111).await?;
|
||||
assert_eq!(opus_codec.capability.mime_type, "audio/OPUS");
|
||||
}
|
||||
|
||||
//"Handle different fmtp"
|
||||
{
|
||||
const OPUS_NO_FMTP: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 111
|
||||
a=rtpmap:111 opus/48000/2
|
||||
";
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.update_from_remote_description(&must_parse(OPUS_NO_FMTP)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let (opus_codec, _) = m.get_codec_by_payload(111).await?;
|
||||
assert_eq!(opus_codec.capability.mime_type, MIME_TYPE_OPUS);
|
||||
}
|
||||
|
||||
//"Header Extensions"
|
||||
{
|
||||
const HEADER_EXTENSIONS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 111
|
||||
a=extmap:7 urn:ietf:params:rtp-hdrext:sdes:mid
|
||||
a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id
|
||||
a=rtpmap:111 opus/48000/2
|
||||
";
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
for extension in [
|
||||
"urn:ietf:params:rtp-hdrext:sdes:mid",
|
||||
"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",
|
||||
] {
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: extension.to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
|
||||
m.update_from_remote_description(&must_parse(HEADER_EXTENSIONS)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let (abs_id, abs_audio_enabled, abs_video_enabled) = m
|
||||
.get_header_extension_id(RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::ABS_SEND_TIME_URI.to_owned(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(abs_id, 0);
|
||||
assert!(!abs_audio_enabled);
|
||||
assert!(!abs_video_enabled);
|
||||
|
||||
let (mid_id, mid_audio_enabled, mid_video_enabled) = m
|
||||
.get_header_extension_id(RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::SDES_MID_URI.to_owned(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(mid_id, 7);
|
||||
assert!(mid_audio_enabled);
|
||||
assert!(!mid_video_enabled);
|
||||
}
|
||||
|
||||
//"Prefers exact codec matches"
|
||||
{
|
||||
const PROFILE_LEVELS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=video 60323 UDP/TLS/RTP/SAVPF 96 98
|
||||
a=rtpmap:96 H264/90000
|
||||
a=fmtp:96 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f
|
||||
a=rtpmap:98 H264/90000
|
||||
a=fmtp:98 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
|
||||
.to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 127,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
m.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
|
||||
.await?;
|
||||
|
||||
assert!(m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(!m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let (supported_h264, _) = m.get_codec_by_payload(98).await?;
|
||||
assert_eq!(supported_h264.capability.mime_type, MIME_TYPE_H264);
|
||||
|
||||
assert!(m.get_codec_by_payload(96).await.is_err());
|
||||
}
|
||||
|
||||
//"Does not match when fmtpline is set and does not match"
|
||||
{
|
||||
const PROFILE_LEVELS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=video 60323 UDP/TLS/RTP/SAVPF 96 98
|
||||
a=rtpmap:96 H264/90000
|
||||
a=fmtp:96 level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640c1f
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
|
||||
.to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 127,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
assert!(m
|
||||
.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
|
||||
.await
|
||||
.is_err());
|
||||
|
||||
assert!(m.get_codec_by_payload(96).await.is_err());
|
||||
}
|
||||
|
||||
//"Matches when fmtpline is not set in offer, but exists in mediaengine"
|
||||
{
|
||||
const PROFILE_LEVELS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=video 60323 UDP/TLS/RTP/SAVPF 96
|
||||
a=rtpmap:96 VP9/90000
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=0".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 98,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
|
||||
.await?;
|
||||
|
||||
assert!(m.negotiated_video.load(Ordering::SeqCst));
|
||||
|
||||
m.get_codec_by_payload(96).await?;
|
||||
}
|
||||
|
||||
//"Matches when fmtpline exists in neither"
|
||||
{
|
||||
const PROFILE_LEVELS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=video 60323 UDP/TLS/RTP/SAVPF 96
|
||||
a=rtpmap:96 VP8/90000
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
|
||||
.await?;
|
||||
|
||||
assert!(m.negotiated_video.load(Ordering::SeqCst));
|
||||
|
||||
m.get_codec_by_payload(96).await?;
|
||||
}
|
||||
|
||||
//"Matches when rtx apt for exact match codec"
|
||||
{
|
||||
const PROFILE_LEVELS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=video 60323 UDP/TLS/RTP/SAVPF 94 96 97
|
||||
a=rtpmap:94 VP8/90000
|
||||
a=rtpmap:96 VP9/90000
|
||||
a=fmtp:96 profile-id=2
|
||||
a=rtpmap:97 rtx/90000
|
||||
a=fmtp:97 apt=96
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 94,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=2".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: "video/rtx".to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "apt=96".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 97,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
|
||||
.await?;
|
||||
|
||||
assert!(m.negotiated_video.load(Ordering::SeqCst));
|
||||
|
||||
m.get_codec_by_payload(97).await?;
|
||||
}
|
||||
|
||||
//"Matches when rtx apt for partial match codec"
|
||||
{
|
||||
const PROFILE_LEVELS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=video 60323 UDP/TLS/RTP/SAVPF 94 96 97
|
||||
a=rtpmap:94 VP8/90000
|
||||
a=rtpmap:96 VP9/90000
|
||||
a=fmtp:96 profile-id=2
|
||||
a=rtpmap:97 rtx/90000
|
||||
a=fmtp:97 apt=96
|
||||
";
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 94,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=1".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: "video/rtx".to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "apt=96".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 97,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
)?;
|
||||
|
||||
m.update_from_remote_description(&must_parse(PROFILE_LEVELS)?)
|
||||
.await?;
|
||||
|
||||
assert!(m.negotiated_video.load(Ordering::SeqCst));
|
||||
|
||||
if let Err(err) = m.get_codec_by_payload(97).await {
|
||||
assert_eq!(err, Error::ErrCodecNotFound);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_media_engine_header_extension_direction() -> Result<()> {
|
||||
let register_codec = |m: &mut MediaEngine| -> Result<()> {
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_owned(),
|
||||
clock_rate: 48000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
)
|
||||
};
|
||||
|
||||
//"No Direction"
|
||||
{
|
||||
let mut m = MediaEngine::default();
|
||||
register_codec(&mut m)?;
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: "webrtc-header-test".to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
|
||||
let params =
|
||||
m.get_rtp_parameters_by_kind(RTPCodecType::Audio, RTCRtpTransceiverDirection::Recvonly);
|
||||
|
||||
assert_eq!(params.header_extensions.len(), 1);
|
||||
}
|
||||
|
||||
//"Same Direction"
|
||||
{
|
||||
let mut m = MediaEngine::default();
|
||||
register_codec(&mut m)?;
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: "webrtc-header-test".to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
Some(RTCRtpTransceiverDirection::Recvonly),
|
||||
)?;
|
||||
|
||||
let params =
|
||||
m.get_rtp_parameters_by_kind(RTPCodecType::Audio, RTCRtpTransceiverDirection::Recvonly);
|
||||
|
||||
assert_eq!(params.header_extensions.len(), 1);
|
||||
}
|
||||
|
||||
//"Different Direction"
|
||||
{
|
||||
let mut m = MediaEngine::default();
|
||||
register_codec(&mut m)?;
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: "webrtc-header-test".to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
Some(RTCRtpTransceiverDirection::Sendonly),
|
||||
)?;
|
||||
|
||||
let params =
|
||||
m.get_rtp_parameters_by_kind(RTPCodecType::Audio, RTCRtpTransceiverDirection::Recvonly);
|
||||
|
||||
assert_eq!(params.header_extensions.len(), 0);
|
||||
}
|
||||
|
||||
//"No direction and inactive"
|
||||
{
|
||||
let mut m = MediaEngine::default();
|
||||
register_codec(&mut m)?;
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: "webrtc-header-test".to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
|
||||
let params =
|
||||
m.get_rtp_parameters_by_kind(RTPCodecType::Audio, RTCRtpTransceiverDirection::Inactive);
|
||||
|
||||
assert_eq!(params.header_extensions.len(), 1);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// If a user attempts to register a codec twice we should just discard duplicate calls
|
||||
#[tokio::test]
|
||||
async fn test_media_engine_double_register() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_owned(),
|
||||
clock_rate: 48000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
)?;
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_owned(),
|
||||
clock_rate: 48000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
)?;
|
||||
|
||||
assert_eq!(m.audio_codecs.len(), 1);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn validate(m: &MediaEngine) -> Result<()> {
|
||||
m.update_header_extension(2, "test-extension", RTPCodecType::Audio)
|
||||
.await?;
|
||||
|
||||
let (id, audio_negotiated, video_negotiated) = m
|
||||
.get_header_extension_id(RTCRtpHeaderExtensionCapability {
|
||||
uri: "test-extension".to_owned(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(id, 2);
|
||||
assert!(audio_negotiated);
|
||||
assert!(!video_negotiated);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The cloned MediaEngine instance should be able to update negotiated header extensions.
|
||||
#[tokio::test]
|
||||
async fn test_update_header_extension_to_cloned_media_engine() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
|
||||
m.register_codec(
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_owned(),
|
||||
clock_rate: 48000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
)?;
|
||||
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: "test-extension".to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
|
||||
validate(&m).await?;
|
||||
validate(&m.clone_to()).await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_extension_id_collision() -> Result<()> {
|
||||
let must_parse = |raw: &str| -> Result<SessionDescription> {
|
||||
let mut reader = Cursor::new(raw.as_bytes());
|
||||
Ok(SessionDescription::unmarshal(&mut reader)?)
|
||||
};
|
||||
|
||||
const HEADER_EXTENSIONS: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=audio 9 UDP/TLS/RTP/SAVPF 111
|
||||
a=extmap:7 urn:ietf:params:rtp-hdrext:sdes:mid
|
||||
a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
|
||||
a=extmap:5 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id
|
||||
a=rtpmap:111 opus/48000/2
|
||||
";
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
{
|
||||
let extension = "urn:3gpp:video-orientation";
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: extension.to_owned(),
|
||||
},
|
||||
RTPCodecType::Video,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
for extension in [
|
||||
"urn:ietf:params:rtp-hdrext:ssrc-audio-level",
|
||||
"urn:ietf:params:rtp-hdrext:sdes:mid",
|
||||
"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",
|
||||
] {
|
||||
m.register_header_extension(
|
||||
RTCRtpHeaderExtensionCapability {
|
||||
uri: extension.to_owned(),
|
||||
},
|
||||
RTPCodecType::Audio,
|
||||
None,
|
||||
)?;
|
||||
}
|
||||
|
||||
m.update_from_remote_description(&must_parse(HEADER_EXTENSIONS)?)
|
||||
.await?;
|
||||
|
||||
assert!(!m.negotiated_video.load(Ordering::SeqCst));
|
||||
assert!(m.negotiated_audio.load(Ordering::SeqCst));
|
||||
|
||||
let (abs_id, abs_audio_enabled, abs_video_enabled) = m
|
||||
.get_header_extension_id(RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::ABS_SEND_TIME_URI.to_owned(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(abs_id, 0);
|
||||
assert!(!abs_audio_enabled);
|
||||
assert!(!abs_video_enabled);
|
||||
|
||||
let (mid_id, mid_audio_enabled, mid_video_enabled) = m
|
||||
.get_header_extension_id(RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::SDES_MID_URI.to_owned(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(mid_id, 7);
|
||||
assert!(mid_audio_enabled);
|
||||
assert!(!mid_video_enabled);
|
||||
|
||||
let (mid_id, mid_audio_enabled, mid_video_enabled) = m
|
||||
.get_header_extension_id(RTCRtpHeaderExtensionCapability {
|
||||
uri: sdp::extmap::AUDIO_LEVEL_URI.to_owned(),
|
||||
})
|
||||
.await;
|
||||
assert_eq!(mid_id, 1);
|
||||
assert!(mid_audio_enabled);
|
||||
assert!(!mid_video_enabled);
|
||||
|
||||
let params =
|
||||
m.get_rtp_parameters_by_kind(RTPCodecType::Video, RTCRtpTransceiverDirection::Sendonly);
|
||||
//dbg!(¶ms);
|
||||
|
||||
let orientation = params
|
||||
.header_extensions
|
||||
.iter()
|
||||
.find(|ext| ext.uri == "urn:3gpp:video-orientation")
|
||||
.unwrap();
|
||||
assert_ne!(orientation.id, 1);
|
||||
assert_ne!(orientation.id, 7);
|
||||
assert_ne!(orientation.id, 5);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+804
@@ -0,0 +1,804 @@
|
||||
#[cfg(test)]
|
||||
mod media_engine_test;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::ops::Range;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use sdp::description::session::SessionDescription;
|
||||
use util::sync::Mutex as SyncMutex;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::peer_connection::sdp::{
|
||||
codecs_from_media_description, rtp_extensions_from_media_description,
|
||||
};
|
||||
use crate::rtp_transceiver::rtp_codec::{
|
||||
codec_parameters_fuzzy_search, CodecMatch, RTCRtpCodecCapability, RTCRtpCodecParameters,
|
||||
RTCRtpHeaderExtensionCapability, RTCRtpHeaderExtensionParameters, RTCRtpParameters,
|
||||
RTPCodecType,
|
||||
};
|
||||
use crate::rtp_transceiver::rtp_transceiver_direction::RTCRtpTransceiverDirection;
|
||||
use crate::rtp_transceiver::{fmtp, PayloadType, RTCPFeedback};
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
use crate::stats::CodecStats;
|
||||
use crate::stats::StatsReportType::Codec;
|
||||
|
||||
/// MIME_TYPE_H264 H264 MIME type.
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_H264: &str = "video/H264";
|
||||
/// MIME_TYPE_OPUS Opus MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_OPUS: &str = "audio/opus";
|
||||
/// MIME_TYPE_VP8 VP8 MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_VP8: &str = "video/VP8";
|
||||
/// MIME_TYPE_VP9 VP9 MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_VP9: &str = "video/VP9";
|
||||
/// MIME_TYPE_AV1 AV1 MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_AV1: &str = "video/AV1";
|
||||
/// MIME_TYPE_G722 G722 MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_G722: &str = "audio/G722";
|
||||
/// MIME_TYPE_PCMU PCMU MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_PCMU: &str = "audio/PCMU";
|
||||
/// MIME_TYPE_PCMA PCMA MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_PCMA: &str = "audio/PCMA";
|
||||
/// MIME_TYPE_TELEPHONE_EVENT telephone-event MIME type
|
||||
/// Note: Matching should be case insensitive.
|
||||
pub const MIME_TYPE_TELEPHONE_EVENT: &str = "audio/telephone-event";
|
||||
|
||||
const VALID_EXT_IDS: Range<isize> = 1..15;
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub(crate) struct MediaEngineHeaderExtension {
|
||||
pub(crate) uri: String,
|
||||
pub(crate) is_audio: bool,
|
||||
pub(crate) is_video: bool,
|
||||
pub(crate) allowed_direction: Option<RTCRtpTransceiverDirection>,
|
||||
}
|
||||
|
||||
impl MediaEngineHeaderExtension {
|
||||
pub fn is_matching_direction(&self, dir: RTCRtpTransceiverDirection) -> bool {
|
||||
if let Some(allowed_direction) = self.allowed_direction {
|
||||
use RTCRtpTransceiverDirection::*;
|
||||
allowed_direction == Inactive && dir == Inactive
|
||||
|| allowed_direction.has_send() && dir.has_send()
|
||||
|| allowed_direction.has_recv() && dir.has_recv()
|
||||
} else {
|
||||
// None means all directions matches.
|
||||
true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A MediaEngine defines the codecs supported by a PeerConnection, and the
|
||||
/// configuration of those codecs. A MediaEngine must not be shared between
|
||||
/// PeerConnections.
|
||||
#[derive(Default)]
|
||||
pub struct MediaEngine {
|
||||
// If we have attempted to negotiate a codec type yet.
|
||||
pub(crate) negotiated_video: AtomicBool,
|
||||
pub(crate) negotiated_audio: AtomicBool,
|
||||
|
||||
pub(crate) video_codecs: Vec<RTCRtpCodecParameters>,
|
||||
pub(crate) audio_codecs: Vec<RTCRtpCodecParameters>,
|
||||
pub(crate) negotiated_video_codecs: SyncMutex<Vec<RTCRtpCodecParameters>>,
|
||||
pub(crate) negotiated_audio_codecs: SyncMutex<Vec<RTCRtpCodecParameters>>,
|
||||
|
||||
header_extensions: Vec<MediaEngineHeaderExtension>,
|
||||
proposed_header_extensions: SyncMutex<HashMap<isize, MediaEngineHeaderExtension>>,
|
||||
pub(crate) negotiated_header_extensions: SyncMutex<HashMap<isize, MediaEngineHeaderExtension>>,
|
||||
}
|
||||
|
||||
impl MediaEngine {
|
||||
/// register_default_codecs registers the default codecs supported by Pion WebRTC.
|
||||
/// register_default_codecs is not safe for concurrent use.
|
||||
pub fn register_default_codecs(&mut self) -> Result<()> {
|
||||
// Default Audio Codecs
|
||||
for codec in vec![
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_owned(),
|
||||
clock_rate: 48000,
|
||||
channels: 2,
|
||||
sdp_fmtp_line: "minptime=10;useinbandfec=1".to_owned(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_G722.to_owned(),
|
||||
clock_rate: 8000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_owned(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 9,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_PCMU.to_owned(),
|
||||
clock_rate: 8000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_owned(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 0,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_PCMA.to_owned(),
|
||||
clock_rate: 8000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_owned(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 8,
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
self.register_codec(codec, RTPCodecType::Audio)?;
|
||||
}
|
||||
|
||||
let video_rtcp_feedback = vec![
|
||||
RTCPFeedback {
|
||||
typ: "goog-remb".to_owned(),
|
||||
parameter: "".to_owned(),
|
||||
},
|
||||
RTCPFeedback {
|
||||
typ: "ccm".to_owned(),
|
||||
parameter: "fir".to_owned(),
|
||||
},
|
||||
RTCPFeedback {
|
||||
typ: "nack".to_owned(),
|
||||
parameter: "".to_owned(),
|
||||
},
|
||||
RTCPFeedback {
|
||||
typ: "nack".to_owned(),
|
||||
parameter: "pli".to_owned(),
|
||||
},
|
||||
];
|
||||
for codec in vec![
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=0".to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 98,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=1".to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 100,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42001f"
|
||||
.to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 102,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f"
|
||||
.to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 127,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f"
|
||||
.to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 125,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42e01f"
|
||||
.to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 108,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=0;profile-level-id=42001f"
|
||||
.to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 127,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line:
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=640032"
|
||||
.to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback.clone(),
|
||||
},
|
||||
payload_type: 123,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_AV1.to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=0".to_owned(),
|
||||
rtcp_feedback: video_rtcp_feedback,
|
||||
},
|
||||
payload_type: 41,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: "video/ulpfec".to_owned(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_owned(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 116,
|
||||
..Default::default()
|
||||
},
|
||||
] {
|
||||
self.register_codec(codec, RTPCodecType::Video)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// add_codec will append codec if it not exists
|
||||
fn add_codec(codecs: &mut Vec<RTCRtpCodecParameters>, codec: RTCRtpCodecParameters) {
|
||||
for c in codecs.iter() {
|
||||
if c.capability.mime_type == codec.capability.mime_type
|
||||
&& c.payload_type == codec.payload_type
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
codecs.push(codec);
|
||||
}
|
||||
|
||||
/// register_codec adds codec to the MediaEngine
|
||||
/// These are the list of codecs supported by this PeerConnection.
|
||||
/// register_codec is not safe for concurrent use.
|
||||
pub fn register_codec(
|
||||
&mut self,
|
||||
mut codec: RTCRtpCodecParameters,
|
||||
typ: RTPCodecType,
|
||||
) -> Result<()> {
|
||||
codec.stats_id = format!(
|
||||
"RTPCodec-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos()
|
||||
);
|
||||
match typ {
|
||||
RTPCodecType::Audio => {
|
||||
MediaEngine::add_codec(&mut self.audio_codecs, codec);
|
||||
Ok(())
|
||||
}
|
||||
RTPCodecType::Video => {
|
||||
MediaEngine::add_codec(&mut self.video_codecs, codec);
|
||||
Ok(())
|
||||
}
|
||||
_ => Err(Error::ErrUnknownType),
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds a header extension to the MediaEngine
|
||||
/// To determine the negotiated value use [`get_header_extension_id`] after signaling is complete.
|
||||
///
|
||||
/// The `allowed_direction` controls for which transceiver directions the extension matches. If
|
||||
/// set to `None` it matches all directions. The `SendRecv` direction would match all transceiver
|
||||
/// directions apart from `Inactive`. Inactive only matches inactive.
|
||||
pub fn register_header_extension(
|
||||
&mut self,
|
||||
extension: RTCRtpHeaderExtensionCapability,
|
||||
typ: RTPCodecType,
|
||||
allowed_direction: Option<RTCRtpTransceiverDirection>,
|
||||
) -> Result<()> {
|
||||
let ext = {
|
||||
match self
|
||||
.header_extensions
|
||||
.iter_mut()
|
||||
.find(|ext| ext.uri == extension.uri)
|
||||
{
|
||||
Some(ext) => ext,
|
||||
None => {
|
||||
// We have registered too many extensions
|
||||
if self.header_extensions.len() > VALID_EXT_IDS.end as usize {
|
||||
return Err(Error::ErrRegisterHeaderExtensionNoFreeID);
|
||||
}
|
||||
self.header_extensions.push(MediaEngineHeaderExtension {
|
||||
allowed_direction,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
// Unwrap is fine because we just pushed
|
||||
self.header_extensions.last_mut().unwrap()
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if typ == RTPCodecType::Audio {
|
||||
ext.is_audio = true;
|
||||
} else if typ == RTPCodecType::Video {
|
||||
ext.is_video = true;
|
||||
}
|
||||
|
||||
ext.uri = extension.uri;
|
||||
|
||||
if ext.allowed_direction != allowed_direction {
|
||||
return Err(Error::ErrRegisterHeaderExtensionInvalidDirection);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// register_feedback adds feedback mechanism to already registered codecs.
|
||||
pub fn register_feedback(&mut self, feedback: RTCPFeedback, typ: RTPCodecType) {
|
||||
match typ {
|
||||
RTPCodecType::Video => {
|
||||
for v in &mut self.video_codecs {
|
||||
v.capability.rtcp_feedback.push(feedback.clone());
|
||||
}
|
||||
}
|
||||
RTPCodecType::Audio => {
|
||||
for a in &mut self.audio_codecs {
|
||||
a.capability.rtcp_feedback.push(feedback.clone());
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// get_header_extension_id returns the negotiated ID for a header extension.
|
||||
/// If the Header Extension isn't enabled ok will be false
|
||||
pub(crate) async fn get_header_extension_id(
|
||||
&self,
|
||||
extension: RTCRtpHeaderExtensionCapability,
|
||||
) -> (isize, bool, bool) {
|
||||
let negotiated_header_extensions = self.negotiated_header_extensions.lock();
|
||||
if negotiated_header_extensions.is_empty() {
|
||||
return (0, false, false);
|
||||
}
|
||||
|
||||
for (id, h) in &*negotiated_header_extensions {
|
||||
if extension.uri == h.uri {
|
||||
return (*id, h.is_audio, h.is_video);
|
||||
}
|
||||
}
|
||||
|
||||
(0, false, false)
|
||||
}
|
||||
|
||||
/// clone_to copies any user modifiable state of the MediaEngine
|
||||
/// all internal state is reset
|
||||
pub(crate) fn clone_to(&self) -> Self {
|
||||
MediaEngine {
|
||||
video_codecs: self.video_codecs.clone(),
|
||||
audio_codecs: self.audio_codecs.clone(),
|
||||
header_extensions: self.header_extensions.clone(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_codec_by_payload(
|
||||
&self,
|
||||
payload_type: PayloadType,
|
||||
) -> Result<(RTCRtpCodecParameters, RTPCodecType)> {
|
||||
{
|
||||
let negotiated_video_codecs = self.negotiated_video_codecs.lock();
|
||||
for codec in &*negotiated_video_codecs {
|
||||
if codec.payload_type == payload_type {
|
||||
return Ok((codec.clone(), RTPCodecType::Video));
|
||||
}
|
||||
}
|
||||
}
|
||||
{
|
||||
let negotiated_audio_codecs = self.negotiated_audio_codecs.lock();
|
||||
for codec in &*negotiated_audio_codecs {
|
||||
if codec.payload_type == payload_type {
|
||||
return Ok((codec.clone(), RTPCodecType::Audio));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::ErrCodecNotFound)
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(&self, collector: &StatsCollector) {
|
||||
let mut reports = HashMap::new();
|
||||
|
||||
for codec in &self.video_codecs {
|
||||
reports.insert(codec.stats_id.clone(), Codec(CodecStats::from(codec)));
|
||||
}
|
||||
|
||||
for codec in &self.audio_codecs {
|
||||
reports.insert(codec.stats_id.clone(), Codec(CodecStats::from(codec)));
|
||||
}
|
||||
|
||||
collector.merge(reports);
|
||||
}
|
||||
|
||||
/// Look up a codec and enable if it exists
|
||||
pub(crate) fn match_remote_codec(
|
||||
&self,
|
||||
remote_codec: &RTCRtpCodecParameters,
|
||||
typ: RTPCodecType,
|
||||
exact_matches: &[RTCRtpCodecParameters],
|
||||
partial_matches: &[RTCRtpCodecParameters],
|
||||
) -> Result<CodecMatch> {
|
||||
let codecs = if typ == RTPCodecType::Audio {
|
||||
&self.audio_codecs
|
||||
} else {
|
||||
&self.video_codecs
|
||||
};
|
||||
|
||||
let remote_fmtp = fmtp::parse(
|
||||
&remote_codec.capability.mime_type,
|
||||
remote_codec.capability.sdp_fmtp_line.as_str(),
|
||||
);
|
||||
if let Some(apt) = remote_fmtp.parameter("apt") {
|
||||
let payload_type = apt.parse::<u8>()?;
|
||||
|
||||
let mut apt_match = CodecMatch::None;
|
||||
for codec in exact_matches {
|
||||
if codec.payload_type == payload_type {
|
||||
apt_match = CodecMatch::Exact;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if apt_match == CodecMatch::None {
|
||||
for codec in partial_matches {
|
||||
if codec.payload_type == payload_type {
|
||||
apt_match = CodecMatch::Partial;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if apt_match == CodecMatch::None {
|
||||
return Ok(CodecMatch::None); // not an error, we just ignore this codec we don't support
|
||||
}
|
||||
|
||||
// if apt's media codec is partial match, then apt codec must be partial match too
|
||||
let (_, mut match_type) = codec_parameters_fuzzy_search(remote_codec, codecs);
|
||||
if match_type == CodecMatch::Exact && apt_match == CodecMatch::Partial {
|
||||
match_type = CodecMatch::Partial;
|
||||
}
|
||||
return Ok(match_type);
|
||||
}
|
||||
|
||||
let (_, match_type) = codec_parameters_fuzzy_search(remote_codec, codecs);
|
||||
Ok(match_type)
|
||||
}
|
||||
|
||||
/// Look up a header extension and enable if it exists
|
||||
pub(crate) async fn update_header_extension(
|
||||
&self,
|
||||
id: isize,
|
||||
extension: &str,
|
||||
typ: RTPCodecType,
|
||||
) -> Result<()> {
|
||||
let mut negotiated_header_extensions = self.negotiated_header_extensions.lock();
|
||||
let mut proposed_header_extensions = self.proposed_header_extensions.lock();
|
||||
|
||||
for local_extension in &self.header_extensions {
|
||||
if local_extension.uri != extension {
|
||||
continue;
|
||||
}
|
||||
|
||||
let negotiated_ext = negotiated_header_extensions
|
||||
.iter_mut()
|
||||
.find(|(_, ext)| ext.uri == extension);
|
||||
|
||||
if let Some(n_ext) = negotiated_ext {
|
||||
if *n_ext.0 == id {
|
||||
n_ext.1.is_video |= typ == RTPCodecType::Video;
|
||||
n_ext.1.is_audio |= typ == RTPCodecType::Audio;
|
||||
} else {
|
||||
let nid = n_ext.0;
|
||||
log::warn!("Invalid ext id mapping in update_header_extension. {} was negotiated as {}, but was {} in call", extension, nid, id);
|
||||
}
|
||||
} else {
|
||||
// We either only have a proposal or we have neither proposal nor a negotiated id
|
||||
// Accept whatevers the peer suggests
|
||||
|
||||
if let Some(prev_ext) = negotiated_header_extensions.get(&id) {
|
||||
let prev_uri = &prev_ext.uri;
|
||||
log::warn!("Assigning {} to {} would override previous assignment to {}, no action taken", id, extension, prev_uri);
|
||||
} else {
|
||||
let h = MediaEngineHeaderExtension {
|
||||
uri: extension.to_owned(),
|
||||
is_audio: local_extension.is_audio && typ == RTPCodecType::Audio,
|
||||
is_video: local_extension.is_video && typ == RTPCodecType::Video,
|
||||
allowed_direction: local_extension.allowed_direction,
|
||||
};
|
||||
negotiated_header_extensions.insert(id, h);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear any proposals we had for this id
|
||||
proposed_header_extensions.remove(&id);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn push_codecs(&self, codecs: Vec<RTCRtpCodecParameters>, typ: RTPCodecType) {
|
||||
for codec in codecs {
|
||||
if typ == RTPCodecType::Audio {
|
||||
let mut negotiated_audio_codecs = self.negotiated_audio_codecs.lock();
|
||||
MediaEngine::add_codec(&mut negotiated_audio_codecs, codec);
|
||||
} else if typ == RTPCodecType::Video {
|
||||
let mut negotiated_video_codecs = self.negotiated_video_codecs.lock();
|
||||
MediaEngine::add_codec(&mut negotiated_video_codecs, codec);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Update the MediaEngine from a remote description
|
||||
pub(crate) async fn update_from_remote_description(
|
||||
&self,
|
||||
desc: &SessionDescription,
|
||||
) -> Result<()> {
|
||||
for media in &desc.media_descriptions {
|
||||
let typ = if !self.negotiated_audio.load(Ordering::SeqCst)
|
||||
&& media.media_name.media.to_lowercase() == "audio"
|
||||
{
|
||||
self.negotiated_audio.store(true, Ordering::SeqCst);
|
||||
RTPCodecType::Audio
|
||||
} else if !self.negotiated_video.load(Ordering::SeqCst)
|
||||
&& media.media_name.media.to_lowercase() == "video"
|
||||
{
|
||||
self.negotiated_video.store(true, Ordering::SeqCst);
|
||||
RTPCodecType::Video
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
|
||||
let codecs = codecs_from_media_description(media)?;
|
||||
|
||||
let mut exact_matches = vec![]; //make([]RTPCodecParameters, 0, len(codecs))
|
||||
let mut partial_matches = vec![]; //make([]RTPCodecParameters, 0, len(codecs))
|
||||
|
||||
for codec in codecs {
|
||||
let match_type =
|
||||
self.match_remote_codec(&codec, typ, &exact_matches, &partial_matches)?;
|
||||
|
||||
if match_type == CodecMatch::Exact {
|
||||
exact_matches.push(codec);
|
||||
} else if match_type == CodecMatch::Partial {
|
||||
partial_matches.push(codec);
|
||||
}
|
||||
}
|
||||
|
||||
// use exact matches when they exist, otherwise fall back to partial
|
||||
if !exact_matches.is_empty() {
|
||||
self.push_codecs(exact_matches, typ).await;
|
||||
} else if !partial_matches.is_empty() {
|
||||
self.push_codecs(partial_matches, typ).await;
|
||||
} else {
|
||||
// no match, not negotiated
|
||||
continue;
|
||||
}
|
||||
|
||||
let extensions = rtp_extensions_from_media_description(media)?;
|
||||
|
||||
for (extension, id) in extensions {
|
||||
self.update_header_extension(id, &extension, typ).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn get_codecs_by_kind(&self, typ: RTPCodecType) -> Vec<RTCRtpCodecParameters> {
|
||||
if typ == RTPCodecType::Video {
|
||||
if self.negotiated_video.load(Ordering::SeqCst) {
|
||||
let negotiated_video_codecs = self.negotiated_video_codecs.lock();
|
||||
negotiated_video_codecs.clone()
|
||||
} else {
|
||||
self.video_codecs.clone()
|
||||
}
|
||||
} else if typ == RTPCodecType::Audio {
|
||||
if self.negotiated_audio.load(Ordering::SeqCst) {
|
||||
let negotiated_audio_codecs = self.negotiated_audio_codecs.lock();
|
||||
negotiated_audio_codecs.clone()
|
||||
} else {
|
||||
self.audio_codecs.clone()
|
||||
}
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_rtp_parameters_by_kind(
|
||||
&self,
|
||||
typ: RTPCodecType,
|
||||
direction: RTCRtpTransceiverDirection,
|
||||
) -> RTCRtpParameters {
|
||||
let mut header_extensions = vec![];
|
||||
|
||||
if self.negotiated_video.load(Ordering::SeqCst) && typ == RTPCodecType::Video
|
||||
|| self.negotiated_audio.load(Ordering::SeqCst) && typ == RTPCodecType::Audio
|
||||
{
|
||||
let negotiated_header_extensions = self.negotiated_header_extensions.lock();
|
||||
for (id, e) in &*negotiated_header_extensions {
|
||||
if e.is_matching_direction(direction)
|
||||
&& (e.is_audio && typ == RTPCodecType::Audio
|
||||
|| e.is_video && typ == RTPCodecType::Video)
|
||||
{
|
||||
header_extensions.push(RTCRtpHeaderExtensionParameters {
|
||||
id: *id,
|
||||
uri: e.uri.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut proposed_header_extensions = self.proposed_header_extensions.lock();
|
||||
let mut negotiated_header_extensions = self.negotiated_header_extensions.lock();
|
||||
|
||||
for local_extension in &self.header_extensions {
|
||||
let relevant = local_extension.is_matching_direction(direction)
|
||||
&& (local_extension.is_audio && typ == RTPCodecType::Audio
|
||||
|| local_extension.is_video && typ == RTPCodecType::Video);
|
||||
|
||||
if !relevant {
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((id, negotiated_extension)) = negotiated_header_extensions
|
||||
.iter_mut()
|
||||
.find(|(_, e)| e.uri == local_extension.uri)
|
||||
{
|
||||
// We have previously negotiated this extension, make sure to record it as
|
||||
// active for the current type
|
||||
negotiated_extension.is_audio |= typ == RTPCodecType::Audio;
|
||||
negotiated_extension.is_video |= typ == RTPCodecType::Video;
|
||||
|
||||
header_extensions.push(RTCRtpHeaderExtensionParameters {
|
||||
id: *id,
|
||||
uri: negotiated_extension.uri.clone(),
|
||||
});
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some((id, negotiated_extension)) = proposed_header_extensions
|
||||
.iter_mut()
|
||||
.find(|(_, e)| e.uri == local_extension.uri)
|
||||
{
|
||||
// We have previously proposed this extension, re-use it
|
||||
header_extensions.push(RTCRtpHeaderExtensionParameters {
|
||||
id: *id,
|
||||
uri: negotiated_extension.uri.clone(),
|
||||
});
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// Figure out which (unused id) to propose.
|
||||
let id = VALID_EXT_IDS.clone().find(|id| {
|
||||
!negotiated_header_extensions.keys().any(|nid| nid == id)
|
||||
&& !proposed_header_extensions.keys().any(|pid| pid == id)
|
||||
});
|
||||
|
||||
if let Some(id) = id {
|
||||
proposed_header_extensions.insert(
|
||||
id,
|
||||
MediaEngineHeaderExtension {
|
||||
uri: local_extension.uri.clone(),
|
||||
is_audio: local_extension.is_audio,
|
||||
is_video: local_extension.is_video,
|
||||
allowed_direction: local_extension.allowed_direction,
|
||||
},
|
||||
);
|
||||
|
||||
header_extensions.push(RTCRtpHeaderExtensionParameters {
|
||||
id,
|
||||
uri: local_extension.uri.clone(),
|
||||
});
|
||||
} else {
|
||||
log::warn!("No available RTP extension ID for {}", local_extension.uri);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
RTCRtpParameters {
|
||||
header_extensions,
|
||||
codecs: self.get_codecs_by_kind(typ),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_rtp_parameters_by_payload_type(
|
||||
&self,
|
||||
payload_type: PayloadType,
|
||||
) -> Result<RTCRtpParameters> {
|
||||
let (codec, typ) = self.get_codec_by_payload(payload_type).await?;
|
||||
|
||||
let mut header_extensions = vec![];
|
||||
{
|
||||
let negotiated_header_extensions = self.negotiated_header_extensions.lock();
|
||||
for (id, e) in &*negotiated_header_extensions {
|
||||
if e.is_audio && typ == RTPCodecType::Audio
|
||||
|| e.is_video && typ == RTPCodecType::Video
|
||||
{
|
||||
header_extensions.push(RTCRtpHeaderExtensionParameters {
|
||||
uri: e.uri.clone(),
|
||||
id: *id,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RTCRtpParameters {
|
||||
header_extensions,
|
||||
codecs: vec![codec],
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
+236
@@ -0,0 +1,236 @@
|
||||
#[cfg(test)]
|
||||
mod api_test;
|
||||
|
||||
pub mod interceptor_registry;
|
||||
pub mod media_engine;
|
||||
pub mod setting_engine;
|
||||
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use interceptor::registry::Registry;
|
||||
use interceptor::Interceptor;
|
||||
use media_engine::*;
|
||||
use rcgen::KeyPair;
|
||||
use setting_engine::*;
|
||||
|
||||
use crate::data_channel::data_channel_parameters::DataChannelParameters;
|
||||
use crate::data_channel::RTCDataChannel;
|
||||
use crate::dtls_transport::RTCDtlsTransport;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ice_transport::ice_gatherer::{RTCIceGatherOptions, RTCIceGatherer};
|
||||
use crate::ice_transport::RTCIceTransport;
|
||||
use crate::peer_connection::certificate::RTCCertificate;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
use crate::peer_connection::RTCPeerConnection;
|
||||
use crate::rtp_transceiver::rtp_codec::RTPCodecType;
|
||||
use crate::rtp_transceiver::rtp_receiver::RTCRtpReceiver;
|
||||
use crate::rtp_transceiver::rtp_sender::RTCRtpSender;
|
||||
use crate::sctp_transport::RTCSctpTransport;
|
||||
use crate::track::track_local::TrackLocal;
|
||||
|
||||
/// API bundles the global functions of the WebRTC and ORTC API.
|
||||
/// Some of these functions are also exported globally using the
|
||||
/// defaultAPI object. Note that the global version of the API
|
||||
/// may be phased out in the future.
|
||||
pub struct API {
|
||||
pub(crate) setting_engine: Arc<SettingEngine>,
|
||||
pub(crate) media_engine: Arc<MediaEngine>,
|
||||
pub(crate) interceptor_registry: Registry,
|
||||
}
|
||||
|
||||
impl API {
|
||||
/// new_peer_connection creates a new PeerConnection with the provided configuration against the received API object
|
||||
pub async fn new_peer_connection(
|
||||
&self,
|
||||
configuration: RTCConfiguration,
|
||||
) -> Result<RTCPeerConnection> {
|
||||
RTCPeerConnection::new(self, configuration).await
|
||||
}
|
||||
|
||||
/// new_ice_gatherer creates a new ice gatherer.
|
||||
/// This constructor is part of the ORTC API. It is not
|
||||
/// meant to be used together with the basic WebRTC API.
|
||||
pub fn new_ice_gatherer(&self, opts: RTCIceGatherOptions) -> Result<RTCIceGatherer> {
|
||||
let mut validated_servers = vec![];
|
||||
if !opts.ice_servers.is_empty() {
|
||||
for server in &opts.ice_servers {
|
||||
let url = server.urls()?;
|
||||
validated_servers.extend(url);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(RTCIceGatherer::new(
|
||||
validated_servers,
|
||||
opts.ice_gather_policy,
|
||||
Arc::clone(&self.setting_engine),
|
||||
))
|
||||
}
|
||||
|
||||
/// new_ice_transport creates a new ice transport.
|
||||
/// This constructor is part of the ORTC API. It is not
|
||||
/// meant to be used together with the basic WebRTC API.
|
||||
pub fn new_ice_transport(&self, gatherer: Arc<RTCIceGatherer>) -> RTCIceTransport {
|
||||
RTCIceTransport::new(gatherer)
|
||||
}
|
||||
|
||||
/// new_dtls_transport creates a new dtls_transport transport.
|
||||
/// This constructor is part of the ORTC API. It is not
|
||||
/// meant to be used together with the basic WebRTC API.
|
||||
pub fn new_dtls_transport(
|
||||
&self,
|
||||
ice_transport: Arc<RTCIceTransport>,
|
||||
mut certificates: Vec<RTCCertificate>,
|
||||
) -> Result<RTCDtlsTransport> {
|
||||
if !certificates.is_empty() {
|
||||
let now = SystemTime::now();
|
||||
for cert in &certificates {
|
||||
cert.expires
|
||||
.duration_since(now)
|
||||
.map_err(|_| Error::ErrCertificateExpired)?;
|
||||
}
|
||||
} else {
|
||||
let kp = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let cert = RTCCertificate::from_key_pair(kp)?;
|
||||
certificates = vec![cert];
|
||||
};
|
||||
|
||||
Ok(RTCDtlsTransport::new(
|
||||
ice_transport,
|
||||
certificates,
|
||||
Arc::clone(&self.setting_engine),
|
||||
))
|
||||
}
|
||||
|
||||
/// new_sctp_transport creates a new SCTPTransport.
|
||||
/// This constructor is part of the ORTC API. It is not
|
||||
/// meant to be used together with the basic WebRTC API.
|
||||
pub fn new_sctp_transport(
|
||||
&self,
|
||||
dtls_transport: Arc<RTCDtlsTransport>,
|
||||
) -> Result<RTCSctpTransport> {
|
||||
Ok(RTCSctpTransport::new(
|
||||
dtls_transport,
|
||||
Arc::clone(&self.setting_engine),
|
||||
))
|
||||
}
|
||||
|
||||
/// new_data_channel creates a new DataChannel.
|
||||
/// This constructor is part of the ORTC API. It is not
|
||||
/// meant to be used together with the basic WebRTC API.
|
||||
pub async fn new_data_channel(
|
||||
&self,
|
||||
sctp_transport: Arc<RTCSctpTransport>,
|
||||
params: DataChannelParameters,
|
||||
) -> Result<RTCDataChannel> {
|
||||
// https://w3c.github.io/webrtc-pc/#peer-to-peer-data-api (Step #5)
|
||||
if params.label.len() > 65535 {
|
||||
return Err(Error::ErrStringSizeLimit);
|
||||
}
|
||||
|
||||
let d = RTCDataChannel::new(params, Arc::clone(&self.setting_engine));
|
||||
d.open(sctp_transport).await?;
|
||||
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// new_rtp_receiver constructs a new RTPReceiver
|
||||
pub fn new_rtp_receiver(
|
||||
&self,
|
||||
kind: RTPCodecType,
|
||||
transport: Arc<RTCDtlsTransport>,
|
||||
interceptor: Arc<dyn Interceptor + Send + Sync>,
|
||||
) -> RTCRtpReceiver {
|
||||
RTCRtpReceiver::new(
|
||||
self.setting_engine.get_receive_mtu(),
|
||||
kind,
|
||||
transport,
|
||||
Arc::clone(&self.media_engine),
|
||||
interceptor,
|
||||
)
|
||||
}
|
||||
|
||||
/// new_rtp_sender constructs a new RTPSender
|
||||
pub async fn new_rtp_sender(
|
||||
&self,
|
||||
track: Option<Arc<dyn TrackLocal + Send + Sync>>,
|
||||
transport: Arc<RTCDtlsTransport>,
|
||||
interceptor: Arc<dyn Interceptor + Send + Sync>,
|
||||
) -> RTCRtpSender {
|
||||
RTCRtpSender::new(
|
||||
self.setting_engine.get_receive_mtu(),
|
||||
track,
|
||||
transport,
|
||||
Arc::clone(&self.media_engine),
|
||||
interceptor,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// Returns the internal [`SettingEngine`].
|
||||
pub fn setting_engine(&self) -> Arc<SettingEngine> {
|
||||
Arc::clone(&self.setting_engine)
|
||||
}
|
||||
|
||||
/// Returns the internal [`MediaEngine`].
|
||||
pub fn media_engine(&self) -> Arc<MediaEngine> {
|
||||
Arc::clone(&self.media_engine)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct APIBuilder {
|
||||
setting_engine: Option<Arc<SettingEngine>>,
|
||||
media_engine: Option<Arc<MediaEngine>>,
|
||||
interceptor_registry: Option<Registry>,
|
||||
}
|
||||
|
||||
impl APIBuilder {
|
||||
pub fn new() -> Self {
|
||||
APIBuilder::default()
|
||||
}
|
||||
|
||||
pub fn build(mut self) -> API {
|
||||
API {
|
||||
setting_engine: if let Some(setting_engine) = self.setting_engine.take() {
|
||||
setting_engine
|
||||
} else {
|
||||
Arc::new(SettingEngine::default())
|
||||
},
|
||||
media_engine: if let Some(media_engine) = self.media_engine.take() {
|
||||
media_engine
|
||||
} else {
|
||||
Arc::new(MediaEngine::default())
|
||||
},
|
||||
interceptor_registry: if let Some(interceptor_registry) =
|
||||
self.interceptor_registry.take()
|
||||
{
|
||||
interceptor_registry
|
||||
} else {
|
||||
Registry::new()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// WithSettingEngine allows providing a SettingEngine to the API.
|
||||
/// Settings should not be changed after passing the engine to an API.
|
||||
pub fn with_setting_engine(mut self, setting_engine: SettingEngine) -> Self {
|
||||
self.setting_engine = Some(Arc::new(setting_engine));
|
||||
self
|
||||
}
|
||||
|
||||
/// WithMediaEngine allows providing a MediaEngine to the API.
|
||||
/// Settings can be changed after passing the engine to an API.
|
||||
pub fn with_media_engine(mut self, media_engine: MediaEngine) -> Self {
|
||||
self.media_engine = Some(Arc::new(media_engine));
|
||||
self
|
||||
}
|
||||
|
||||
/// with_interceptor_registry allows providing Interceptors to the API.
|
||||
/// Settings should not be changed after passing the registry to an API.
|
||||
pub fn with_interceptor_registry(mut self, interceptor_registry: Registry) -> Self {
|
||||
self.interceptor_registry = Some(interceptor_registry);
|
||||
self
|
||||
}
|
||||
}
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
#[cfg(test)]
|
||||
mod setting_engine_test;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use dtls::extension::extension_use_srtp::SrtpProtectionProfile;
|
||||
use ice::agent::agent_config::{InterfaceFilterFn, IpFilterFn};
|
||||
use ice::mdns::MulticastDnsMode;
|
||||
use ice::network_type::NetworkType;
|
||||
use ice::udp_network::UDPNetwork;
|
||||
use tokio::time::Duration;
|
||||
use util::vnet::net::*;
|
||||
|
||||
use crate::dtls_transport::dtls_role::DTLSRole;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ice_transport::ice_candidate_type::RTCIceCandidateType;
|
||||
use crate::RECEIVE_MTU;
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct Detach {
|
||||
pub data_channels: bool,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct Timeout {
|
||||
pub ice_disconnected_timeout: Option<Duration>,
|
||||
pub ice_failed_timeout: Option<Duration>,
|
||||
pub ice_keepalive_interval: Option<Duration>,
|
||||
pub ice_host_acceptance_min_wait: Option<Duration>,
|
||||
pub ice_srflx_acceptance_min_wait: Option<Duration>,
|
||||
pub ice_prflx_acceptance_min_wait: Option<Duration>,
|
||||
pub ice_relay_acceptance_min_wait: Option<Duration>,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct Candidates {
|
||||
pub ice_lite: bool,
|
||||
pub ice_network_types: Vec<NetworkType>,
|
||||
pub interface_filter: Arc<Option<InterfaceFilterFn>>,
|
||||
pub ip_filter: Arc<Option<IpFilterFn>>,
|
||||
pub nat_1to1_ips: Vec<String>,
|
||||
pub nat_1to1_ip_candidate_type: RTCIceCandidateType,
|
||||
pub multicast_dns_mode: MulticastDnsMode,
|
||||
pub multicast_dns_host_name: String,
|
||||
pub username_fragment: String,
|
||||
pub password: String,
|
||||
}
|
||||
|
||||
#[derive(Default, Clone)]
|
||||
pub struct ReplayProtection {
|
||||
pub dtls: usize,
|
||||
pub srtp: usize,
|
||||
pub srtcp: usize,
|
||||
}
|
||||
|
||||
/// SettingEngine allows influencing behavior in ways that are not
|
||||
/// supported by the WebRTC API. This allows us to support additional
|
||||
/// use-cases without deviating from the WebRTC API elsewhere.
|
||||
#[derive(Default, Clone)]
|
||||
pub struct SettingEngine {
|
||||
pub(crate) detach: Detach,
|
||||
pub(crate) timeout: Timeout,
|
||||
pub(crate) candidates: Candidates,
|
||||
pub(crate) replay_protection: ReplayProtection,
|
||||
pub(crate) sdp_media_level_fingerprints: bool,
|
||||
pub(crate) answering_dtls_role: DTLSRole,
|
||||
pub(crate) disable_certificate_fingerprint_verification: bool,
|
||||
pub(crate) allow_insecure_verification_algorithm: bool,
|
||||
pub(crate) disable_srtp_replay_protection: bool,
|
||||
pub(crate) disable_srtcp_replay_protection: bool,
|
||||
pub(crate) vnet: Option<Arc<Net>>,
|
||||
//BufferFactory :func(packetType packetio.BufferPacketType, ssrc uint32) io.ReadWriteCloser,
|
||||
//iceTCPMux :ice.TCPMux,?
|
||||
//iceProxyDialer :proxy.Dialer,?
|
||||
pub(crate) udp_network: UDPNetwork,
|
||||
pub(crate) disable_media_engine_copy: bool,
|
||||
pub(crate) srtp_protection_profiles: Vec<SrtpProtectionProfile>,
|
||||
pub(crate) receive_mtu: usize,
|
||||
pub(crate) mid_generator: Option<Arc<dyn Fn(isize) -> String + Send + Sync>>,
|
||||
}
|
||||
|
||||
impl SettingEngine {
|
||||
/// get_receive_mtu returns the configured MTU. If SettingEngine's MTU is configured to 0 it returns the default
|
||||
pub(crate) fn get_receive_mtu(&self) -> usize {
|
||||
if self.receive_mtu != 0 {
|
||||
self.receive_mtu
|
||||
} else {
|
||||
RECEIVE_MTU
|
||||
}
|
||||
}
|
||||
/// detach_data_channels enables detaching data channels. When enabled
|
||||
/// data channels have to be detached in the OnOpen callback using the
|
||||
/// DataChannel.Detach method.
|
||||
pub fn detach_data_channels(&mut self) {
|
||||
self.detach.data_channels = true;
|
||||
}
|
||||
|
||||
/// set_srtp_protection_profiles allows the user to override the default srtp Protection Profiles
|
||||
/// The default srtp protection profiles are provided by the function `defaultSrtpProtectionProfiles`
|
||||
pub fn set_srtp_protection_profiles(&mut self, profiles: Vec<SrtpProtectionProfile>) {
|
||||
self.srtp_protection_profiles = profiles
|
||||
}
|
||||
|
||||
/// set_ice_timeouts sets the behavior around ICE Timeouts
|
||||
/// * disconnected_timeout is the duration without network activity before a Agent is considered disconnected. Default is 5 Seconds
|
||||
/// * failed_timeout is the duration without network activity before a Agent is considered failed after disconnected. Default is 25 Seconds
|
||||
/// * keep_alive_interval is how often the ICE Agent sends extra traffic if there is no activity, if media is flowing no traffic will be sent. Default is 2 seconds
|
||||
pub fn set_ice_timeouts(
|
||||
&mut self,
|
||||
disconnected_timeout: Option<Duration>,
|
||||
failed_timeout: Option<Duration>,
|
||||
keep_alive_interval: Option<Duration>,
|
||||
) {
|
||||
self.timeout.ice_disconnected_timeout = disconnected_timeout;
|
||||
self.timeout.ice_failed_timeout = failed_timeout;
|
||||
self.timeout.ice_keepalive_interval = keep_alive_interval;
|
||||
}
|
||||
|
||||
/// set_host_acceptance_min_wait sets the icehost_acceptance_min_wait
|
||||
pub fn set_host_acceptance_min_wait(&mut self, t: Option<Duration>) {
|
||||
self.timeout.ice_host_acceptance_min_wait = t;
|
||||
}
|
||||
|
||||
/// set_srflx_acceptance_min_wait sets the icesrflx_acceptance_min_wait
|
||||
pub fn set_srflx_acceptance_min_wait(&mut self, t: Option<Duration>) {
|
||||
self.timeout.ice_srflx_acceptance_min_wait = t;
|
||||
}
|
||||
|
||||
/// set_prflx_acceptance_min_wait sets the iceprflx_acceptance_min_wait
|
||||
pub fn set_prflx_acceptance_min_wait(&mut self, t: Option<Duration>) {
|
||||
self.timeout.ice_prflx_acceptance_min_wait = t;
|
||||
}
|
||||
|
||||
/// set_relay_acceptance_min_wait sets the icerelay_acceptance_min_wait
|
||||
pub fn set_relay_acceptance_min_wait(&mut self, t: Option<Duration>) {
|
||||
self.timeout.ice_relay_acceptance_min_wait = t;
|
||||
}
|
||||
|
||||
/// set_udp_network allows ICE traffic to come through Ephemeral or UDPMux.
|
||||
/// UDPMux drastically simplifying deployments where ports will need to be opened/forwarded.
|
||||
/// UDPMux should be started prior to creating PeerConnections.
|
||||
pub fn set_udp_network(&mut self, udp_network: UDPNetwork) {
|
||||
self.udp_network = udp_network;
|
||||
}
|
||||
|
||||
/// set_lite configures whether or not the ice agent should be a lite agent
|
||||
pub fn set_lite(&mut self, lite: bool) {
|
||||
self.candidates.ice_lite = lite;
|
||||
}
|
||||
|
||||
/// set_network_types configures what types of candidate networks are supported
|
||||
/// during local and server reflexive gathering.
|
||||
pub fn set_network_types(&mut self, candidate_types: Vec<NetworkType>) {
|
||||
self.candidates.ice_network_types = candidate_types;
|
||||
}
|
||||
|
||||
/// set_interface_filter sets the filtering functions when gathering ICE candidates
|
||||
/// This can be used to exclude certain network interfaces from ICE. Which may be
|
||||
/// useful if you know a certain interface will never succeed, or if you wish to reduce
|
||||
/// the amount of information you wish to expose to the remote peer
|
||||
pub fn set_interface_filter(&mut self, filter: InterfaceFilterFn) {
|
||||
self.candidates.interface_filter = Arc::new(Some(filter));
|
||||
}
|
||||
|
||||
/// set_ip_filter sets the filtering functions when gathering ICE candidates
|
||||
/// This can be used to exclude certain ip from ICE. Which may be
|
||||
/// useful if you know a certain ip will never succeed, or if you wish to reduce
|
||||
/// the amount of information you wish to expose to the remote peer
|
||||
pub fn set_ip_filter(&mut self, filter: IpFilterFn) {
|
||||
self.candidates.ip_filter = Arc::new(Some(filter));
|
||||
}
|
||||
|
||||
/// set_nat_1to1_ips sets a list of external IP addresses of 1:1 (D)NAT
|
||||
/// and a candidate type for which the external IP address is used.
|
||||
/// This is useful when you are host a server using Pion on an AWS EC2 instance
|
||||
/// which has a private address, behind a 1:1 DNAT with a public IP (e.g.
|
||||
/// Elastic IP). In this case, you can give the public IP address so that
|
||||
/// Pion will use the public IP address in its candidate instead of the private
|
||||
/// IP address. The second argument, candidate_type, is used to tell Pion which
|
||||
/// type of candidate should use the given public IP address.
|
||||
/// Two types of candidates are supported:
|
||||
///
|
||||
/// ICECandidateTypeHost:
|
||||
/// The public IP address will be used for the host candidate in the SDP.
|
||||
/// ICECandidateTypeSrflx:
|
||||
/// A server reflexive candidate with the given public IP address will be added
|
||||
/// to the SDP.
|
||||
///
|
||||
/// Please note that if you choose ICECandidateTypeHost, then the private IP address
|
||||
/// won't be advertised with the peer. Also, this option cannot be used along with mDNS.
|
||||
///
|
||||
/// If you choose ICECandidateTypeSrflx, it simply adds a server reflexive candidate
|
||||
/// with the public IP. The host candidate is still available along with mDNS
|
||||
/// capabilities unaffected. Also, you cannot give STUN server URL at the same time.
|
||||
/// It will result in an error otherwise.
|
||||
pub fn set_nat_1to1_ips(&mut self, ips: Vec<String>, candidate_type: RTCIceCandidateType) {
|
||||
self.candidates.nat_1to1_ips = ips;
|
||||
self.candidates.nat_1to1_ip_candidate_type = candidate_type;
|
||||
}
|
||||
|
||||
/// set_answering_dtls_role sets the dtls_transport role that is selected when offering
|
||||
/// The dtls_transport role controls if the WebRTC Client as a client or server. This
|
||||
/// may be useful when interacting with non-compliant clients or debugging issues.
|
||||
///
|
||||
/// DTLSRoleActive:
|
||||
/// Act as dtls_transport Client, send the ClientHello and starts the handshake
|
||||
/// DTLSRolePassive:
|
||||
/// Act as dtls_transport Server, wait for ClientHello
|
||||
pub fn set_answering_dtls_role(&mut self, role: DTLSRole) -> Result<()> {
|
||||
if role != DTLSRole::Client && role != DTLSRole::Server {
|
||||
return Err(Error::ErrSettingEngineSetAnsweringDTLSRole);
|
||||
}
|
||||
|
||||
self.answering_dtls_role = role;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// set_vnet sets the VNet instance that is passed to ice
|
||||
/// VNet is a virtual network layer, allowing users to simulate
|
||||
/// different topologies, latency, loss and jitter. This can be useful for
|
||||
/// learning WebRTC concepts or testing your application in a lab environment
|
||||
pub fn set_vnet(&mut self, vnet: Option<Arc<Net>>) {
|
||||
self.vnet = vnet;
|
||||
}
|
||||
|
||||
/// set_ice_multicast_dns_mode controls if ice queries and generates mDNS ICE Candidates
|
||||
pub fn set_ice_multicast_dns_mode(&mut self, multicast_dns_mode: ice::mdns::MulticastDnsMode) {
|
||||
self.candidates.multicast_dns_mode = multicast_dns_mode
|
||||
}
|
||||
|
||||
/// set_multicast_dns_host_name sets a static HostName to be used by ice instead of generating one on startup
|
||||
/// This should only be used for a single PeerConnection. Having multiple PeerConnections with the same HostName will cause
|
||||
/// undefined behavior
|
||||
pub fn set_multicast_dns_host_name(&mut self, host_name: String) {
|
||||
self.candidates.multicast_dns_host_name = host_name;
|
||||
}
|
||||
|
||||
/// set_ice_credentials sets a staic uFrag/uPwd to be used by ice
|
||||
/// This is useful if you want to do signalless WebRTC session, or having a reproducible environment with static credentials
|
||||
pub fn set_ice_credentials(&mut self, username_fragment: String, password: String) {
|
||||
self.candidates.username_fragment = username_fragment;
|
||||
self.candidates.password = password;
|
||||
}
|
||||
|
||||
/// disable_certificate_fingerprint_verification disables fingerprint verification after dtls_transport Handshake has finished
|
||||
pub fn disable_certificate_fingerprint_verification(&mut self, is_disabled: bool) {
|
||||
self.disable_certificate_fingerprint_verification = is_disabled;
|
||||
}
|
||||
|
||||
/// allow_insecure_verification_algorithm allows the usage of certain signature verification
|
||||
/// algorithm that are known to be vulnerable or deprecated.
|
||||
pub fn allow_insecure_verification_algorithm(&mut self, is_allowed: bool) {
|
||||
self.allow_insecure_verification_algorithm = is_allowed;
|
||||
}
|
||||
/// set_dtls_replay_protection_window sets a replay attack protection window size of dtls_transport connection.
|
||||
pub fn set_dtls_replay_protection_window(&mut self, n: usize) {
|
||||
self.replay_protection.dtls = n;
|
||||
}
|
||||
|
||||
/// set_srtp_replay_protection_window sets a replay attack protection window size of srtp session.
|
||||
pub fn set_srtp_replay_protection_window(&mut self, n: usize) {
|
||||
self.disable_srtp_replay_protection = false;
|
||||
self.replay_protection.srtp = n;
|
||||
}
|
||||
|
||||
/// set_srtcp_replay_protection_window sets a replay attack protection window size of srtcp session.
|
||||
pub fn set_srtcp_replay_protection_window(&mut self, n: usize) {
|
||||
self.disable_srtcp_replay_protection = false;
|
||||
self.replay_protection.srtcp = n;
|
||||
}
|
||||
|
||||
/// disable_srtp_replay_protection disables srtp replay protection.
|
||||
pub fn disable_srtp_replay_protection(&mut self, is_disabled: bool) {
|
||||
self.disable_srtp_replay_protection = is_disabled;
|
||||
}
|
||||
|
||||
/// disable_srtcp_replay_protection disables srtcp replay protection.
|
||||
pub fn disable_srtcp_replay_protection(&mut self, is_disabled: bool) {
|
||||
self.disable_srtcp_replay_protection = is_disabled;
|
||||
}
|
||||
|
||||
/// set_sdp_media_level_fingerprints configures the logic for dtls_transport Fingerprint insertion
|
||||
/// If true, fingerprints will be inserted in the sdp at the fingerprint
|
||||
/// level, instead of the session level. This helps with compatibility with
|
||||
/// some webrtc implementations.
|
||||
pub fn set_sdp_media_level_fingerprints(&mut self, sdp_media_level_fingerprints: bool) {
|
||||
self.sdp_media_level_fingerprints = sdp_media_level_fingerprints;
|
||||
}
|
||||
|
||||
// SetICETCPMux enables ICE-TCP when set to a non-nil value. Make sure that
|
||||
// NetworkTypeTCP4 or NetworkTypeTCP6 is enabled as well.
|
||||
//pub fn SetICETCPMux(&mut self, tcpMux ice.TCPMux) {
|
||||
// self.iceTCPMux = tcpMux
|
||||
//}
|
||||
|
||||
// SetICEProxyDialer sets the proxy dialer interface based on golang.org/x/net/proxy.
|
||||
//pub fn SetICEProxyDialer(&mut self, d proxy.Dialer) {
|
||||
// self.iceProxyDialer = d
|
||||
//}
|
||||
|
||||
/// disable_media_engine_copy stops the MediaEngine from being copied. This allows a user to modify
|
||||
/// the MediaEngine after the PeerConnection has been constructed. This is useful if you wish to
|
||||
/// modify codecs after signaling. Make sure not to share MediaEngines between PeerConnections.
|
||||
pub fn disable_media_engine_copy(&mut self, is_disabled: bool) {
|
||||
self.disable_media_engine_copy = is_disabled;
|
||||
}
|
||||
|
||||
/// set_receive_mtu sets the size of read buffer that copies incoming packets. This is optional.
|
||||
/// Leave this 0 for the default receive_mtu
|
||||
pub fn set_receive_mtu(&mut self, receive_mtu: usize) {
|
||||
self.receive_mtu = receive_mtu;
|
||||
}
|
||||
|
||||
/// Sets a callback used to generate mid for transceivers created by this side of the RTCPeerconnection.
|
||||
/// By having separate "naming schemes" for mids generated by either side of a connection, it's
|
||||
/// possible to reduce complexity when handling SDP offers/answers clashing.
|
||||
///
|
||||
/// The `isize` argument is currently greatest seen _numeric_ mid. Since mids don't need to be numeric
|
||||
/// this doesn't necessarily indicating anything.
|
||||
///
|
||||
/// Note that the spec says: All MID values MUST be generated in a fashion that does not leak user
|
||||
/// information, e.g., randomly or using a per-PeerConnection counter, and SHOULD be 3 bytes or less,
|
||||
/// to allow them to efficiently fit into the RTP header extension
|
||||
pub fn set_mid_generator(&mut self, f: impl Fn(isize) -> String + Send + Sync + 'static) {
|
||||
self.mid_generator = Some(Arc::new(f));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::peer_connection::peer_connection_test::*;
|
||||
use crate::rtp_transceiver::rtp_codec::RTPCodecType;
|
||||
|
||||
#[test]
|
||||
fn test_set_connection_timeout() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
|
||||
assert_eq!(s.timeout.ice_disconnected_timeout, None);
|
||||
assert_eq!(s.timeout.ice_failed_timeout, None);
|
||||
assert_eq!(s.timeout.ice_keepalive_interval, None);
|
||||
|
||||
s.set_ice_timeouts(
|
||||
Some(Duration::from_secs(1)),
|
||||
Some(Duration::from_secs(2)),
|
||||
Some(Duration::from_secs(3)),
|
||||
);
|
||||
assert_eq!(
|
||||
s.timeout.ice_disconnected_timeout,
|
||||
Some(Duration::from_secs(1))
|
||||
);
|
||||
assert_eq!(s.timeout.ice_failed_timeout, Some(Duration::from_secs(2)));
|
||||
assert_eq!(
|
||||
s.timeout.ice_keepalive_interval,
|
||||
Some(Duration::from_secs(3))
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_detach_data_channels() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
|
||||
assert!(
|
||||
!s.detach.data_channels,
|
||||
"SettingEngine defaults aren't as expected."
|
||||
);
|
||||
|
||||
s.detach_data_channels();
|
||||
|
||||
assert!(
|
||||
s.detach.data_channels,
|
||||
"Failed to enable detached data channels."
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_nat_1to1_ips() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
|
||||
assert!(
|
||||
s.candidates.nat_1to1_ips.is_empty(),
|
||||
"Invalid default value"
|
||||
);
|
||||
assert!(
|
||||
s.candidates.nat_1to1_ip_candidate_type == RTCIceCandidateType::Unspecified,
|
||||
"Invalid default value"
|
||||
);
|
||||
|
||||
let ips = vec!["1.2.3.4".to_owned()];
|
||||
let typ = RTCIceCandidateType::Host;
|
||||
s.set_nat_1to1_ips(ips, typ);
|
||||
assert!(
|
||||
!(s.candidates.nat_1to1_ips.len() != 1 || s.candidates.nat_1to1_ips[0] != "1.2.3.4"),
|
||||
"Failed to set NAT1To1IPs"
|
||||
);
|
||||
assert!(
|
||||
s.candidates.nat_1to1_ip_candidate_type == typ,
|
||||
"Failed to set NAT1To1IPCandidateType"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_answering_dtls_role() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
assert!(
|
||||
s.set_answering_dtls_role(DTLSRole::Auto).is_err(),
|
||||
"SetAnsweringDTLSRole can only be called with DTLSRoleClient or DTLSRoleServer"
|
||||
);
|
||||
assert!(
|
||||
s.set_answering_dtls_role(DTLSRole::Unspecified).is_err(),
|
||||
"SetAnsweringDTLSRole can only be called with DTLSRoleClient or DTLSRoleServer"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_set_replay_protection() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
|
||||
assert!(
|
||||
!(s.replay_protection.dtls != 0
|
||||
|| s.replay_protection.srtp != 0
|
||||
|| s.replay_protection.srtcp != 0),
|
||||
"SettingEngine defaults aren't as expected."
|
||||
);
|
||||
|
||||
s.set_dtls_replay_protection_window(128);
|
||||
s.set_srtp_replay_protection_window(64);
|
||||
s.set_srtcp_replay_protection_window(32);
|
||||
|
||||
assert!(
|
||||
!(s.replay_protection.dtls == 0 || s.replay_protection.dtls != 128),
|
||||
"Failed to set DTLS replay protection window"
|
||||
);
|
||||
assert!(
|
||||
!(s.replay_protection.srtp == 0 || s.replay_protection.srtp != 64),
|
||||
"Failed to set SRTP replay protection window"
|
||||
);
|
||||
assert!(
|
||||
!(s.replay_protection.srtcp == 0 || s.replay_protection.srtcp != 32),
|
||||
"Failed to set SRTCP replay protection window"
|
||||
);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/*TODO:#[test] fn test_setting_engine_set_ice_tcp_mux() ->Result<()> {
|
||||
|
||||
listener, err := net.ListenTCP("tcp", &net.TCPAddr{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
defer func() {
|
||||
_ = listener.Close()
|
||||
}()
|
||||
|
||||
tcpMux := NewICETCPMux(nil, listener, 8)
|
||||
|
||||
defer func() {
|
||||
_ = tcpMux.Close()
|
||||
}()
|
||||
|
||||
let mut s = SettingEngine::default();
|
||||
settingEngine.SetICETCPMux(tcpMux)
|
||||
|
||||
assert.Equal(t, tcpMux, settingEngine.iceTCPMux)
|
||||
|
||||
Ok(())
|
||||
}
|
||||
*/
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_setting_engine_set_disable_media_engine_copy() -> Result<()> {
|
||||
//"Copy"
|
||||
{
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut offerer, mut answerer) = new_pair(&api).await?;
|
||||
|
||||
offerer
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
signal_pair(&mut offerer, &mut answerer).await?;
|
||||
|
||||
// Assert that the MediaEngine the user created isn't modified
|
||||
assert!(!api.media_engine.negotiated_video.load(Ordering::SeqCst));
|
||||
{
|
||||
let negotiated_video_codecs = api.media_engine.negotiated_video_codecs.lock();
|
||||
assert!(negotiated_video_codecs.is_empty());
|
||||
}
|
||||
|
||||
// Assert that the internal MediaEngine is modified
|
||||
assert!(offerer
|
||||
.internal
|
||||
.media_engine
|
||||
.negotiated_video
|
||||
.load(Ordering::SeqCst));
|
||||
{
|
||||
let negotiated_video_codecs =
|
||||
offerer.internal.media_engine.negotiated_video_codecs.lock();
|
||||
assert!(!negotiated_video_codecs.is_empty());
|
||||
}
|
||||
|
||||
close_pair_now(&offerer, &answerer).await;
|
||||
|
||||
let (new_offerer, new_answerer) = new_pair(&api).await?;
|
||||
|
||||
// Assert that the first internal MediaEngine hasn't been cleared
|
||||
assert!(offerer
|
||||
.internal
|
||||
.media_engine
|
||||
.negotiated_video
|
||||
.load(Ordering::SeqCst));
|
||||
{
|
||||
let negotiated_video_codecs =
|
||||
offerer.internal.media_engine.negotiated_video_codecs.lock();
|
||||
assert!(!negotiated_video_codecs.is_empty());
|
||||
}
|
||||
|
||||
// Assert that the new internal MediaEngine isn't modified
|
||||
assert!(!new_offerer
|
||||
.internal
|
||||
.media_engine
|
||||
.negotiated_video
|
||||
.load(Ordering::SeqCst));
|
||||
{
|
||||
let negotiated_video_codecs = new_offerer
|
||||
.internal
|
||||
.media_engine
|
||||
.negotiated_video_codecs
|
||||
.lock();
|
||||
assert!(negotiated_video_codecs.is_empty());
|
||||
}
|
||||
|
||||
close_pair_now(&new_offerer, &new_answerer).await;
|
||||
}
|
||||
|
||||
//"No Copy"
|
||||
{
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
|
||||
let mut s = SettingEngine::default();
|
||||
s.disable_media_engine_copy(true);
|
||||
|
||||
let api = APIBuilder::new()
|
||||
.with_media_engine(m)
|
||||
.with_setting_engine(s)
|
||||
.build();
|
||||
|
||||
let (mut offerer, mut answerer) = new_pair(&api).await?;
|
||||
|
||||
offerer
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
signal_pair(&mut offerer, &mut answerer).await?;
|
||||
|
||||
// Assert that the user MediaEngine was modified, so no copy happened
|
||||
assert!(api.media_engine.negotiated_video.load(Ordering::SeqCst));
|
||||
{
|
||||
let negotiated_video_codecs = api.media_engine.negotiated_video_codecs.lock();
|
||||
assert!(!negotiated_video_codecs.is_empty());
|
||||
}
|
||||
|
||||
close_pair_now(&offerer, &answerer).await;
|
||||
|
||||
let (offerer, answerer) = new_pair(&api).await?;
|
||||
|
||||
// Assert that the new internal MediaEngine was modified, so no copy happened
|
||||
assert!(offerer
|
||||
.internal
|
||||
.media_engine
|
||||
.negotiated_video
|
||||
.load(Ordering::SeqCst));
|
||||
{
|
||||
let negotiated_video_codecs =
|
||||
offerer.internal.media_engine.negotiated_video_codecs.lock();
|
||||
assert!(!negotiated_video_codecs.is_empty());
|
||||
}
|
||||
|
||||
close_pair_now(&offerer, &answerer).await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
/// DataChannelConfig can be used to configure properties of the underlying
|
||||
/// channel such as data reliability.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct RTCDataChannelInit {
|
||||
/// ordered indicates if data is allowed to be delivered out of order. The
|
||||
/// default value of true, guarantees that data will be delivered in order.
|
||||
pub ordered: Option<bool>,
|
||||
|
||||
/// max_packet_life_time limits the time (in milliseconds) during which the
|
||||
/// channel will transmit or retransmit data if not acknowledged. This value
|
||||
/// may be clamped if it exceeds the maximum value supported.
|
||||
pub max_packet_life_time: Option<u16>,
|
||||
|
||||
/// max_retransmits limits the number of times a channel will retransmit data
|
||||
/// if not successfully delivered. This value may be clamped if it exceeds
|
||||
/// the maximum value supported.
|
||||
pub max_retransmits: Option<u16>,
|
||||
|
||||
/// protocol describes the subprotocol name used for this channel.
|
||||
pub protocol: Option<String>,
|
||||
|
||||
/// negotiated describes if the data channel is created by the local peer or
|
||||
/// the remote peer. The default value of None tells the user agent to
|
||||
/// announce the channel in-band and instruct the other peer to dispatch a
|
||||
/// corresponding DataChannel. If set to Some(id), it is up to the application
|
||||
/// to negotiate the channel and create an DataChannel with the same id
|
||||
/// at the other peer.
|
||||
pub negotiated: Option<u16>,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use bytes::Bytes;
|
||||
|
||||
/// DataChannelMessage represents a message received from the
|
||||
/// data channel. IsString will be set to true if the incoming
|
||||
/// message is of the string type. Otherwise the message is of
|
||||
/// a binary type.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct DataChannelMessage {
|
||||
pub is_string: bool,
|
||||
pub data: Bytes,
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// DataChannelParameters describes the configuration of the DataChannel.
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DataChannelParameters {
|
||||
pub label: String,
|
||||
pub protocol: String,
|
||||
pub ordered: bool,
|
||||
pub max_packet_life_time: u16,
|
||||
pub max_retransmits: u16,
|
||||
pub negotiated: Option<u16>,
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
/// DataChannelState indicates the state of a data channel.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize)]
|
||||
pub enum RTCDataChannelState {
|
||||
#[serde(rename = "unspecified")]
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// DataChannelStateConnecting indicates that the data channel is being
|
||||
/// established. This is the initial state of DataChannel, whether created
|
||||
/// with create_data_channel, or dispatched as a part of an DataChannelEvent.
|
||||
#[serde(rename = "connecting")]
|
||||
Connecting,
|
||||
|
||||
/// DataChannelStateOpen indicates that the underlying data transport is
|
||||
/// established and communication is possible.
|
||||
#[serde(rename = "open")]
|
||||
Open,
|
||||
|
||||
/// DataChannelStateClosing indicates that the procedure to close down the
|
||||
/// underlying data transport has started.
|
||||
#[serde(rename = "closing")]
|
||||
Closing,
|
||||
|
||||
/// DataChannelStateClosed indicates that the underlying data transport
|
||||
/// has been closed or could not be established.
|
||||
#[serde(rename = "closed")]
|
||||
Closed,
|
||||
}
|
||||
|
||||
const DATA_CHANNEL_STATE_CONNECTING_STR: &str = "connecting";
|
||||
const DATA_CHANNEL_STATE_OPEN_STR: &str = "open";
|
||||
const DATA_CHANNEL_STATE_CLOSING_STR: &str = "closing";
|
||||
const DATA_CHANNEL_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
impl From<u8> for RTCDataChannelState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCDataChannelState::Connecting,
|
||||
2 => RTCDataChannelState::Open,
|
||||
3 => RTCDataChannelState::Closing,
|
||||
4 => RTCDataChannelState::Closed,
|
||||
_ => RTCDataChannelState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<&str> for RTCDataChannelState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
DATA_CHANNEL_STATE_CONNECTING_STR => RTCDataChannelState::Connecting,
|
||||
DATA_CHANNEL_STATE_OPEN_STR => RTCDataChannelState::Open,
|
||||
DATA_CHANNEL_STATE_CLOSING_STR => RTCDataChannelState::Closing,
|
||||
DATA_CHANNEL_STATE_CLOSED_STR => RTCDataChannelState::Closed,
|
||||
_ => RTCDataChannelState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCDataChannelState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCDataChannelState::Connecting => DATA_CHANNEL_STATE_CONNECTING_STR,
|
||||
RTCDataChannelState::Open => DATA_CHANNEL_STATE_OPEN_STR,
|
||||
RTCDataChannelState::Closing => DATA_CHANNEL_STATE_CLOSING_STR,
|
||||
RTCDataChannelState::Closed => DATA_CHANNEL_STATE_CLOSED_STR,
|
||||
RTCDataChannelState::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_data_channel_state() {
|
||||
let tests = vec![
|
||||
(crate::UNSPECIFIED_STR, RTCDataChannelState::Unspecified),
|
||||
("connecting", RTCDataChannelState::Connecting),
|
||||
("open", RTCDataChannelState::Open),
|
||||
("closing", RTCDataChannelState::Closing),
|
||||
("closed", RTCDataChannelState::Closed),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(
|
||||
RTCDataChannelState::from(state_string),
|
||||
expected_state,
|
||||
"testCase: {expected_state}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_data_channel_state_string() {
|
||||
let tests = vec![
|
||||
(RTCDataChannelState::Unspecified, crate::UNSPECIFIED_STR),
|
||||
(RTCDataChannelState::Connecting, "connecting"),
|
||||
(RTCDataChannelState::Open, "open"),
|
||||
(RTCDataChannelState::Closing, "closing"),
|
||||
(RTCDataChannelState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string)
|
||||
}
|
||||
}
|
||||
}
|
||||
+1504
File diff suppressed because it is too large.
Load diff
+558
@@ -0,0 +1,558 @@
|
||||
#[cfg(test)]
|
||||
mod data_channel_test;
|
||||
|
||||
pub mod data_channel_init;
|
||||
pub mod data_channel_message;
|
||||
pub mod data_channel_parameters;
|
||||
pub mod data_channel_state;
|
||||
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU16, AtomicU8, AtomicUsize, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use bytes::Bytes;
|
||||
use data::message::message_channel_open::ChannelType;
|
||||
use data_channel_message::*;
|
||||
use data_channel_parameters::*;
|
||||
use data_channel_state::RTCDataChannelState;
|
||||
use sctp::stream::OnBufferedAmountLowFn;
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
use util::sync::Mutex as SyncMutex;
|
||||
|
||||
use crate::api::setting_engine::SettingEngine;
|
||||
use crate::error::{Error, OnErrorHdlrFn, Result};
|
||||
use crate::sctp_transport::RTCSctpTransport;
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
use crate::stats::{DataChannelStats, StatsReportType};
|
||||
|
||||
/// message size limit for Chromium
|
||||
// uu-remote-linux patch: receive messages up to the advertised a=max-message-size (libwebrtc's
|
||||
// 262144 default). The upstream u16::MAX buffer breaks the channel on larger messages, and the
|
||||
// official viewer sends port-mapping frames bigger than 64 KB.
|
||||
const DATA_CHANNEL_BUFFER_SIZE: usize = 262_144;
|
||||
|
||||
pub type OnMessageHdlrFn = Box<
|
||||
dyn (FnMut(DataChannelMessage) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
pub type OnOpenHdlrFn =
|
||||
Box<dyn (FnOnce() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>) + Send + Sync>;
|
||||
|
||||
pub type OnCloseHdlrFn =
|
||||
Box<dyn (FnMut() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>) + Send + Sync>;
|
||||
|
||||
/// DataChannel represents a WebRTC DataChannel
|
||||
/// The DataChannel interface represents a network channel
|
||||
/// which can be used for bidirectional peer-to-peer transfers of arbitrary data
|
||||
#[derive(Default)]
|
||||
pub struct RTCDataChannel {
|
||||
pub(crate) stats_id: String,
|
||||
pub(crate) label: String,
|
||||
pub(crate) ordered: bool,
|
||||
pub(crate) max_packet_lifetime: u16,
|
||||
pub(crate) max_retransmits: u16,
|
||||
pub(crate) protocol: String,
|
||||
pub(crate) negotiated: bool,
|
||||
pub(crate) id: AtomicU16,
|
||||
pub(crate) ready_state: Arc<AtomicU8>, // DataChannelState
|
||||
pub(crate) buffered_amount_low_threshold: AtomicUsize,
|
||||
pub(crate) detach_called: Arc<AtomicBool>,
|
||||
|
||||
// The binaryType represents attribute MUST, on getting, return the value to
|
||||
// which it was last set. On setting, if the new value is either the string
|
||||
// "blob" or the string "arraybuffer", then set the IDL attribute to this
|
||||
// new value. Otherwise, throw a SyntaxError. When an DataChannel object
|
||||
// is created, the binaryType attribute MUST be initialized to the string
|
||||
// "blob". This attribute controls how binary data is exposed to scripts.
|
||||
// binaryType string
|
||||
pub(crate) on_message_handler: Arc<ArcSwapOption<Mutex<OnMessageHdlrFn>>>,
|
||||
pub(crate) on_open_handler: SyncMutex<Option<OnOpenHdlrFn>>,
|
||||
pub(crate) on_close_handler: Arc<ArcSwapOption<Mutex<OnCloseHdlrFn>>>,
|
||||
pub(crate) on_error_handler: Arc<ArcSwapOption<Mutex<OnErrorHdlrFn>>>,
|
||||
|
||||
pub(crate) on_buffered_amount_low: Mutex<Option<OnBufferedAmountLowFn>>,
|
||||
|
||||
pub(crate) sctp_transport: Mutex<Option<Weak<RTCSctpTransport>>>,
|
||||
pub(crate) data_channel: Mutex<Option<Arc<data::data_channel::DataChannel>>>,
|
||||
|
||||
pub(crate) notify_tx: Arc<Notify>,
|
||||
|
||||
// A reference to the associated api object used by this datachannel
|
||||
pub(crate) setting_engine: Arc<SettingEngine>,
|
||||
}
|
||||
|
||||
impl RTCDataChannel {
|
||||
// create the DataChannel object before the networking is set up.
|
||||
pub(crate) fn new(params: DataChannelParameters, setting_engine: Arc<SettingEngine>) -> Self {
|
||||
// the id value if non-negotiated doesn't matter, since it will be overwritten
|
||||
// on opening
|
||||
let id = params.negotiated.unwrap_or(0);
|
||||
RTCDataChannel {
|
||||
stats_id: format!(
|
||||
"DataChannel-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.map_or(0, |d| d.as_nanos())
|
||||
),
|
||||
label: params.label,
|
||||
protocol: params.protocol,
|
||||
negotiated: params.negotiated.is_some(),
|
||||
id: AtomicU16::new(id),
|
||||
ordered: params.ordered,
|
||||
max_packet_lifetime: params.max_packet_life_time,
|
||||
max_retransmits: params.max_retransmits,
|
||||
ready_state: Arc::new(AtomicU8::new(RTCDataChannelState::Connecting as u8)),
|
||||
detach_called: Arc::new(AtomicBool::new(false)),
|
||||
|
||||
notify_tx: Arc::new(Notify::new()),
|
||||
|
||||
setting_engine,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// open opens the datachannel over the sctp transport
|
||||
pub(crate) async fn open(&self, sctp_transport: Arc<RTCSctpTransport>) -> Result<()> {
|
||||
if let Some(association) = sctp_transport.association().await {
|
||||
{
|
||||
let mut st = self.sctp_transport.lock().await;
|
||||
if st.is_none() {
|
||||
*st = Some(Arc::downgrade(&sctp_transport));
|
||||
} else {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
let channel_type;
|
||||
let reliability_parameter;
|
||||
|
||||
if self.max_packet_lifetime == 0 && self.max_retransmits == 0 {
|
||||
reliability_parameter = 0u32;
|
||||
if self.ordered {
|
||||
channel_type = ChannelType::Reliable;
|
||||
} else {
|
||||
channel_type = ChannelType::ReliableUnordered;
|
||||
}
|
||||
} else if self.max_retransmits != 0 {
|
||||
reliability_parameter = self.max_retransmits as u32;
|
||||
if self.ordered {
|
||||
channel_type = ChannelType::PartialReliableRexmit;
|
||||
} else {
|
||||
channel_type = ChannelType::PartialReliableRexmitUnordered;
|
||||
}
|
||||
} else {
|
||||
reliability_parameter = self.max_packet_lifetime as u32;
|
||||
if self.ordered {
|
||||
channel_type = ChannelType::PartialReliableTimed;
|
||||
} else {
|
||||
channel_type = ChannelType::PartialReliableTimedUnordered;
|
||||
}
|
||||
}
|
||||
|
||||
let cfg = data::data_channel::Config {
|
||||
channel_type,
|
||||
priority: data::message::message_channel_open::CHANNEL_PRIORITY_NORMAL,
|
||||
reliability_parameter,
|
||||
label: self.label.clone(),
|
||||
protocol: self.protocol.clone(),
|
||||
negotiated: self.negotiated,
|
||||
};
|
||||
|
||||
if !self.negotiated {
|
||||
self.id.store(
|
||||
sctp_transport
|
||||
.generate_and_set_data_channel_id(
|
||||
sctp_transport.dtls_transport.role().await,
|
||||
)
|
||||
.await?,
|
||||
Ordering::SeqCst,
|
||||
);
|
||||
}
|
||||
|
||||
let dc = data::data_channel::DataChannel::dial(&association, self.id(), cfg).await?;
|
||||
|
||||
// buffered_amount_low_threshold and on_buffered_amount_low might be set earlier
|
||||
dc.set_buffered_amount_low_threshold(
|
||||
self.buffered_amount_low_threshold.load(Ordering::SeqCst),
|
||||
);
|
||||
{
|
||||
let mut on_buffered_amount_low = self.on_buffered_amount_low.lock().await;
|
||||
if let Some(f) = on_buffered_amount_low.take() {
|
||||
dc.on_buffered_amount_low(f);
|
||||
}
|
||||
}
|
||||
|
||||
self.handle_open(Arc::new(dc)).await;
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ErrSCTPNotEstablished)
|
||||
}
|
||||
}
|
||||
|
||||
/// transport returns the SCTPTransport instance the DataChannel is sending over.
|
||||
pub async fn transport(&self) -> Option<Weak<RTCSctpTransport>> {
|
||||
let sctp_transport = self.sctp_transport.lock().await;
|
||||
sctp_transport.clone()
|
||||
}
|
||||
|
||||
/// on_open sets an event handler which is invoked when
|
||||
/// the underlying data transport has been established (or re-established).
|
||||
pub fn on_open(&self, f: OnOpenHdlrFn) {
|
||||
let _ = self.on_open_handler.lock().replace(f);
|
||||
|
||||
if self.ready_state() == RTCDataChannelState::Open {
|
||||
self.do_open();
|
||||
}
|
||||
}
|
||||
|
||||
fn do_open(&self) {
|
||||
let on_open_handler = self.on_open_handler.lock().take();
|
||||
if on_open_handler.is_none() {
|
||||
return;
|
||||
}
|
||||
|
||||
let detach_data_channels = self.setting_engine.detach.data_channels;
|
||||
let detach_called = Arc::clone(&self.detach_called);
|
||||
tokio::spawn(async move {
|
||||
if let Some(f) = on_open_handler {
|
||||
f().await;
|
||||
|
||||
// self.check_detach_after_open();
|
||||
// After onOpen is complete check that the user called detach
|
||||
// and provide an error message if the call was missed
|
||||
if detach_data_channels && !detach_called.load(Ordering::SeqCst) {
|
||||
log::warn!(
|
||||
"webrtc.DetachDataChannels() enabled but didn't Detach, call Detach from OnOpen"
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// on_close sets an event handler which is invoked when
|
||||
/// the underlying data transport has been closed.
|
||||
pub fn on_close(&self, f: OnCloseHdlrFn) {
|
||||
self.on_close_handler.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// on_message sets an event handler which is invoked on a binary
|
||||
/// message arrival over the sctp transport from a remote peer.
|
||||
/// OnMessage can currently receive messages up to 16384 bytes
|
||||
/// in size. Check out the detach API if you want to use larger
|
||||
/// message sizes. Note that browser support for larger messages
|
||||
/// is also limited.
|
||||
pub fn on_message(&self, f: OnMessageHdlrFn) {
|
||||
self.on_message_handler.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
async fn do_message(&self, msg: DataChannelMessage) {
|
||||
if let Some(handler) = &*self.on_message_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(msg).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_open(&self, dc: Arc<data::data_channel::DataChannel>) {
|
||||
{
|
||||
let mut data_channel = self.data_channel.lock().await;
|
||||
*data_channel = Some(Arc::clone(&dc));
|
||||
}
|
||||
self.set_ready_state(RTCDataChannelState::Open);
|
||||
|
||||
self.do_open();
|
||||
|
||||
if !self.setting_engine.detach.data_channels {
|
||||
let ready_state = Arc::clone(&self.ready_state);
|
||||
let on_message_handler = Arc::clone(&self.on_message_handler);
|
||||
let on_close_handler = Arc::clone(&self.on_close_handler);
|
||||
let on_error_handler = Arc::clone(&self.on_error_handler);
|
||||
let notify_rx = self.notify_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
RTCDataChannel::read_loop(
|
||||
notify_rx,
|
||||
dc,
|
||||
ready_state,
|
||||
on_message_handler,
|
||||
on_close_handler,
|
||||
on_error_handler,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// on_error sets an event handler which is invoked when
|
||||
/// the underlying data transport cannot be read.
|
||||
pub fn on_error(&self, f: OnErrorHdlrFn) {
|
||||
self.on_error_handler.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
async fn read_loop(
|
||||
notify_rx: Arc<Notify>,
|
||||
data_channel: Arc<data::data_channel::DataChannel>,
|
||||
ready_state: Arc<AtomicU8>,
|
||||
on_message_handler: Arc<ArcSwapOption<Mutex<OnMessageHdlrFn>>>,
|
||||
on_close_handler: Arc<ArcSwapOption<Mutex<OnCloseHdlrFn>>>,
|
||||
on_error_handler: Arc<ArcSwapOption<Mutex<OnErrorHdlrFn>>>,
|
||||
) {
|
||||
let mut buffer = vec![0u8; DATA_CHANNEL_BUFFER_SIZE];
|
||||
loop {
|
||||
let (n, is_string) = tokio::select! {
|
||||
_ = notify_rx.notified() => break,
|
||||
result = data_channel.read_data_channel(&mut buffer) => {
|
||||
match result{
|
||||
// EOF (`data_channel` was either closed or the underlying stream got
|
||||
// reset by the remote) => close and run `on_close` handler.
|
||||
Ok((0, _)) =>
|
||||
{
|
||||
ready_state.store(RTCDataChannelState::Closed as u8, Ordering::SeqCst);
|
||||
|
||||
let on_close_handler2 = Arc::clone(&on_close_handler);
|
||||
tokio::spawn(async move {
|
||||
if let Some(handler) = &*on_close_handler2.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f().await;
|
||||
}
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
Ok((n, is_string)) => (n, is_string),
|
||||
Err(err) => {
|
||||
ready_state.store(RTCDataChannelState::Closed as u8, Ordering::SeqCst);
|
||||
|
||||
let on_error_handler2 = Arc::clone(&on_error_handler);
|
||||
tokio::spawn(async move {
|
||||
if let Some(handler) = &*on_error_handler2.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(err.into()).await;
|
||||
}
|
||||
});
|
||||
|
||||
let on_close_handler2 = Arc::clone(&on_close_handler);
|
||||
tokio::spawn(async move {
|
||||
if let Some(handler) = &*on_close_handler2.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f().await;
|
||||
}
|
||||
});
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Some(handler) = &*on_message_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(DataChannelMessage {
|
||||
is_string,
|
||||
data: Bytes::from(buffer[..n].to_vec()),
|
||||
})
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// send sends the binary message to the DataChannel peer
|
||||
pub async fn send(&self, data: &Bytes) -> Result<usize> {
|
||||
self.ensure_open()?;
|
||||
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
Ok(dc.write_data_channel(data, false).await?)
|
||||
} else {
|
||||
Err(Error::ErrClosedPipe)
|
||||
}
|
||||
}
|
||||
|
||||
/// send_text sends the text message to the DataChannel peer
|
||||
pub async fn send_text(&self, s: impl Into<String>) -> Result<usize> {
|
||||
self.ensure_open()?;
|
||||
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
Ok(dc.write_data_channel(&Bytes::from(s.into()), true).await?)
|
||||
} else {
|
||||
Err(Error::ErrClosedPipe)
|
||||
}
|
||||
}
|
||||
|
||||
fn ensure_open(&self) -> Result<()> {
|
||||
if self.ready_state() != RTCDataChannelState::Open {
|
||||
Err(Error::ErrClosedPipe)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// detach allows you to detach the underlying datachannel. This provides
|
||||
/// an idiomatic API to work with, however it disables the OnMessage callback.
|
||||
/// Before calling Detach you have to enable this behavior by calling
|
||||
/// webrtc.DetachDataChannels(). Combining detached and normal data channels
|
||||
/// is not supported.
|
||||
/// Please refer to the data-channels-detach example and the
|
||||
/// pion/datachannel documentation for the correct way to handle the
|
||||
/// resulting DataChannel object.
|
||||
pub async fn detach(&self) -> Result<Arc<data::data_channel::DataChannel>> {
|
||||
if !self.setting_engine.detach.data_channels {
|
||||
return Err(Error::ErrDetachNotEnabled);
|
||||
}
|
||||
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
self.detach_called.store(true, Ordering::SeqCst);
|
||||
|
||||
Ok(Arc::clone(dc))
|
||||
} else {
|
||||
Err(Error::ErrDetachBeforeOpened)
|
||||
}
|
||||
}
|
||||
|
||||
/// Close Closes the DataChannel. It may be called regardless of whether
|
||||
/// the DataChannel object was created by this peer or the remote peer.
|
||||
pub async fn close(&self) -> Result<()> {
|
||||
if self.ready_state() == RTCDataChannelState::Closed {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.set_ready_state(RTCDataChannelState::Closing);
|
||||
self.notify_tx.notify_waiters();
|
||||
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
Ok(dc.close().await?)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// label represents a label that can be used to distinguish this
|
||||
/// DataChannel object from other DataChannel objects. Scripts are
|
||||
/// allowed to create multiple DataChannel objects with the same label.
|
||||
pub fn label(&self) -> &str {
|
||||
self.label.as_str()
|
||||
}
|
||||
|
||||
/// Ordered returns true if the DataChannel is ordered, and false if
|
||||
/// out-of-order delivery is allowed.
|
||||
pub fn ordered(&self) -> bool {
|
||||
self.ordered
|
||||
}
|
||||
|
||||
/// max_packet_lifetime represents the length of the time window (msec) during
|
||||
/// which transmissions and retransmissions may occur in unreliable mode.
|
||||
pub fn max_packet_lifetime(&self) -> u16 {
|
||||
self.max_packet_lifetime
|
||||
}
|
||||
|
||||
/// max_retransmits represents the maximum number of retransmissions that are
|
||||
/// attempted in unreliable mode.
|
||||
pub fn max_retransmits(&self) -> u16 {
|
||||
self.max_retransmits
|
||||
}
|
||||
|
||||
/// protocol represents the name of the sub-protocol used with this
|
||||
/// DataChannel.
|
||||
pub fn protocol(&self) -> &str {
|
||||
self.protocol.as_str()
|
||||
}
|
||||
|
||||
/// negotiated represents whether this DataChannel was negotiated by the
|
||||
/// application (true), or not (false).
|
||||
pub fn negotiated(&self) -> bool {
|
||||
self.negotiated
|
||||
}
|
||||
|
||||
/// ID represents the ID for this DataChannel. The value is initially
|
||||
/// null, which is what will be returned if the ID was not provided at
|
||||
/// channel creation time, and the DTLS role of the SCTP transport has not
|
||||
/// yet been negotiated. Otherwise, it will return the ID that was either
|
||||
/// selected by the script or generated. After the ID is set to a non-null
|
||||
/// value, it will not change.
|
||||
pub fn id(&self) -> u16 {
|
||||
self.id.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// ready_state represents the state of the DataChannel object.
|
||||
pub fn ready_state(&self) -> RTCDataChannelState {
|
||||
self.ready_state.load(Ordering::SeqCst).into()
|
||||
}
|
||||
|
||||
/// buffered_amount represents the number of bytes of application data
|
||||
/// (UTF-8 text and binary data) that have been queued using send(). Even
|
||||
/// though the data transmission can occur in parallel, the returned value
|
||||
/// MUST NOT be decreased before the current task yielded back to the event
|
||||
/// loop to prevent race conditions. The value does not include framing
|
||||
/// overhead incurred by the protocol, or buffering done by the operating
|
||||
/// system or network hardware. The value of buffered_amount slot will only
|
||||
/// increase with each call to the send() method as long as the ready_state is
|
||||
/// open; however, buffered_amount does not reset to zero once the channel
|
||||
/// closes.
|
||||
pub async fn buffered_amount(&self) -> usize {
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
dc.buffered_amount()
|
||||
} else {
|
||||
0
|
||||
}
|
||||
}
|
||||
|
||||
/// buffered_amount_low_threshold represents the threshold at which the
|
||||
/// bufferedAmount is considered to be low. When the bufferedAmount decreases
|
||||
/// from above this threshold to equal or below it, the bufferedamountlow
|
||||
/// event fires. buffered_amount_low_threshold is initially zero on each new
|
||||
/// DataChannel, but the application may change its value at any time.
|
||||
/// The threshold is set to 0 by default.
|
||||
pub async fn buffered_amount_low_threshold(&self) -> usize {
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
dc.buffered_amount_low_threshold()
|
||||
} else {
|
||||
self.buffered_amount_low_threshold.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
/// set_buffered_amount_low_threshold is used to update the threshold.
|
||||
/// See buffered_amount_low_threshold().
|
||||
pub async fn set_buffered_amount_low_threshold(&self, th: usize) {
|
||||
self.buffered_amount_low_threshold
|
||||
.store(th, Ordering::SeqCst);
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
dc.set_buffered_amount_low_threshold(th);
|
||||
}
|
||||
}
|
||||
|
||||
/// on_buffered_amount_low sets an event handler which is invoked when
|
||||
/// the number of bytes of outgoing data becomes lower than the
|
||||
/// buffered_amount_low_threshold.
|
||||
pub async fn on_buffered_amount_low(&self, f: OnBufferedAmountLowFn) {
|
||||
let data_channel = self.data_channel.lock().await;
|
||||
if let Some(dc) = &*data_channel {
|
||||
dc.on_buffered_amount_low(f);
|
||||
} else {
|
||||
let mut on_buffered_amount_low = self.on_buffered_amount_low.lock().await;
|
||||
*on_buffered_amount_low = Some(f);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn get_stats_id(&self) -> &str {
|
||||
self.stats_id.as_str()
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(&self, collector: &StatsCollector) {
|
||||
let stats = DataChannelStats::from(self).await;
|
||||
collector.insert(self.stats_id.clone(), StatsReportType::DataChannel(stats));
|
||||
}
|
||||
|
||||
pub(crate) fn set_ready_state(&self, r: RTCDataChannelState) {
|
||||
self.ready_state.store(r as u8, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// DTLSFingerprint specifies the hash function algorithm and certificate
|
||||
/// fingerprint as described in <https://tools.ietf.org/html/rfc4572>.
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RTCDtlsFingerprint {
|
||||
/// Algorithm specifies one of the the hash function algorithms defined in
|
||||
/// the 'Hash function Textual Names' registry.
|
||||
pub algorithm: String,
|
||||
|
||||
/// Value specifies the value of the certificate fingerprint in lowercase
|
||||
/// hex string as expressed utilizing the syntax of 'fingerprint' in
|
||||
/// <https://tools.ietf.org/html/rfc4572#section-5>.
|
||||
pub value: String,
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::dtls_fingerprint::*;
|
||||
use super::dtls_role::*;
|
||||
|
||||
/// DTLSParameters holds information relating to DTLS configuration.
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct DTLSParameters {
|
||||
pub role: DTLSRole,
|
||||
pub fingerprints: Vec<RTCDtlsFingerprint>,
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
use std::fmt;
|
||||
|
||||
use sdp::description::session::SessionDescription;
|
||||
use sdp::util::ConnectionRole;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// DtlsRole indicates the role of the DTLS transport.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum DTLSRole {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// DTLSRoleAuto defines the DTLS role is determined based on
|
||||
/// the resolved ICE role: the ICE controlled role acts as the DTLS
|
||||
/// client and the ICE controlling role acts as the DTLS server.
|
||||
#[serde(rename = "auto")]
|
||||
Auto = 1,
|
||||
|
||||
/// DTLSRoleClient defines the DTLS client role.
|
||||
#[serde(rename = "client")]
|
||||
Client = 2,
|
||||
|
||||
/// DTLSRoleServer defines the DTLS server role.
|
||||
#[serde(rename = "server")]
|
||||
Server = 3,
|
||||
}
|
||||
|
||||
/// <https://tools.ietf.org/html/rfc5763>
|
||||
/// The answerer MUST use either a
|
||||
/// setup attribute value of setup:active or setup:passive. Note that
|
||||
/// if the answerer uses setup:passive, then the DTLS handshake will
|
||||
/// not begin until the answerer is received, which adds additional
|
||||
/// latency. setup:active allows the answer and the DTLS handshake to
|
||||
/// occur in parallel. Thus, setup:active is RECOMMENDED.
|
||||
pub(crate) const DEFAULT_DTLS_ROLE_ANSWER: DTLSRole = DTLSRole::Client;
|
||||
|
||||
/// The endpoint that is the offerer MUST use the setup attribute
|
||||
/// value of setup:actpass and be prepared to receive a client_hello
|
||||
/// before it receives the answer.
|
||||
pub(crate) const DEFAULT_DTLS_ROLE_OFFER: DTLSRole = DTLSRole::Auto;
|
||||
|
||||
impl fmt::Display for DTLSRole {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
DTLSRole::Auto => write!(f, "auto"),
|
||||
DTLSRole::Client => write!(f, "client"),
|
||||
DTLSRole::Server => write!(f, "server"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Iterate a SessionDescription from a remote to determine if an explicit
|
||||
/// role can been determined from it. The decision is made from the first role we we parse.
|
||||
/// If no role can be found we return DTLSRoleAuto
|
||||
impl From<&SessionDescription> for DTLSRole {
|
||||
fn from(session_description: &SessionDescription) -> Self {
|
||||
for media_section in &session_description.media_descriptions {
|
||||
for attribute in &media_section.attributes {
|
||||
if attribute.key == "setup" {
|
||||
if let Some(value) = &attribute.value {
|
||||
match value.as_str() {
|
||||
"active" => return DTLSRole::Client,
|
||||
"passive" => return DTLSRole::Server,
|
||||
_ => return DTLSRole::Auto,
|
||||
};
|
||||
} else {
|
||||
return DTLSRole::Auto;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
DTLSRole::Auto
|
||||
}
|
||||
}
|
||||
|
||||
impl DTLSRole {
|
||||
pub(crate) fn to_connection_role(self) -> ConnectionRole {
|
||||
match self {
|
||||
DTLSRole::Client => ConnectionRole::Active,
|
||||
DTLSRole::Server => ConnectionRole::Passive,
|
||||
DTLSRole::Auto => ConnectionRole::Actpass,
|
||||
_ => ConnectionRole::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::io::Cursor;
|
||||
|
||||
use super::*;
|
||||
use crate::error::Result;
|
||||
|
||||
#[test]
|
||||
fn test_dtls_role_string() {
|
||||
let tests = vec![
|
||||
(DTLSRole::Unspecified, "Unspecified"),
|
||||
(DTLSRole::Auto, "auto"),
|
||||
(DTLSRole::Client, "client"),
|
||||
(DTLSRole::Server, "server"),
|
||||
];
|
||||
|
||||
for (role, expected_string) in tests {
|
||||
assert_eq!(role.to_string(), expected_string)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dtls_role_from_remote_sdp() -> Result<()> {
|
||||
const NO_MEDIA: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
";
|
||||
|
||||
const MEDIA_NO_SETUP: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=application 47299 DTLS/SCTP 5000
|
||||
c=IN IP4 192.168.20.129
|
||||
";
|
||||
|
||||
const MEDIA_SETUP_DECLARED: &str = "v=0
|
||||
o=- 4596489990601351948 2 IN IP4 127.0.0.1
|
||||
s=-
|
||||
t=0 0
|
||||
m=application 47299 DTLS/SCTP 5000
|
||||
c=IN IP4 192.168.20.129
|
||||
a=setup:";
|
||||
|
||||
let tests = vec![
|
||||
("No MediaDescriptions", NO_MEDIA.to_owned(), DTLSRole::Auto),
|
||||
(
|
||||
"MediaDescription, no setup",
|
||||
MEDIA_NO_SETUP.to_owned(),
|
||||
DTLSRole::Auto,
|
||||
),
|
||||
(
|
||||
"MediaDescription, setup:actpass",
|
||||
format!("{}{}\n", MEDIA_SETUP_DECLARED, "actpass"),
|
||||
DTLSRole::Auto,
|
||||
),
|
||||
(
|
||||
"MediaDescription, setup:passive",
|
||||
format!("{}{}\n", MEDIA_SETUP_DECLARED, "passive"),
|
||||
DTLSRole::Server,
|
||||
),
|
||||
(
|
||||
"MediaDescription, setup:active",
|
||||
format!("{}{}\n", MEDIA_SETUP_DECLARED, "active"),
|
||||
DTLSRole::Client,
|
||||
),
|
||||
];
|
||||
|
||||
for (name, session_description_str, expected_role) in tests {
|
||||
let mut reader = Cursor::new(session_description_str.as_bytes());
|
||||
let session_description = SessionDescription::unmarshal(&mut reader)?;
|
||||
assert_eq!(
|
||||
DTLSRole::from(&session_description),
|
||||
expected_role,
|
||||
"{name} failed"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
use std::fmt;
|
||||
|
||||
/// DTLSTransportState indicates the DTLS transport establishment state.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCDtlsTransportState {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// DTLSTransportStateNew indicates that DTLS has not started negotiating
|
||||
/// yet.
|
||||
New = 1,
|
||||
|
||||
/// DTLSTransportStateConnecting indicates that DTLS is in the process of
|
||||
/// negotiating a secure connection and verifying the remote fingerprint.
|
||||
Connecting = 2,
|
||||
|
||||
/// DTLSTransportStateConnected indicates that DTLS has completed
|
||||
/// negotiation of a secure connection and verified the remote fingerprint.
|
||||
Connected = 3,
|
||||
|
||||
/// DTLSTransportStateClosed indicates that the transport has been closed
|
||||
/// intentionally as the result of receipt of a close_notify alert, or
|
||||
/// calling close().
|
||||
Closed = 4,
|
||||
|
||||
/// DTLSTransportStateFailed indicates that the transport has failed as
|
||||
/// the result of an error (such as receipt of an error alert or failure to
|
||||
/// validate the remote fingerprint).
|
||||
Failed = 5,
|
||||
}
|
||||
|
||||
const DTLS_TRANSPORT_STATE_NEW_STR: &str = "new";
|
||||
const DTLS_TRANSPORT_STATE_CONNECTING_STR: &str = "connecting";
|
||||
const DTLS_TRANSPORT_STATE_CONNECTED_STR: &str = "connected";
|
||||
const DTLS_TRANSPORT_STATE_CLOSED_STR: &str = "closed";
|
||||
const DTLS_TRANSPORT_STATE_FAILED_STR: &str = "failed";
|
||||
|
||||
impl From<&str> for RTCDtlsTransportState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
DTLS_TRANSPORT_STATE_NEW_STR => RTCDtlsTransportState::New,
|
||||
DTLS_TRANSPORT_STATE_CONNECTING_STR => RTCDtlsTransportState::Connecting,
|
||||
DTLS_TRANSPORT_STATE_CONNECTED_STR => RTCDtlsTransportState::Connected,
|
||||
DTLS_TRANSPORT_STATE_CLOSED_STR => RTCDtlsTransportState::Closed,
|
||||
DTLS_TRANSPORT_STATE_FAILED_STR => RTCDtlsTransportState::Failed,
|
||||
_ => RTCDtlsTransportState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCDtlsTransportState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCDtlsTransportState::New,
|
||||
2 => RTCDtlsTransportState::Connecting,
|
||||
3 => RTCDtlsTransportState::Connected,
|
||||
4 => RTCDtlsTransportState::Closed,
|
||||
5 => RTCDtlsTransportState::Failed,
|
||||
_ => RTCDtlsTransportState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCDtlsTransportState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCDtlsTransportState::New => DTLS_TRANSPORT_STATE_NEW_STR,
|
||||
RTCDtlsTransportState::Connecting => DTLS_TRANSPORT_STATE_CONNECTING_STR,
|
||||
RTCDtlsTransportState::Connected => DTLS_TRANSPORT_STATE_CONNECTED_STR,
|
||||
RTCDtlsTransportState::Closed => DTLS_TRANSPORT_STATE_CLOSED_STR,
|
||||
RTCDtlsTransportState::Failed => DTLS_TRANSPORT_STATE_FAILED_STR,
|
||||
RTCDtlsTransportState::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_dtls_transport_state() {
|
||||
let tests = vec![
|
||||
(crate::UNSPECIFIED_STR, RTCDtlsTransportState::Unspecified),
|
||||
("new", RTCDtlsTransportState::New),
|
||||
("connecting", RTCDtlsTransportState::Connecting),
|
||||
("connected", RTCDtlsTransportState::Connected),
|
||||
("closed", RTCDtlsTransportState::Closed),
|
||||
("failed", RTCDtlsTransportState::Failed),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(
|
||||
RTCDtlsTransportState::from(state_string),
|
||||
expected_state,
|
||||
"testCase: {expected_state}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_dtls_transport_state_string() {
|
||||
let tests = vec![
|
||||
(RTCDtlsTransportState::Unspecified, crate::UNSPECIFIED_STR),
|
||||
(RTCDtlsTransportState::New, "new"),
|
||||
(RTCDtlsTransportState::Connecting, "connecting"),
|
||||
(RTCDtlsTransportState::Connected, "connected"),
|
||||
(RTCDtlsTransportState::Closed, "closed"),
|
||||
(RTCDtlsTransportState::Failed, "failed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
use ice::mdns::MulticastDnsMode;
|
||||
use ice::network_type::NetworkType;
|
||||
use regex::Regex;
|
||||
use tokio::time::Duration;
|
||||
use waitgroup::WaitGroup;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::data_channel::RTCDataChannel;
|
||||
use crate::ice_transport::ice_candidate::RTCIceCandidate;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
use crate::peer_connection::peer_connection_state::RTCPeerConnectionState;
|
||||
use crate::peer_connection::peer_connection_test::{
|
||||
close_pair_now, new_pair, signal_pair, until_connection_state,
|
||||
};
|
||||
|
||||
//use log::LevelFilter;
|
||||
//use std::io::Write;
|
||||
|
||||
// An invalid fingerprint MUST cause PeerConnectionState to go to PeerConnectionStateFailed
|
||||
#[tokio::test]
|
||||
async fn test_invalid_fingerprint_causes_failed() -> Result<()> {
|
||||
/*env_logger::Builder::new()
|
||||
.format(|buf, record| {
|
||||
writeln!(
|
||||
buf,
|
||||
"{}:{} [{}] {} - {}",
|
||||
record.file().unwrap_or("unknown"),
|
||||
record.line().unwrap_or(0),
|
||||
record.level(),
|
||||
chrono::Local::now().format("%H:%M:%S.%6f"),
|
||||
record.args()
|
||||
)
|
||||
})
|
||||
.filter(None, LevelFilter::Trace)
|
||||
.init();*/
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut pc_offer, mut pc_answer) = new_pair(&api).await?;
|
||||
|
||||
pc_answer.on_data_channel(Box::new(|_: Arc<RTCDataChannel>| {
|
||||
panic!("A DataChannel must not be created when Fingerprint verification fails");
|
||||
}));
|
||||
|
||||
let (offer_chan_tx, mut offer_chan_rx) = mpsc::channel::<()>(1);
|
||||
|
||||
let offer_chan_tx = Arc::new(offer_chan_tx);
|
||||
pc_offer.on_ice_candidate(Box::new(move |candidate: Option<RTCIceCandidate>| {
|
||||
let offer_chan_tx2 = Arc::clone(&offer_chan_tx);
|
||||
Box::pin(async move {
|
||||
if candidate.is_none() {
|
||||
let _ = offer_chan_tx2.send(()).await;
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
let offer_connection_has_failed = WaitGroup::new();
|
||||
until_connection_state(
|
||||
&mut pc_offer,
|
||||
&offer_connection_has_failed,
|
||||
RTCPeerConnectionState::Failed,
|
||||
)
|
||||
.await;
|
||||
let answer_connection_has_failed = WaitGroup::new();
|
||||
until_connection_state(
|
||||
&mut pc_answer,
|
||||
&answer_connection_has_failed,
|
||||
RTCPeerConnectionState::Failed,
|
||||
)
|
||||
.await;
|
||||
|
||||
let _ = pc_offer
|
||||
.create_data_channel("unusedDataChannel", None)
|
||||
.await?;
|
||||
|
||||
let offer = pc_offer.create_offer(None).await?;
|
||||
pc_offer.set_local_description(offer).await?;
|
||||
|
||||
let timeout = tokio::time::sleep(Duration::from_secs(1));
|
||||
tokio::pin!(timeout);
|
||||
|
||||
tokio::select! {
|
||||
_ = offer_chan_rx.recv() =>{
|
||||
let mut offer = pc_offer.pending_local_description().await.unwrap();
|
||||
|
||||
log::trace!("receiving pending local desc: {:?}", offer);
|
||||
|
||||
// Replace with invalid fingerprint
|
||||
let re = Regex::new(r"sha-256 (.*?)\r").unwrap();
|
||||
offer.sdp = re.replace_all(offer.sdp.as_str(), "sha-256 AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA\r").to_string();
|
||||
|
||||
pc_answer.set_remote_description(offer).await?;
|
||||
|
||||
let mut answer = pc_answer.create_answer(None).await?;
|
||||
|
||||
pc_answer.set_local_description(answer.clone()).await?;
|
||||
|
||||
answer.sdp = re.replace_all(answer.sdp.as_str(), "sha-256 AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA:AA\r").to_string();
|
||||
|
||||
pc_offer.set_remote_description(answer).await?;
|
||||
}
|
||||
_ = timeout.as_mut() =>{
|
||||
panic!("timed out waiting to receive offer");
|
||||
}
|
||||
}
|
||||
|
||||
log::trace!("offer_connection_has_failed wait begin");
|
||||
|
||||
offer_connection_has_failed.wait().await;
|
||||
answer_connection_has_failed.wait().await;
|
||||
|
||||
log::trace!("offer_connection_has_failed wait end");
|
||||
{
|
||||
let transport = pc_offer.sctp().transport();
|
||||
assert_eq!(transport.state(), RTCDtlsTransportState::Failed);
|
||||
assert!(transport.conn().await.is_none());
|
||||
}
|
||||
|
||||
{
|
||||
let transport = pc_answer.sctp().transport();
|
||||
assert_eq!(transport.state(), RTCDtlsTransportState::Failed);
|
||||
assert!(transport.conn().await.is_none());
|
||||
}
|
||||
|
||||
close_pair_now(&pc_offer, &pc_answer).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn run_test(r: DTLSRole) -> Result<()> {
|
||||
let mut offer_s = SettingEngine::default();
|
||||
offer_s.set_answering_dtls_role(r)?;
|
||||
offer_s.set_ice_multicast_dns_mode(MulticastDnsMode::Disabled);
|
||||
offer_s.set_network_types(vec![NetworkType::Udp4]);
|
||||
let mut offer_pc = APIBuilder::new()
|
||||
.with_setting_engine(offer_s)
|
||||
.build()
|
||||
.new_peer_connection(RTCConfiguration::default())
|
||||
.await?;
|
||||
|
||||
let mut answer_s = SettingEngine::default();
|
||||
answer_s.set_answering_dtls_role(r)?;
|
||||
answer_s.set_ice_multicast_dns_mode(MulticastDnsMode::Disabled);
|
||||
answer_s.set_network_types(vec![NetworkType::Udp4]);
|
||||
let mut answer_pc = APIBuilder::new()
|
||||
.with_setting_engine(answer_s)
|
||||
.build()
|
||||
.new_peer_connection(RTCConfiguration::default())
|
||||
.await?;
|
||||
|
||||
signal_pair(&mut offer_pc, &mut answer_pc).await?;
|
||||
|
||||
let wg = WaitGroup::new();
|
||||
until_connection_state(&mut answer_pc, &wg, RTCPeerConnectionState::Connected).await;
|
||||
wg.wait().await;
|
||||
|
||||
close_pair_now(&offer_pc, &answer_pc).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_peer_connection_dtls_role_setting_engine_server() -> Result<()> {
|
||||
/*env_logger::Builder::new()
|
||||
.format(|buf, record| {
|
||||
writeln!(
|
||||
buf,
|
||||
"{}:{} [{}] {} - {}",
|
||||
record.file().unwrap_or("unknown"),
|
||||
record.line().unwrap_or(0),
|
||||
record.level(),
|
||||
chrono::Local::now().format("%H:%M:%S.%6f"),
|
||||
record.args()
|
||||
)
|
||||
})
|
||||
.filter(None, LevelFilter::Trace)
|
||||
.init();*/
|
||||
|
||||
run_test(DTLSRole::Server).await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_peer_connection_dtls_role_setting_engine_client() -> Result<()> {
|
||||
/*env_logger::Builder::new()
|
||||
.format(|buf, record| {
|
||||
writeln!(
|
||||
buf,
|
||||
"{}:{} [{}] {} - {}",
|
||||
record.file().unwrap_or("unknown"),
|
||||
record.line().unwrap_or(0),
|
||||
record.level(),
|
||||
chrono::Local::now().format("%H:%M:%S.%6f"),
|
||||
record.args()
|
||||
)
|
||||
})
|
||||
.filter(None, LevelFilter::Trace)
|
||||
.init();*/
|
||||
|
||||
run_test(DTLSRole::Client).await
|
||||
}
|
||||
+616
@@ -0,0 +1,616 @@
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use bytes::Bytes;
|
||||
use dtls::config::ClientAuthType;
|
||||
use dtls::conn::DTLSConn;
|
||||
use dtls::extension::extension_use_srtp::SrtpProtectionProfile;
|
||||
use dtls_role::*;
|
||||
use interceptor::stream_info::StreamInfo;
|
||||
use interceptor::{Interceptor, RTCPReader, RTPReader};
|
||||
use sha2::{Digest, Sha256};
|
||||
use srtp::protection_profile::ProtectionProfile;
|
||||
use srtp::session::Session;
|
||||
use srtp::stream::Stream;
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use util::Conn;
|
||||
|
||||
use crate::api::setting_engine::SettingEngine;
|
||||
use crate::dtls_transport::dtls_parameters::DTLSParameters;
|
||||
use crate::dtls_transport::dtls_transport_state::RTCDtlsTransportState;
|
||||
use crate::error::{flatten_errs, Error, Result};
|
||||
use crate::ice_transport::ice_role::RTCIceRole;
|
||||
use crate::ice_transport::ice_transport_state::RTCIceTransportState;
|
||||
use crate::ice_transport::RTCIceTransport;
|
||||
use crate::mux::endpoint::Endpoint;
|
||||
use crate::mux::mux_func::{match_dtls, match_srtcp, match_srtp, MatchFunc};
|
||||
use crate::peer_connection::certificate::RTCCertificate;
|
||||
use crate::rtp_transceiver::SSRC;
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
|
||||
#[cfg(test)]
|
||||
mod dtls_transport_test;
|
||||
|
||||
pub mod dtls_fingerprint;
|
||||
pub mod dtls_parameters;
|
||||
pub mod dtls_role;
|
||||
pub mod dtls_transport_state;
|
||||
|
||||
pub(crate) fn default_srtp_protection_profiles() -> Vec<SrtpProtectionProfile> {
|
||||
vec![
|
||||
SrtpProtectionProfile::Srtp_Aead_Aes_128_Gcm,
|
||||
SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80,
|
||||
]
|
||||
}
|
||||
|
||||
pub type OnDTLSTransportStateChangeHdlrFn = Box<
|
||||
dyn (FnMut(RTCDtlsTransportState) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
/// DTLSTransport allows an application access to information about the DTLS
|
||||
/// transport over which RTP and RTCP packets are sent and received by
|
||||
/// RTPSender and RTPReceiver, as well other data such as SCTP packets sent
|
||||
/// and received by data channels.
|
||||
#[derive(Default)]
|
||||
pub struct RTCDtlsTransport {
|
||||
pub(crate) ice_transport: Arc<RTCIceTransport>,
|
||||
pub(crate) certificates: Vec<RTCCertificate>,
|
||||
pub(crate) setting_engine: Arc<SettingEngine>,
|
||||
|
||||
pub(crate) remote_parameters: Mutex<DTLSParameters>,
|
||||
pub(crate) remote_certificate: Mutex<Bytes>,
|
||||
pub(crate) state: AtomicU8, //DTLSTransportState,
|
||||
pub(crate) srtp_protection_profile: Mutex<ProtectionProfile>,
|
||||
pub(crate) on_state_change_handler: ArcSwapOption<Mutex<OnDTLSTransportStateChangeHdlrFn>>,
|
||||
pub(crate) conn: Mutex<Option<Arc<DTLSConn>>>,
|
||||
|
||||
pub(crate) srtp_session: Mutex<Option<Arc<Session>>>,
|
||||
pub(crate) srtcp_session: Mutex<Option<Arc<Session>>>,
|
||||
pub(crate) srtp_endpoint: Mutex<Option<Arc<Endpoint>>>,
|
||||
pub(crate) srtcp_endpoint: Mutex<Option<Arc<Endpoint>>>,
|
||||
|
||||
pub(crate) simulcast_streams: Mutex<HashMap<SSRC, Arc<Stream>>>,
|
||||
|
||||
pub(crate) srtp_ready_signal: Arc<AtomicBool>,
|
||||
pub(crate) srtp_ready_tx: Mutex<Option<mpsc::Sender<()>>>,
|
||||
pub(crate) srtp_ready_rx: Mutex<Option<mpsc::Receiver<()>>>,
|
||||
|
||||
pub(crate) dtls_matcher: Option<MatchFunc>,
|
||||
}
|
||||
|
||||
impl RTCDtlsTransport {
|
||||
pub(crate) fn new(
|
||||
ice_transport: Arc<RTCIceTransport>,
|
||||
certificates: Vec<RTCCertificate>,
|
||||
setting_engine: Arc<SettingEngine>,
|
||||
) -> Self {
|
||||
let (srtp_ready_tx, srtp_ready_rx) = mpsc::channel(1);
|
||||
RTCDtlsTransport {
|
||||
ice_transport,
|
||||
certificates,
|
||||
setting_engine,
|
||||
srtp_ready_signal: Arc::new(AtomicBool::new(false)),
|
||||
srtp_ready_tx: Mutex::new(Some(srtp_ready_tx)),
|
||||
srtp_ready_rx: Mutex::new(Some(srtp_ready_rx)),
|
||||
state: AtomicU8::new(RTCDtlsTransportState::New as u8),
|
||||
dtls_matcher: Some(Box::new(match_dtls)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn conn(&self) -> Option<Arc<DTLSConn>> {
|
||||
let conn = self.conn.lock().await;
|
||||
conn.clone()
|
||||
}
|
||||
|
||||
/// returns the currently-configured ICETransport or None
|
||||
/// if one has not been configured
|
||||
pub fn ice_transport(&self) -> &RTCIceTransport {
|
||||
&self.ice_transport
|
||||
}
|
||||
|
||||
/// state_change requires the caller holds the lock
|
||||
async fn state_change(&self, state: RTCDtlsTransportState) {
|
||||
self.state.store(state as u8, Ordering::SeqCst);
|
||||
if let Some(handler) = &*self.on_state_change_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(state).await;
|
||||
}
|
||||
}
|
||||
|
||||
/// on_state_change sets a handler that is fired when the DTLS
|
||||
/// connection state changes.
|
||||
pub fn on_state_change(&self, f: OnDTLSTransportStateChangeHdlrFn) {
|
||||
self.on_state_change_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// state returns the current dtls_transport transport state.
|
||||
pub fn state(&self) -> RTCDtlsTransportState {
|
||||
self.state.load(Ordering::SeqCst).into()
|
||||
}
|
||||
|
||||
/// write_rtcp sends a user provided RTCP packet to the connected peer. If no peer is connected the
|
||||
/// packet is discarded.
|
||||
pub async fn write_rtcp(
|
||||
&self,
|
||||
pkts: &[Box<dyn rtcp::packet::Packet + Send + Sync>],
|
||||
) -> Result<usize> {
|
||||
let srtcp_session = self.srtcp_session.lock().await;
|
||||
if let Some(srtcp_session) = &*srtcp_session {
|
||||
let raw = rtcp::packet::marshal(pkts)?;
|
||||
Ok(srtcp_session.write(&raw, false).await?)
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
/// get_local_parameters returns the DTLS parameters of the local DTLSTransport upon construction.
|
||||
pub fn get_local_parameters(&self) -> Result<DTLSParameters> {
|
||||
let mut fingerprints = vec![];
|
||||
|
||||
for c in &self.certificates {
|
||||
fingerprints.extend(c.get_fingerprints());
|
||||
}
|
||||
|
||||
Ok(DTLSParameters {
|
||||
role: DTLSRole::Auto, // always returns the default role
|
||||
fingerprints,
|
||||
})
|
||||
}
|
||||
|
||||
/// get_remote_certificate returns the certificate chain in use by the remote side
|
||||
/// returns an empty list prior to selection of the remote certificate
|
||||
pub async fn get_remote_certificate(&self) -> Bytes {
|
||||
let remote_certificate = self.remote_certificate.lock().await;
|
||||
remote_certificate.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn start_srtp(&self) -> Result<()> {
|
||||
let profile = {
|
||||
let srtp_protection_profile = self.srtp_protection_profile.lock().await;
|
||||
*srtp_protection_profile
|
||||
};
|
||||
|
||||
let mut srtp_config = srtp::config::Config {
|
||||
profile,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if self.setting_engine.replay_protection.srtp != 0 {
|
||||
srtp_config.remote_rtp_options = Some(srtp::option::srtp_replay_protection(
|
||||
self.setting_engine.replay_protection.srtp,
|
||||
));
|
||||
} else if self.setting_engine.disable_srtp_replay_protection {
|
||||
srtp_config.remote_rtp_options = Some(srtp::option::srtp_no_replay_protection());
|
||||
}
|
||||
|
||||
if let Some(conn) = self.conn().await {
|
||||
let conn_state = conn.connection_state().await;
|
||||
srtp_config
|
||||
.extract_session_keys_from_dtls(conn_state, self.role().await == DTLSRole::Client)
|
||||
.await?;
|
||||
} else {
|
||||
return Err(Error::ErrDtlsTransportNotStarted);
|
||||
}
|
||||
|
||||
{
|
||||
let mut srtp_session = self.srtp_session.lock().await;
|
||||
*srtp_session = {
|
||||
let se = self.srtp_endpoint.lock().await;
|
||||
if let Some(srtp_endpoint) = &*se {
|
||||
Some(Arc::new(
|
||||
Session::new(
|
||||
Arc::clone(srtp_endpoint) as Arc<dyn Conn + Send + Sync>,
|
||||
srtp_config,
|
||||
true,
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let mut srtcp_config = srtp::config::Config {
|
||||
profile,
|
||||
..Default::default()
|
||||
};
|
||||
if self.setting_engine.replay_protection.srtcp != 0 {
|
||||
srtcp_config.remote_rtcp_options = Some(srtp::option::srtcp_replay_protection(
|
||||
self.setting_engine.replay_protection.srtcp,
|
||||
));
|
||||
} else if self.setting_engine.disable_srtcp_replay_protection {
|
||||
srtcp_config.remote_rtcp_options = Some(srtp::option::srtcp_no_replay_protection());
|
||||
}
|
||||
|
||||
if let Some(conn) = self.conn().await {
|
||||
let conn_state = conn.connection_state().await;
|
||||
srtcp_config
|
||||
.extract_session_keys_from_dtls(conn_state, self.role().await == DTLSRole::Client)
|
||||
.await?;
|
||||
} else {
|
||||
return Err(Error::ErrDtlsTransportNotStarted);
|
||||
}
|
||||
|
||||
{
|
||||
let mut srtcp_session = self.srtcp_session.lock().await;
|
||||
*srtcp_session = {
|
||||
let se = self.srtcp_endpoint.lock().await;
|
||||
if let Some(srtcp_endpoint) = &*se {
|
||||
Some(Arc::new(
|
||||
Session::new(
|
||||
Arc::clone(srtcp_endpoint) as Arc<dyn Conn + Send + Sync>,
|
||||
srtcp_config,
|
||||
false,
|
||||
)
|
||||
.await?,
|
||||
))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
{
|
||||
let mut srtp_ready_tx = self.srtp_ready_tx.lock().await;
|
||||
srtp_ready_tx.take();
|
||||
if srtp_ready_tx.is_none() {
|
||||
self.srtp_ready_signal.store(true, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn get_srtp_session(&self) -> Option<Arc<Session>> {
|
||||
let srtp_session = self.srtp_session.lock().await;
|
||||
srtp_session.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn get_srtcp_session(&self) -> Option<Arc<Session>> {
|
||||
let srtcp_session = self.srtcp_session.lock().await;
|
||||
srtcp_session.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn role(&self) -> DTLSRole {
|
||||
// If remote has an explicit role use the inverse
|
||||
{
|
||||
let remote_parameters = self.remote_parameters.lock().await;
|
||||
match remote_parameters.role {
|
||||
DTLSRole::Client => return DTLSRole::Server,
|
||||
DTLSRole::Server => return DTLSRole::Client,
|
||||
_ => {}
|
||||
};
|
||||
}
|
||||
|
||||
// If SettingEngine has an explicit role
|
||||
match self.setting_engine.answering_dtls_role {
|
||||
DTLSRole::Server => return DTLSRole::Server,
|
||||
DTLSRole::Client => return DTLSRole::Client,
|
||||
_ => {}
|
||||
};
|
||||
|
||||
// Remote was auto and no explicit role was configured via SettingEngine
|
||||
if self.ice_transport.role().await == RTCIceRole::Controlling {
|
||||
return DTLSRole::Server;
|
||||
}
|
||||
|
||||
DEFAULT_DTLS_ROLE_ANSWER
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(&self, collector: &StatsCollector) {
|
||||
for cert in &self.certificates {
|
||||
cert.collect_stats(collector).await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn prepare_transport(
|
||||
&self,
|
||||
remote_parameters: DTLSParameters,
|
||||
) -> Result<(DTLSRole, dtls::config::Config)> {
|
||||
self.ensure_ice_conn()?;
|
||||
|
||||
if self.state() != RTCDtlsTransportState::New {
|
||||
return Err(Error::ErrInvalidDTLSStart);
|
||||
}
|
||||
|
||||
{
|
||||
let mut srtp_endpoint = self.srtp_endpoint.lock().await;
|
||||
*srtp_endpoint = self.ice_transport.new_endpoint(Box::new(match_srtp)).await;
|
||||
}
|
||||
{
|
||||
let mut srtcp_endpoint = self.srtcp_endpoint.lock().await;
|
||||
*srtcp_endpoint = self.ice_transport.new_endpoint(Box::new(match_srtcp)).await;
|
||||
}
|
||||
{
|
||||
let mut rp = self.remote_parameters.lock().await;
|
||||
*rp = remote_parameters;
|
||||
}
|
||||
|
||||
let certificate = if let Some(cert) = self.certificates.first() {
|
||||
cert.dtls_certificate.clone()
|
||||
} else {
|
||||
return Err(Error::ErrNonCertificate);
|
||||
};
|
||||
self.state_change(RTCDtlsTransportState::Connecting).await;
|
||||
|
||||
Ok((
|
||||
self.role().await,
|
||||
dtls::config::Config {
|
||||
certificates: vec![certificate],
|
||||
srtp_protection_profiles: if !self
|
||||
.setting_engine
|
||||
.srtp_protection_profiles
|
||||
.is_empty()
|
||||
{
|
||||
self.setting_engine.srtp_protection_profiles.clone()
|
||||
} else {
|
||||
default_srtp_protection_profiles()
|
||||
},
|
||||
client_auth: ClientAuthType::RequireAnyClientCert,
|
||||
insecure_skip_verify: true,
|
||||
insecure_verification: self.setting_engine.allow_insecure_verification_algorithm,
|
||||
..Default::default()
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/// start DTLS transport negotiation with the parameters of the remote DTLS transport
|
||||
pub async fn start(&self, remote_parameters: DTLSParameters) -> Result<()> {
|
||||
let dtls_conn_result = if let Some(dtls_endpoint) =
|
||||
self.ice_transport.new_endpoint(Box::new(match_dtls)).await
|
||||
{
|
||||
let (role, mut dtls_config) = self.prepare_transport(remote_parameters).await?;
|
||||
if self.setting_engine.replay_protection.dtls != 0 {
|
||||
dtls_config.replay_protection_window = self.setting_engine.replay_protection.dtls;
|
||||
}
|
||||
|
||||
// Connect as DTLS Client/Server, function is blocking and we
|
||||
// must not hold the DTLSTransport lock
|
||||
if role == DTLSRole::Client {
|
||||
dtls::conn::DTLSConn::new(
|
||||
dtls_endpoint as Arc<dyn Conn + Send + Sync>,
|
||||
dtls_config,
|
||||
true,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
dtls::conn::DTLSConn::new(
|
||||
dtls_endpoint as Arc<dyn Conn + Send + Sync>,
|
||||
dtls_config,
|
||||
false,
|
||||
None,
|
||||
)
|
||||
.await
|
||||
}
|
||||
} else {
|
||||
Err(dtls::Error::Other(
|
||||
"ice_transport.new_endpoint failed".to_owned(),
|
||||
))
|
||||
};
|
||||
|
||||
let dtls_conn = match dtls_conn_result {
|
||||
Ok(dtls_conn) => dtls_conn,
|
||||
Err(err) => {
|
||||
self.state_change(RTCDtlsTransportState::Failed).await;
|
||||
return Err(err.into());
|
||||
}
|
||||
};
|
||||
|
||||
let srtp_profile = dtls_conn.selected_srtpprotection_profile();
|
||||
{
|
||||
let mut srtp_protection_profile = self.srtp_protection_profile.lock().await;
|
||||
*srtp_protection_profile = match srtp_profile {
|
||||
dtls::extension::extension_use_srtp::SrtpProtectionProfile::Srtp_Aead_Aes_128_Gcm => {
|
||||
srtp::protection_profile::ProtectionProfile::AeadAes128Gcm
|
||||
}
|
||||
dtls::extension::extension_use_srtp::SrtpProtectionProfile::Srtp_Aes128_Cm_Hmac_Sha1_80 => {
|
||||
srtp::protection_profile::ProtectionProfile::Aes128CmHmacSha1_80
|
||||
}
|
||||
_ => {
|
||||
if let Err(err) = dtls_conn.close().await {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
self.state_change(RTCDtlsTransportState::Failed).await;
|
||||
return Err(Error::ErrNoSRTPProtectionProfile);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// Check the fingerprint if a certificate was exchanged
|
||||
let remote_certs = &dtls_conn.connection_state().await.peer_certificates;
|
||||
if remote_certs.is_empty() {
|
||||
if let Err(err) = dtls_conn.close().await {
|
||||
log::error!("{}", err);
|
||||
}
|
||||
|
||||
self.state_change(RTCDtlsTransportState::Failed).await;
|
||||
return Err(Error::ErrNoRemoteCertificate);
|
||||
}
|
||||
|
||||
{
|
||||
let mut remote_certificate = self.remote_certificate.lock().await;
|
||||
*remote_certificate = Bytes::from(remote_certs[0].clone());
|
||||
}
|
||||
|
||||
if !self
|
||||
.setting_engine
|
||||
.disable_certificate_fingerprint_verification
|
||||
{
|
||||
if let Err(err) = self.validate_fingerprint(&remote_certs[0]).await {
|
||||
if let Err(close_err) = dtls_conn.close().await {
|
||||
log::error!("{}", close_err);
|
||||
}
|
||||
|
||||
self.state_change(RTCDtlsTransportState::Failed).await;
|
||||
return Err(err);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let mut conn = self.conn.lock().await;
|
||||
*conn = Some(Arc::new(dtls_conn));
|
||||
}
|
||||
self.state_change(RTCDtlsTransportState::Connected).await;
|
||||
|
||||
self.start_srtp().await
|
||||
}
|
||||
|
||||
/// stops and closes the DTLSTransport object.
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
// Try closing everything and collect the errors
|
||||
let mut close_errs: Vec<Error> = vec![];
|
||||
{
|
||||
let srtp_session = {
|
||||
let mut srtp_session = self.srtp_session.lock().await;
|
||||
srtp_session.take()
|
||||
};
|
||||
if let Some(srtp_session) = srtp_session {
|
||||
match srtp_session.close().await {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
close_errs.push(err.into());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let srtcp_session = {
|
||||
let mut srtcp_session = self.srtcp_session.lock().await;
|
||||
srtcp_session.take()
|
||||
};
|
||||
if let Some(srtcp_session) = srtcp_session {
|
||||
match srtcp_session.close().await {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
close_errs.push(err.into());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let simulcast_streams: Vec<Arc<Stream>> = {
|
||||
let mut simulcast_streams = self.simulcast_streams.lock().await;
|
||||
simulcast_streams.drain().map(|(_, v)| v).collect()
|
||||
};
|
||||
for ss in simulcast_streams {
|
||||
match ss.close().await {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
close_errs.push(Error::new(format!(
|
||||
"simulcast_streams ssrc={}: {}",
|
||||
ss.get_ssrc(),
|
||||
err
|
||||
)));
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(conn) = self.conn().await {
|
||||
// dtls_transport connection may be closed on sctp close.
|
||||
match conn.close().await {
|
||||
Ok(_) => {}
|
||||
Err(err) => {
|
||||
if err.to_string() != dtls::Error::ErrConnClosed.to_string() {
|
||||
close_errs.push(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.state_change(RTCDtlsTransportState::Closed).await;
|
||||
|
||||
flatten_errs(close_errs)
|
||||
}
|
||||
|
||||
pub(crate) async fn validate_fingerprint(&self, remote_cert: &[u8]) -> Result<()> {
|
||||
let remote_parameters = self.remote_parameters.lock().await;
|
||||
for fp in &remote_parameters.fingerprints {
|
||||
if fp.algorithm != "sha-256" {
|
||||
return Err(Error::ErrUnsupportedFingerprintAlgorithm);
|
||||
}
|
||||
|
||||
let mut h = Sha256::new();
|
||||
h.update(remote_cert);
|
||||
let hashed = h.finalize();
|
||||
let values: Vec<String> = hashed.iter().map(|x| format! {"{x:02x}"}).collect();
|
||||
let remote_value = values.join(":").to_lowercase();
|
||||
|
||||
if remote_value == fp.value.to_lowercase() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::ErrNoMatchingCertificateFingerprint)
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_ice_conn(&self) -> Result<()> {
|
||||
if self.ice_transport.state() == RTCIceTransportState::New {
|
||||
Err(Error::ErrICEConnectionNotStarted)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn store_simulcast_stream(&self, ssrc: SSRC, stream: Arc<Stream>) {
|
||||
let mut simulcast_streams = self.simulcast_streams.lock().await;
|
||||
simulcast_streams.insert(ssrc, stream);
|
||||
}
|
||||
|
||||
pub(crate) async fn remove_simulcast_stream(&self, ssrc: SSRC) {
|
||||
let mut simulcast_streams = self.simulcast_streams.lock().await;
|
||||
simulcast_streams.remove(&ssrc);
|
||||
}
|
||||
|
||||
pub(crate) async fn streams_for_ssrc(
|
||||
&self,
|
||||
ssrc: SSRC,
|
||||
stream_info: &StreamInfo,
|
||||
interceptor: &Arc<dyn Interceptor + Send + Sync>,
|
||||
) -> Result<(
|
||||
Arc<srtp::stream::Stream>,
|
||||
Arc<dyn RTPReader + Send + Sync>,
|
||||
Arc<srtp::stream::Stream>,
|
||||
Arc<dyn RTCPReader + Send + Sync>,
|
||||
)> {
|
||||
let srtp_session = self
|
||||
.get_srtp_session()
|
||||
.await
|
||||
.ok_or(Error::ErrDtlsTransportNotStarted)?;
|
||||
//log::debug!("streams_for_ssrc: srtp_session.listen ssrc={}", ssrc);
|
||||
let rtp_read_stream = srtp_session.open(ssrc).await;
|
||||
let rtp_stream_reader = Arc::clone(&rtp_read_stream) as Arc<dyn RTPReader + Send + Sync>;
|
||||
let rtp_interceptor = interceptor
|
||||
.bind_remote_stream(stream_info, rtp_stream_reader)
|
||||
.await;
|
||||
|
||||
let srtcp_session = self
|
||||
.get_srtcp_session()
|
||||
.await
|
||||
.ok_or(Error::ErrDtlsTransportNotStarted)?;
|
||||
//log::debug!("streams_for_ssrc: srtcp_session.listen ssrc={}", ssrc);
|
||||
let rtcp_read_stream = srtcp_session.open(ssrc).await;
|
||||
let rtcp_stream_reader = Arc::clone(&rtcp_read_stream) as Arc<dyn RTCPReader + Send + Sync>;
|
||||
let rtcp_interceptor = interceptor.bind_rtcp_reader(rtcp_stream_reader).await;
|
||||
|
||||
Ok((
|
||||
rtp_read_stream,
|
||||
rtp_interceptor,
|
||||
rtcp_read_stream,
|
||||
rtcp_interceptor,
|
||||
))
|
||||
}
|
||||
}
|
||||
Vendored
+463
@@ -0,0 +1,463 @@
|
||||
use std::future::Future;
|
||||
use std::num::ParseIntError;
|
||||
use std::pin::Pin;
|
||||
use std::string::FromUtf8Error;
|
||||
|
||||
use rcgen::RcgenError;
|
||||
use thiserror::Error;
|
||||
use tokio::sync::mpsc::error::SendError as MpscSendError;
|
||||
|
||||
use crate::peer_connection::sdp::sdp_type::RTCSdpType;
|
||||
use crate::peer_connection::signaling_state::RTCSignalingState;
|
||||
use crate::rtp_transceiver::rtp_receiver;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
#[derive(Error, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Error {
|
||||
/// ErrUnknownType indicates an error with Unknown info.
|
||||
#[error("unknown")]
|
||||
ErrUnknownType,
|
||||
|
||||
/// ErrConnectionClosed indicates an operation executed after connection
|
||||
/// has already been closed.
|
||||
#[error("connection closed")]
|
||||
ErrConnectionClosed,
|
||||
|
||||
/// ErrDataChannelNotOpen indicates an operation executed when the data
|
||||
/// channel is not (yet) open.
|
||||
#[error("data channel not open")]
|
||||
ErrDataChannelNotOpen,
|
||||
|
||||
/// ErrCertificateExpired indicates that an x509 certificate has expired.
|
||||
#[error("x509Cert expired")]
|
||||
ErrCertificateExpired,
|
||||
|
||||
/// ErrNoTurnCredentials indicates that a TURN server URL was provided
|
||||
/// without required credentials.
|
||||
#[error("turn server credentials required")]
|
||||
ErrNoTurnCredentials,
|
||||
|
||||
/// ErrTurnCredentials indicates that provided TURN credentials are partial
|
||||
/// or malformed.
|
||||
#[error("invalid turn server credentials")]
|
||||
ErrTurnCredentials,
|
||||
|
||||
/// ErrExistingTrack indicates that a track already exists.
|
||||
#[error("track already exists")]
|
||||
ErrExistingTrack,
|
||||
|
||||
/// ErrPrivateKeyType indicates that a particular private key encryption
|
||||
/// chosen to generate a certificate is not supported.
|
||||
#[error("private key type not supported")]
|
||||
ErrPrivateKeyType,
|
||||
|
||||
/// ErrModifyingPeerIdentity indicates that an attempt to modify
|
||||
/// PeerIdentity was made after PeerConnection has been initialized.
|
||||
#[error("peerIdentity cannot be modified")]
|
||||
ErrModifyingPeerIdentity,
|
||||
|
||||
/// ErrModifyingCertificates indicates that an attempt to modify
|
||||
/// Certificates was made after PeerConnection has been initialized.
|
||||
#[error("certificates cannot be modified")]
|
||||
ErrModifyingCertificates,
|
||||
|
||||
/// ErrNonCertificate indicates that there is no certificate
|
||||
#[error("no certificate")]
|
||||
ErrNonCertificate,
|
||||
|
||||
/// ErrModifyingBundlePolicy indicates that an attempt to modify
|
||||
/// BundlePolicy was made after PeerConnection has been initialized.
|
||||
#[error("bundle policy cannot be modified")]
|
||||
ErrModifyingBundlePolicy,
|
||||
|
||||
/// ErrModifyingRTCPMuxPolicy indicates that an attempt to modify
|
||||
/// RTCPMuxPolicy was made after PeerConnection has been initialized.
|
||||
#[error("rtcp mux policy cannot be modified")]
|
||||
ErrModifyingRTCPMuxPolicy,
|
||||
|
||||
/// ErrModifyingICECandidatePoolSize indicates that an attempt to modify
|
||||
/// ICECandidatePoolSize was made after PeerConnection has been initialized.
|
||||
#[error("ice candidate pool size cannot be modified")]
|
||||
ErrModifyingICECandidatePoolSize,
|
||||
|
||||
/// ErrStringSizeLimit indicates that the character size limit of string is
|
||||
/// exceeded. The limit is hardcoded to 65535 according to specifications.
|
||||
#[error("data channel label exceeds size limit")]
|
||||
ErrStringSizeLimit,
|
||||
|
||||
/// ErrMaxDataChannelID indicates that the maximum number ID that could be
|
||||
/// specified for a data channel has been exceeded.
|
||||
#[error("maximum number ID for datachannel specified")]
|
||||
ErrMaxDataChannelID,
|
||||
|
||||
/// ErrNegotiatedWithoutID indicates that an attempt to create a data channel
|
||||
/// was made while setting the negotiated option to true without providing
|
||||
/// the negotiated channel ID.
|
||||
#[error("negotiated set without channel id")]
|
||||
ErrNegotiatedWithoutID,
|
||||
|
||||
/// ErrRetransmitsOrPacketLifeTime indicates that an attempt to create a data
|
||||
/// channel was made with both options max_packet_life_time and max_retransmits
|
||||
/// set together. Such configuration is not supported by the specification
|
||||
/// and is mutually exclusive.
|
||||
#[error("both max_packet_life_time and max_retransmits was set")]
|
||||
ErrRetransmitsOrPacketLifeTime,
|
||||
|
||||
/// ErrCodecNotFound is returned when a codec search to the Media Engine fails
|
||||
#[error("codec not found")]
|
||||
ErrCodecNotFound,
|
||||
|
||||
/// ErrNoRemoteDescription indicates that an operation was rejected because
|
||||
/// the remote description is not set
|
||||
#[error("remote description is not set")]
|
||||
ErrNoRemoteDescription,
|
||||
|
||||
/// ErrIncorrectSDPSemantics indicates that the PeerConnection was configured to
|
||||
/// generate SDP Answers with different SDP Semantics than the received Offer
|
||||
#[error("offer SDP semantics does not match configuration")]
|
||||
ErrIncorrectSDPSemantics,
|
||||
|
||||
/// ErrIncorrectSignalingState indicates that the signaling state of PeerConnection is not correct
|
||||
#[error("operation can not be run in current signaling state")]
|
||||
ErrIncorrectSignalingState,
|
||||
|
||||
/// ErrProtocolTooLarge indicates that value given for a DataChannelInit protocol is
|
||||
/// longer then 65535 bytes
|
||||
#[error("protocol is larger then 65535 bytes")]
|
||||
ErrProtocolTooLarge,
|
||||
|
||||
/// ErrSenderNotCreatedByConnection indicates remove_track was called with a RtpSender not created
|
||||
/// by this PeerConnection
|
||||
#[error("RtpSender not created by this PeerConnection")]
|
||||
ErrSenderNotCreatedByConnection,
|
||||
|
||||
/// ErrSenderInitialTrackIdAlreadySet indicates a second call to
|
||||
/// [`RtpSender::set_initial_track_id`] which is not allowed.
|
||||
#[error("RtpSender's initial_track_id has already been set")]
|
||||
ErrSenderInitialTrackIdAlreadySet,
|
||||
|
||||
/// ErrSessionDescriptionNoFingerprint indicates set_remote_description was called with a SessionDescription that has no
|
||||
/// fingerprint
|
||||
#[error("set_remote_description called with no fingerprint")]
|
||||
ErrSessionDescriptionNoFingerprint,
|
||||
|
||||
/// ErrSessionDescriptionInvalidFingerprint indicates set_remote_description was called with a SessionDescription that
|
||||
/// has an invalid fingerprint
|
||||
#[error("set_remote_description called with an invalid fingerprint")]
|
||||
ErrSessionDescriptionInvalidFingerprint,
|
||||
|
||||
/// ErrSessionDescriptionConflictingFingerprints indicates set_remote_description was called with a SessionDescription that
|
||||
/// has an conflicting fingerprints
|
||||
#[error("set_remote_description called with multiple conflicting fingerprint")]
|
||||
ErrSessionDescriptionConflictingFingerprints,
|
||||
|
||||
/// ErrSessionDescriptionMissingIceUfrag indicates set_remote_description was called with a SessionDescription that
|
||||
/// is missing an ice-ufrag value
|
||||
#[error("set_remote_description called with no ice-ufrag")]
|
||||
ErrSessionDescriptionMissingIceUfrag,
|
||||
|
||||
/// ErrSessionDescriptionMissingIcePwd indicates set_remote_description was called with a SessionDescription that
|
||||
/// is missing an ice-pwd value
|
||||
#[error("set_remote_description called with no ice-pwd")]
|
||||
ErrSessionDescriptionMissingIcePwd,
|
||||
|
||||
/// ErrSessionDescriptionConflictingIceUfrag indicates set_remote_description was called with a SessionDescription that
|
||||
/// contains multiple conflicting ice-ufrag values
|
||||
#[error("set_remote_description called with multiple conflicting ice-ufrag values")]
|
||||
ErrSessionDescriptionConflictingIceUfrag,
|
||||
|
||||
/// ErrSessionDescriptionConflictingIcePwd indicates set_remote_description was called with a SessionDescription that
|
||||
/// contains multiple conflicting ice-pwd values
|
||||
#[error("set_remote_description called with multiple conflicting ice-pwd values")]
|
||||
ErrSessionDescriptionConflictingIcePwd,
|
||||
|
||||
/// ErrNoSRTPProtectionProfile indicates that the DTLS handshake completed and no SRTP Protection Profile was chosen
|
||||
#[error("DTLS Handshake completed and no SRTP Protection Profile was chosen")]
|
||||
ErrNoSRTPProtectionProfile,
|
||||
|
||||
/// ErrFailedToGenerateCertificateFingerprint indicates that we failed to generate the fingerprint used for comparing certificates
|
||||
#[error("failed to generate certificate fingerprint")]
|
||||
ErrFailedToGenerateCertificateFingerprint,
|
||||
|
||||
/// ErrNoCodecsAvailable indicates that operation isn't possible because the MediaEngine has no codecs available
|
||||
#[error("operation failed no codecs are available")]
|
||||
ErrNoCodecsAvailable,
|
||||
|
||||
/// ErrUnsupportedCodec indicates the remote peer doesn't support the requested codec
|
||||
#[error("unable to start track, codec is not supported by remote")]
|
||||
ErrUnsupportedCodec,
|
||||
|
||||
/// ErrSenderWithNoCodecs indicates that a RTPSender was created without any codecs. To send media the MediaEngine needs at
|
||||
/// least one configured codec.
|
||||
#[error("unable to populate media section, RTPSender created with no codecs")]
|
||||
ErrSenderWithNoCodecs,
|
||||
|
||||
/// ErrRTPSenderNewTrackHasIncorrectKind indicates that the new track is of a different kind than the previous/original
|
||||
#[error("new track must be of the same kind as previous")]
|
||||
ErrRTPSenderNewTrackHasIncorrectKind,
|
||||
|
||||
/// ErrRTPSenderDataSent indicates that the sequence number transformer tries to be enabled after the data sending began
|
||||
#[error("Sequence number transformer must be enabled before sending data")]
|
||||
ErrRTPSenderDataSent,
|
||||
|
||||
/// ErrRTPSenderSeqTransEnabled indicates that the sequence number transformer has been already enabled
|
||||
#[error("Sequence number transformer has been already enabled")]
|
||||
ErrRTPSenderSeqTransEnabled,
|
||||
|
||||
/// ErrUnbindFailed indicates that a TrackLocal was not able to be unbind
|
||||
#[error("failed to unbind TrackLocal from PeerConnection")]
|
||||
ErrUnbindFailed,
|
||||
|
||||
/// ErrNoPayloaderForCodec indicates that the requested codec does not have a payloader
|
||||
#[error("the requested codec does not have a payloader")]
|
||||
ErrNoPayloaderForCodec,
|
||||
|
||||
/// ErrRegisterHeaderExtensionInvalidDirection indicates that a extension was registered with different
|
||||
/// directions for two different calls.
|
||||
#[error("a header extension must be registered with the same direction each time")]
|
||||
ErrRegisterHeaderExtensionInvalidDirection,
|
||||
|
||||
/// ErrRegisterHeaderExtensionNoFreeID indicates that there was no extension ID available which
|
||||
/// in turn means that all 15 available id(1 through 14) have been used.
|
||||
#[error("no header extension ID was free to use(this means the maximum of 15 extensions have been registered)")]
|
||||
ErrRegisterHeaderExtensionNoFreeID,
|
||||
|
||||
/// ErrSimulcastProbeOverflow indicates that too many Simulcast probe streams are in flight and the requested SSRC was ignored
|
||||
#[error("simulcast probe limit has been reached, new SSRC has been discarded")]
|
||||
ErrSimulcastProbeOverflow,
|
||||
|
||||
#[error("enable detaching by calling webrtc.DetachDataChannels()")]
|
||||
ErrDetachNotEnabled,
|
||||
#[error("datachannel not opened yet, try calling Detach from OnOpen")]
|
||||
ErrDetachBeforeOpened,
|
||||
#[error("the DTLS transport has not started yet")]
|
||||
ErrDtlsTransportNotStarted,
|
||||
#[error("failed extracting keys from DTLS for SRTP")]
|
||||
ErrDtlsKeyExtractionFailed,
|
||||
#[error("failed to start SRTP")]
|
||||
ErrFailedToStartSRTP,
|
||||
#[error("failed to start SRTCP")]
|
||||
ErrFailedToStartSRTCP,
|
||||
#[error("attempted to start DTLSTransport that is not in new state")]
|
||||
ErrInvalidDTLSStart,
|
||||
#[error("peer didn't provide certificate via DTLS")]
|
||||
ErrNoRemoteCertificate,
|
||||
#[error("identity provider is not implemented")]
|
||||
ErrIdentityProviderNotImplemented,
|
||||
#[error("remote certificate does not match any fingerprint")]
|
||||
ErrNoMatchingCertificateFingerprint,
|
||||
#[error("unsupported fingerprint algorithm")]
|
||||
ErrUnsupportedFingerprintAlgorithm,
|
||||
#[error("ICE connection not started")]
|
||||
ErrICEConnectionNotStarted,
|
||||
#[error("unknown candidate type")]
|
||||
ErrICECandidateTypeUnknown,
|
||||
#[error("cannot convert ice.CandidateType into webrtc.ICECandidateType, invalid type")]
|
||||
ErrICEInvalidConvertCandidateType,
|
||||
#[error("ICEAgent does not exist")]
|
||||
ErrICEAgentNotExist,
|
||||
#[error("unable to convert ICE candidates to ICECandidates")]
|
||||
ErrICECandidatesConversionFailed,
|
||||
#[error("unknown ICE Role")]
|
||||
ErrICERoleUnknown,
|
||||
#[error("unknown protocol")]
|
||||
ErrICEProtocolUnknown,
|
||||
#[error("gatherer not started")]
|
||||
ErrICEGathererNotStarted,
|
||||
#[error("unknown network type")]
|
||||
ErrNetworkTypeUnknown,
|
||||
#[error("new sdp does not match previous offer")]
|
||||
ErrSDPDoesNotMatchOffer,
|
||||
#[error("new sdp does not match previous answer")]
|
||||
ErrSDPDoesNotMatchAnswer,
|
||||
#[error("provided value is not a valid enum value of type SDPType")]
|
||||
ErrPeerConnSDPTypeInvalidValue,
|
||||
#[error("invalid state change op")]
|
||||
ErrPeerConnStateChangeInvalid,
|
||||
#[error("unhandled state change op")]
|
||||
ErrPeerConnStateChangeUnhandled,
|
||||
#[error("invalid SDP type supplied to SetLocalDescription()")]
|
||||
ErrPeerConnSDPTypeInvalidValueSetLocalDescription,
|
||||
#[error("remoteDescription contained media section without mid value")]
|
||||
ErrPeerConnRemoteDescriptionWithoutMidValue,
|
||||
#[error("remoteDescription has not been set yet")]
|
||||
ErrPeerConnRemoteDescriptionNil,
|
||||
#[error("single media section has an explicit SSRC")]
|
||||
ErrPeerConnSingleMediaSectionHasExplicitSSRC,
|
||||
#[error("could not add transceiver for remote SSRC")]
|
||||
ErrPeerConnRemoteSSRCAddTransceiver,
|
||||
#[error("mid RTP Extensions required for Simulcast")]
|
||||
ErrPeerConnSimulcastMidRTPExtensionRequired,
|
||||
#[error("stream id RTP Extensions required for Simulcast")]
|
||||
ErrPeerConnSimulcastStreamIDRTPExtensionRequired,
|
||||
#[error("incoming SSRC failed Simulcast probing")]
|
||||
ErrPeerConnSimulcastIncomingSSRCFailed,
|
||||
#[error("failed collecting stats")]
|
||||
ErrPeerConnStatsCollectionFailed,
|
||||
#[error("add_transceiver_from_kind only accepts one RTPTransceiverInit")]
|
||||
ErrPeerConnAddTransceiverFromKindOnlyAcceptsOne,
|
||||
#[error("add_transceiver_from_track only accepts one RTPTransceiverInit")]
|
||||
ErrPeerConnAddTransceiverFromTrackOnlyAcceptsOne,
|
||||
#[error("add_transceiver_from_kind currently only supports recvonly")]
|
||||
ErrPeerConnAddTransceiverFromKindSupport,
|
||||
#[error("add_transceiver_from_track currently only supports sendonly and sendrecv")]
|
||||
ErrPeerConnAddTransceiverFromTrackSupport,
|
||||
#[error("TODO set_identity_provider")]
|
||||
ErrPeerConnSetIdentityProviderNotImplemented,
|
||||
#[error("write_rtcp failed to open write_stream")]
|
||||
ErrPeerConnWriteRTCPOpenWriteStream,
|
||||
#[error("cannot find transceiver with mid")]
|
||||
ErrPeerConnTransceiverMidNil,
|
||||
#[error("DTLSTransport must not be nil")]
|
||||
ErrRTPReceiverDTLSTransportNil,
|
||||
#[error("Receive has already been called")]
|
||||
ErrRTPReceiverReceiveAlreadyCalled,
|
||||
#[error("unable to find stream for Track with SSRC")]
|
||||
ErrRTPReceiverWithSSRCTrackStreamNotFound,
|
||||
#[error("no trackStreams found for SSRC")]
|
||||
ErrRTPReceiverForSSRCTrackStreamNotFound,
|
||||
#[error("no trackStreams found for RID")]
|
||||
ErrRTPReceiverForRIDTrackStreamNotFound,
|
||||
#[error("invalid RTP Receiver transition from {from} to {to}")]
|
||||
ErrRTPReceiverStateChangeInvalid {
|
||||
from: rtp_receiver::State,
|
||||
to: rtp_receiver::State,
|
||||
},
|
||||
#[error("Track must not be nil")]
|
||||
ErrRTPSenderTrackNil,
|
||||
#[error("RTPSender must not be nil")]
|
||||
ErrRTPSenderNil,
|
||||
#[error("RTPReceiver must not be nil")]
|
||||
ErrRTPReceiverNil,
|
||||
#[error("DTLSTransport must not be nil")]
|
||||
ErrRTPSenderDTLSTransportNil,
|
||||
#[error("Send has already been called")]
|
||||
ErrRTPSenderSendAlreadyCalled,
|
||||
#[error("errRTPSenderTrackNil")]
|
||||
ErrRTPTransceiverCannotChangeMid,
|
||||
#[error("invalid state change in RTPTransceiver.setSending")]
|
||||
ErrRTPTransceiverSetSendingInvalidState,
|
||||
#[error("unsupported codec type by this transceiver")]
|
||||
ErrRTPTransceiverCodecUnsupported,
|
||||
#[error("DTLS not established")]
|
||||
ErrSCTPTransportDTLS,
|
||||
#[error("add_transceiver_sdp() called with 0 transceivers")]
|
||||
ErrSDPZeroTransceivers,
|
||||
#[error("invalid Media Section. Media + DataChannel both enabled")]
|
||||
ErrSDPMediaSectionMediaDataChanInvalid,
|
||||
#[error(
|
||||
"invalid Media Section. Can not have multiple tracks in one MediaSection in UnifiedPlan"
|
||||
)]
|
||||
ErrSDPMediaSectionMultipleTrackInvalid,
|
||||
#[error("set_answering_dtlsrole must DTLSRoleClient or DTLSRoleServer")]
|
||||
ErrSettingEngineSetAnsweringDTLSRole,
|
||||
#[error("can't rollback from stable state")]
|
||||
ErrSignalingStateCannotRollback,
|
||||
#[error(
|
||||
"invalid proposed signaling state transition from {} applying {} {}",
|
||||
from,
|
||||
if *is_local { "local" } else { "remote" },
|
||||
applying
|
||||
)]
|
||||
ErrSignalingStateProposedTransitionInvalid {
|
||||
from: RTCSignalingState,
|
||||
applying: RTCSdpType,
|
||||
is_local: bool,
|
||||
},
|
||||
#[error("cannot convert to StatsICECandidatePairStateSucceeded invalid ice candidate state")]
|
||||
ErrStatsICECandidateStateInvalid,
|
||||
#[error("ICETransport can only be called in ICETransportStateNew")]
|
||||
ErrICETransportNotInNew,
|
||||
#[error("bad Certificate PEM format")]
|
||||
ErrCertificatePEMFormatError,
|
||||
#[error("SCTP is not established")]
|
||||
ErrSCTPNotEstablished,
|
||||
|
||||
#[error("DataChannel is not opened")]
|
||||
ErrClosedPipe,
|
||||
#[error("Interceptor is not bind")]
|
||||
ErrInterceptorNotBind,
|
||||
#[error("excessive retries in CreateOffer")]
|
||||
ErrExcessiveRetries,
|
||||
|
||||
#[error("not long enough to be a RTP Packet")]
|
||||
ErrRTPTooShort,
|
||||
|
||||
#[error("{0}")]
|
||||
Util(#[from] util::Error),
|
||||
#[error("{0}")]
|
||||
Ice(#[from] ice::Error),
|
||||
#[error("{0}")]
|
||||
Srtp(#[from] srtp::Error),
|
||||
#[error("{0}")]
|
||||
Dtls(#[from] dtls::Error),
|
||||
#[error("{0}")]
|
||||
Data(#[from] data::Error),
|
||||
#[error("{0}")]
|
||||
Sctp(#[from] sctp::Error),
|
||||
#[error("{0}")]
|
||||
Sdp(#[from] sdp::Error),
|
||||
#[error("{0}")]
|
||||
Interceptor(#[from] interceptor::Error),
|
||||
#[error("{0}")]
|
||||
Rtcp(#[from] rtcp::Error),
|
||||
#[error("{0}")]
|
||||
Rtp(#[from] rtp::Error),
|
||||
|
||||
#[error("utf-8 error: {0}")]
|
||||
Utf8(#[from] FromUtf8Error),
|
||||
#[error("{0}")]
|
||||
RcGen(#[from] RcgenError),
|
||||
#[error("mpsc send: {0}")]
|
||||
MpscSend(String),
|
||||
#[error("parse int: {0}")]
|
||||
ParseInt(#[from] ParseIntError),
|
||||
#[error("parse url: {0}")]
|
||||
ParseUrl(#[from] url::ParseError),
|
||||
|
||||
/// Error parsing a given PEM string.
|
||||
#[error("invalid PEM: {0}")]
|
||||
InvalidPEM(String),
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
#[error("{0}")]
|
||||
new(String),
|
||||
}
|
||||
|
||||
pub type OnErrorHdlrFn =
|
||||
Box<dyn (FnMut(Error) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>) + Send + Sync>;
|
||||
|
||||
// Because Tokio SendError is parameterized, we sadly lose the backtrace.
|
||||
impl<T> From<MpscSendError<T>> for Error {
|
||||
fn from(e: MpscSendError<T>) -> Self {
|
||||
Error::MpscSend(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Error> for interceptor::Error {
|
||||
fn from(e: Error) -> Self {
|
||||
// this is a bit lol, but we do preserve the stack trace
|
||||
interceptor::Error::Util(util::Error::from_std(e))
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq<ice::Error> for Error {
|
||||
fn eq(&self, other: &ice::Error) -> bool {
|
||||
if let Error::Ice(e) = self {
|
||||
return e == other;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// flatten_errs flattens multiple errors into one
|
||||
pub fn flatten_errs(errs: Vec<impl Into<Error>>) -> Result<()> {
|
||||
if errs.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
let errs_strs: Vec<String> = errs.into_iter().map(|e| e.into().to_string()).collect();
|
||||
Err(Error::new(errs_strs.join("\n")))
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use ice::candidate::candidate_base::CandidateBaseConfig;
|
||||
use ice::candidate::candidate_host::CandidateHostConfig;
|
||||
use ice::candidate::candidate_peer_reflexive::CandidatePeerReflexiveConfig;
|
||||
use ice::candidate::candidate_relay::CandidateRelayConfig;
|
||||
use ice::candidate::candidate_server_reflexive::CandidateServerReflexiveConfig;
|
||||
use ice::candidate::Candidate;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ice_transport::ice_candidate_type::RTCIceCandidateType;
|
||||
use crate::ice_transport::ice_protocol::RTCIceProtocol;
|
||||
|
||||
/// ICECandidate represents a ice candidate
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RTCIceCandidate {
|
||||
pub stats_id: String,
|
||||
pub foundation: String,
|
||||
pub priority: u32,
|
||||
pub address: String,
|
||||
pub protocol: RTCIceProtocol,
|
||||
pub port: u16,
|
||||
pub typ: RTCIceCandidateType,
|
||||
pub component: u16,
|
||||
pub related_address: String,
|
||||
pub related_port: u16,
|
||||
pub tcp_type: String,
|
||||
}
|
||||
|
||||
/// Conversion for ice_candidates
|
||||
pub(crate) fn rtc_ice_candidates_from_ice_candidates(
|
||||
ice_candidates: &[Arc<dyn Candidate + Send + Sync>],
|
||||
) -> Vec<RTCIceCandidate> {
|
||||
ice_candidates.iter().map(|c| c.into()).collect()
|
||||
}
|
||||
|
||||
impl From<&Arc<dyn Candidate + Send + Sync>> for RTCIceCandidate {
|
||||
fn from(c: &Arc<dyn Candidate + Send + Sync>) -> Self {
|
||||
let typ: RTCIceCandidateType = c.candidate_type().into();
|
||||
let protocol = RTCIceProtocol::from(c.network_type().network_short().as_str());
|
||||
let (related_address, related_port) = if let Some(ra) = c.related_address() {
|
||||
(ra.address, ra.port)
|
||||
} else {
|
||||
(String::new(), 0)
|
||||
};
|
||||
|
||||
RTCIceCandidate {
|
||||
stats_id: c.id(),
|
||||
foundation: c.foundation(),
|
||||
priority: c.priority(),
|
||||
address: c.address(),
|
||||
protocol,
|
||||
port: c.port(),
|
||||
component: c.component(),
|
||||
typ,
|
||||
tcp_type: c.tcp_type().to_string(),
|
||||
related_address,
|
||||
related_port,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCIceCandidate {
|
||||
pub(crate) fn to_ice(&self) -> Result<impl Candidate> {
|
||||
let candidate_id = self.stats_id.clone();
|
||||
let c = match self.typ {
|
||||
RTCIceCandidateType::Host => {
|
||||
let config = CandidateHostConfig {
|
||||
base_config: CandidateBaseConfig {
|
||||
candidate_id,
|
||||
network: self.protocol.to_string(),
|
||||
address: self.address.clone(),
|
||||
port: self.port,
|
||||
component: self.component,
|
||||
//tcp_type: ice.NewTCPType(c.TCPType),
|
||||
foundation: self.foundation.clone(),
|
||||
priority: self.priority,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
config.new_candidate_host()?
|
||||
}
|
||||
RTCIceCandidateType::Srflx => {
|
||||
let config = CandidateServerReflexiveConfig {
|
||||
base_config: CandidateBaseConfig {
|
||||
candidate_id,
|
||||
network: self.protocol.to_string(),
|
||||
address: self.address.clone(),
|
||||
port: self.port,
|
||||
component: self.component,
|
||||
foundation: self.foundation.clone(),
|
||||
priority: self.priority,
|
||||
..Default::default()
|
||||
},
|
||||
rel_addr: self.related_address.clone(),
|
||||
rel_port: self.related_port,
|
||||
};
|
||||
config.new_candidate_server_reflexive()?
|
||||
}
|
||||
RTCIceCandidateType::Prflx => {
|
||||
let config = CandidatePeerReflexiveConfig {
|
||||
base_config: CandidateBaseConfig {
|
||||
candidate_id,
|
||||
network: self.protocol.to_string(),
|
||||
address: self.address.clone(),
|
||||
port: self.port,
|
||||
component: self.component,
|
||||
foundation: self.foundation.clone(),
|
||||
priority: self.priority,
|
||||
..Default::default()
|
||||
},
|
||||
rel_addr: self.related_address.clone(),
|
||||
rel_port: self.related_port,
|
||||
};
|
||||
config.new_candidate_peer_reflexive()?
|
||||
}
|
||||
RTCIceCandidateType::Relay => {
|
||||
let config = CandidateRelayConfig {
|
||||
base_config: CandidateBaseConfig {
|
||||
candidate_id,
|
||||
network: self.protocol.to_string(),
|
||||
address: self.address.clone(),
|
||||
port: self.port,
|
||||
component: self.component,
|
||||
foundation: self.foundation.clone(),
|
||||
priority: self.priority,
|
||||
..Default::default()
|
||||
},
|
||||
rel_addr: self.related_address.clone(),
|
||||
rel_port: self.related_port,
|
||||
relay_client: None, //TODO?
|
||||
};
|
||||
config.new_candidate_relay()?
|
||||
}
|
||||
_ => return Err(Error::ErrICECandidateTypeUnknown),
|
||||
};
|
||||
|
||||
Ok(c)
|
||||
}
|
||||
|
||||
/// to_json returns an ICECandidateInit
|
||||
/// as indicated by the spec <https://w3c.github.io/webrtc-pc/#dom-rtcicecandidate-tojson>
|
||||
pub fn to_json(&self) -> Result<RTCIceCandidateInit> {
|
||||
let candidate = self.to_ice()?;
|
||||
|
||||
Ok(RTCIceCandidateInit {
|
||||
candidate: format!("candidate:{}", candidate.marshal()),
|
||||
sdp_mid: Some("".to_owned()),
|
||||
sdp_mline_index: Some(0u16),
|
||||
username_fragment: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceCandidate {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(
|
||||
f,
|
||||
"{} {} {}:{}{}",
|
||||
self.protocol, self.typ, self.address, self.port, self.related_address,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// ICECandidateInit is used to serialize ice candidates
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RTCIceCandidateInit {
|
||||
pub candidate: String,
|
||||
pub sdp_mid: Option<String>,
|
||||
#[serde(rename = "sdpMLineIndex")]
|
||||
pub sdp_mline_index: Option<u16>,
|
||||
pub username_fragment: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_ice_candidate_serialization() {
|
||||
let tests = vec![
|
||||
(
|
||||
RTCIceCandidateInit {
|
||||
candidate: "candidate:abc123".to_string(),
|
||||
sdp_mid: Some("0".to_string()),
|
||||
sdp_mline_index: Some(0),
|
||||
username_fragment: Some("def".to_string()),
|
||||
},
|
||||
r#"{"candidate":"candidate:abc123","sdpMid":"0","sdpMLineIndex":0,"usernameFragment":"def"}"#,
|
||||
),
|
||||
(
|
||||
RTCIceCandidateInit {
|
||||
candidate: "candidate:abc123".to_string(),
|
||||
sdp_mid: None,
|
||||
sdp_mline_index: None,
|
||||
username_fragment: None,
|
||||
},
|
||||
r#"{"candidate":"candidate:abc123","sdpMid":null,"sdpMLineIndex":null,"usernameFragment":null}"#,
|
||||
),
|
||||
];
|
||||
|
||||
for (candidate_init, expected_string) in tests {
|
||||
let result = serde_json::to_string(&candidate_init);
|
||||
assert!(result.is_ok(), "testCase: marshal err: {result:?}");
|
||||
let candidate_data = result.unwrap();
|
||||
assert_eq!(candidate_data, expected_string, "string is not expected");
|
||||
|
||||
let result = serde_json::from_str::<RTCIceCandidateInit>(&candidate_data);
|
||||
assert!(result.is_ok(), "testCase: unmarshal err: {result:?}");
|
||||
if let Ok(actual_candidate_init) = result {
|
||||
assert_eq!(actual_candidate_init, candidate_init);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
use std::fmt;
|
||||
|
||||
use crate::ice_transport::ice_candidate::*;
|
||||
|
||||
/// ICECandidatePair represents an ICE Candidate pair
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RTCIceCandidatePair {
|
||||
stats_id: String,
|
||||
local: RTCIceCandidate,
|
||||
remote: RTCIceCandidate,
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceCandidatePair {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
write!(f, "(local) {} <-> (remote) {}", self.local, self.remote)
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCIceCandidatePair {
|
||||
fn stats_id(local_id: &str, remote_id: &str) -> String {
|
||||
format!("{local_id}-{remote_id}")
|
||||
}
|
||||
|
||||
/// returns an initialized ICECandidatePair
|
||||
/// for the given pair of ICECandidate instances
|
||||
pub fn new(local: RTCIceCandidate, remote: RTCIceCandidate) -> Self {
|
||||
let stats_id = Self::stats_id(&local.stats_id, &remote.stats_id);
|
||||
RTCIceCandidatePair {
|
||||
stats_id,
|
||||
local,
|
||||
remote,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
use std::fmt;
|
||||
|
||||
use ice::candidate::CandidateType;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ICECandidateType represents the type of the ICE candidate used.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RTCIceCandidateType {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICECandidateTypeHost indicates that the candidate is of Host type as
|
||||
/// described in <https://tools.ietf.org/html/rfc8445#section-5.1.1.1>. A
|
||||
/// candidate obtained by binding to a specific port from an IP address on
|
||||
/// the host. This includes IP addresses on physical interfaces and logical
|
||||
/// ones, such as ones obtained through VPNs.
|
||||
#[serde(rename = "host")]
|
||||
Host,
|
||||
|
||||
/// ICECandidateTypeSrflx indicates the the candidate is of Server
|
||||
/// Reflexive type as described
|
||||
/// <https://tools.ietf.org/html/rfc8445#section-5.1.1.2>. A candidate type
|
||||
/// whose IP address and port are a binding allocated by a NAT for an ICE
|
||||
/// agent after it sends a packet through the NAT to a server, such as a
|
||||
/// STUN server.
|
||||
#[serde(rename = "srflx")]
|
||||
Srflx,
|
||||
|
||||
/// ICECandidateTypePrflx indicates that the candidate is of Peer
|
||||
/// Reflexive type. A candidate type whose IP address and port are a binding
|
||||
/// allocated by a NAT for an ICE agent after it sends a packet through the
|
||||
/// NAT to its peer.
|
||||
#[serde(rename = "prflx")]
|
||||
Prflx,
|
||||
|
||||
/// ICECandidateTypeRelay indicates the the candidate is of Relay type as
|
||||
/// described in <https://tools.ietf.org/html/rfc8445#section-5.1.1.2>. A
|
||||
/// candidate type obtained from a relay server, such as a TURN server.
|
||||
#[serde(rename = "relay")]
|
||||
Relay,
|
||||
}
|
||||
|
||||
const ICE_CANDIDATE_TYPE_HOST_STR: &str = "host";
|
||||
const ICE_CANDIDATE_TYPE_SRFLX_STR: &str = "srflx";
|
||||
const ICE_CANDIDATE_TYPE_PRFLX_STR: &str = "prflx";
|
||||
const ICE_CANDIDATE_TYPE_RELAY_STR: &str = "relay";
|
||||
|
||||
/// takes a string and converts it into ICECandidateType
|
||||
impl From<&str> for RTCIceCandidateType {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_CANDIDATE_TYPE_HOST_STR => RTCIceCandidateType::Host,
|
||||
ICE_CANDIDATE_TYPE_SRFLX_STR => RTCIceCandidateType::Srflx,
|
||||
ICE_CANDIDATE_TYPE_PRFLX_STR => RTCIceCandidateType::Prflx,
|
||||
ICE_CANDIDATE_TYPE_RELAY_STR => RTCIceCandidateType::Relay,
|
||||
_ => RTCIceCandidateType::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CandidateType> for RTCIceCandidateType {
|
||||
fn from(candidate_type: CandidateType) -> Self {
|
||||
match candidate_type {
|
||||
CandidateType::Host => RTCIceCandidateType::Host,
|
||||
CandidateType::ServerReflexive => RTCIceCandidateType::Srflx,
|
||||
CandidateType::PeerReflexive => RTCIceCandidateType::Prflx,
|
||||
CandidateType::Relay => RTCIceCandidateType::Relay,
|
||||
_ => RTCIceCandidateType::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceCandidateType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceCandidateType::Host => write!(f, "{ICE_CANDIDATE_TYPE_HOST_STR}"),
|
||||
RTCIceCandidateType::Srflx => write!(f, "{ICE_CANDIDATE_TYPE_SRFLX_STR}"),
|
||||
RTCIceCandidateType::Prflx => write!(f, "{ICE_CANDIDATE_TYPE_PRFLX_STR}"),
|
||||
RTCIceCandidateType::Relay => write!(f, "{ICE_CANDIDATE_TYPE_RELAY_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_ice_candidate_type() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCIceCandidateType::Unspecified),
|
||||
("host", RTCIceCandidateType::Host),
|
||||
("srflx", RTCIceCandidateType::Srflx),
|
||||
("prflx", RTCIceCandidateType::Prflx),
|
||||
("relay", RTCIceCandidateType::Relay),
|
||||
];
|
||||
|
||||
for (type_string, expected_type) in tests {
|
||||
let actual = RTCIceCandidateType::from(type_string);
|
||||
assert_eq!(actual, expected_type);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_candidate_type_string() {
|
||||
let tests = vec![
|
||||
(RTCIceCandidateType::Unspecified, "Unspecified"),
|
||||
(RTCIceCandidateType::Host, "host"),
|
||||
(RTCIceCandidateType::Srflx, "srflx"),
|
||||
(RTCIceCandidateType::Prflx, "prflx"),
|
||||
(RTCIceCandidateType::Relay, "relay"),
|
||||
];
|
||||
|
||||
for (ctype, expected_string) in tests {
|
||||
assert_eq!(ctype.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
use std::fmt;
|
||||
|
||||
/// RTCIceConnectionState indicates signaling state of the ICE Connection.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCIceConnectionState {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICEConnectionStateNew indicates that any of the ICETransports are
|
||||
/// in the "new" state and none of them are in the "checking", "disconnected"
|
||||
/// or "failed" state, or all ICETransports are in the "closed" state, or
|
||||
/// there are no transports.
|
||||
New,
|
||||
|
||||
/// ICEConnectionStateChecking indicates that any of the ICETransports
|
||||
/// are in the "checking" state and none of them are in the "disconnected"
|
||||
/// or "failed" state.
|
||||
Checking,
|
||||
|
||||
/// ICEConnectionStateConnected indicates that all ICETransports are
|
||||
/// in the "connected", "completed" or "closed" state and at least one of
|
||||
/// them is in the "connected" state.
|
||||
Connected,
|
||||
|
||||
/// ICEConnectionStateCompleted indicates that all ICETransports are
|
||||
/// in the "completed" or "closed" state and at least one of them is in the
|
||||
/// "completed" state.
|
||||
Completed,
|
||||
|
||||
/// ICEConnectionStateDisconnected indicates that any of the
|
||||
/// ICETransports are in the "disconnected" state and none of them are
|
||||
/// in the "failed" state.
|
||||
Disconnected,
|
||||
|
||||
/// ICEConnectionStateFailed indicates that any of the ICETransports
|
||||
/// are in the "failed" state.
|
||||
Failed,
|
||||
|
||||
/// ICEConnectionStateClosed indicates that the PeerConnection's
|
||||
/// isClosed is true.
|
||||
Closed,
|
||||
}
|
||||
|
||||
const ICE_CONNECTION_STATE_NEW_STR: &str = "new";
|
||||
const ICE_CONNECTION_STATE_CHECKING_STR: &str = "checking";
|
||||
const ICE_CONNECTION_STATE_CONNECTED_STR: &str = "connected";
|
||||
const ICE_CONNECTION_STATE_COMPLETED_STR: &str = "completed";
|
||||
const ICE_CONNECTION_STATE_DISCONNECTED_STR: &str = "disconnected";
|
||||
const ICE_CONNECTION_STATE_FAILED_STR: &str = "failed";
|
||||
const ICE_CONNECTION_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
/// takes a string and converts it to iceconnection_state
|
||||
impl From<&str> for RTCIceConnectionState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_CONNECTION_STATE_NEW_STR => RTCIceConnectionState::New,
|
||||
ICE_CONNECTION_STATE_CHECKING_STR => RTCIceConnectionState::Checking,
|
||||
ICE_CONNECTION_STATE_CONNECTED_STR => RTCIceConnectionState::Connected,
|
||||
ICE_CONNECTION_STATE_COMPLETED_STR => RTCIceConnectionState::Completed,
|
||||
ICE_CONNECTION_STATE_DISCONNECTED_STR => RTCIceConnectionState::Disconnected,
|
||||
ICE_CONNECTION_STATE_FAILED_STR => RTCIceConnectionState::Failed,
|
||||
ICE_CONNECTION_STATE_CLOSED_STR => RTCIceConnectionState::Closed,
|
||||
_ => RTCIceConnectionState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCIceConnectionState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCIceConnectionState::New,
|
||||
2 => RTCIceConnectionState::Checking,
|
||||
3 => RTCIceConnectionState::Connected,
|
||||
4 => RTCIceConnectionState::Completed,
|
||||
5 => RTCIceConnectionState::Disconnected,
|
||||
6 => RTCIceConnectionState::Failed,
|
||||
7 => RTCIceConnectionState::Closed,
|
||||
_ => RTCIceConnectionState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceConnectionState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCIceConnectionState::New => ICE_CONNECTION_STATE_NEW_STR,
|
||||
RTCIceConnectionState::Checking => ICE_CONNECTION_STATE_CHECKING_STR,
|
||||
RTCIceConnectionState::Connected => ICE_CONNECTION_STATE_CONNECTED_STR,
|
||||
RTCIceConnectionState::Completed => ICE_CONNECTION_STATE_COMPLETED_STR,
|
||||
RTCIceConnectionState::Disconnected => ICE_CONNECTION_STATE_DISCONNECTED_STR,
|
||||
RTCIceConnectionState::Failed => ICE_CONNECTION_STATE_FAILED_STR,
|
||||
RTCIceConnectionState::Closed => ICE_CONNECTION_STATE_CLOSED_STR,
|
||||
RTCIceConnectionState::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_ice_connection_state() {
|
||||
let tests = vec![
|
||||
(crate::UNSPECIFIED_STR, RTCIceConnectionState::Unspecified),
|
||||
("new", RTCIceConnectionState::New),
|
||||
("checking", RTCIceConnectionState::Checking),
|
||||
("connected", RTCIceConnectionState::Connected),
|
||||
("completed", RTCIceConnectionState::Completed),
|
||||
("disconnected", RTCIceConnectionState::Disconnected),
|
||||
("failed", RTCIceConnectionState::Failed),
|
||||
("closed", RTCIceConnectionState::Closed),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(
|
||||
RTCIceConnectionState::from(state_string),
|
||||
expected_state,
|
||||
"testCase: {expected_state}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_connection_state_string() {
|
||||
let tests = vec![
|
||||
(RTCIceConnectionState::Unspecified, crate::UNSPECIFIED_STR),
|
||||
(RTCIceConnectionState::New, "new"),
|
||||
(RTCIceConnectionState::Checking, "checking"),
|
||||
(RTCIceConnectionState::Connected, "connected"),
|
||||
(RTCIceConnectionState::Completed, "completed"),
|
||||
(RTCIceConnectionState::Disconnected, "disconnected"),
|
||||
(RTCIceConnectionState::Failed, "failed"),
|
||||
(RTCIceConnectionState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ICECredentialType indicates the type of credentials used to connect to
|
||||
/// an ICE server.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)]
|
||||
pub enum RTCIceCredentialType {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICECredential::Password describes username and password based
|
||||
/// credentials as described in <https://tools.ietf.org/html/rfc5389>.
|
||||
Password,
|
||||
|
||||
/// ICECredential::Oauth describes token based credential as described
|
||||
/// in <https://tools.ietf.org/html/rfc7635>.
|
||||
/// Not supported in WebRTC 1.0 spec
|
||||
Oauth,
|
||||
}
|
||||
|
||||
const ICE_CREDENTIAL_TYPE_PASSWORD_STR: &str = "password";
|
||||
const ICE_CREDENTIAL_TYPE_OAUTH_STR: &str = "oauth";
|
||||
|
||||
impl From<&str> for RTCIceCredentialType {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_CREDENTIAL_TYPE_PASSWORD_STR => RTCIceCredentialType::Password,
|
||||
ICE_CREDENTIAL_TYPE_OAUTH_STR => RTCIceCredentialType::Oauth,
|
||||
_ => RTCIceCredentialType::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceCredentialType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceCredentialType::Password => write!(f, "{ICE_CREDENTIAL_TYPE_PASSWORD_STR}"),
|
||||
RTCIceCredentialType::Oauth => write!(f, "{ICE_CREDENTIAL_TYPE_OAUTH_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_ice_credential_type() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCIceCredentialType::Unspecified),
|
||||
("password", RTCIceCredentialType::Password),
|
||||
("oauth", RTCIceCredentialType::Oauth),
|
||||
];
|
||||
|
||||
for (ct_str, expected_ct) in tests {
|
||||
assert_eq!(RTCIceCredentialType::from(ct_str), expected_ct);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_credential_type_string() {
|
||||
let tests = vec![
|
||||
(RTCIceCredentialType::Unspecified, "Unspecified"),
|
||||
(RTCIceCredentialType::Password, "password"),
|
||||
(RTCIceCredentialType::Oauth, "oauth"),
|
||||
];
|
||||
|
||||
for (ct, expected_string) in tests {
|
||||
assert_eq!(ct.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
+409
@@ -0,0 +1,409 @@
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use ice::agent::Agent;
|
||||
use ice::candidate::{Candidate, CandidateType};
|
||||
use ice::url::Url;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::api::setting_engine::SettingEngine;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ice_transport::ice_candidate::*;
|
||||
use crate::ice_transport::ice_candidate_type::RTCIceCandidateType;
|
||||
use crate::ice_transport::ice_gatherer_state::RTCIceGathererState;
|
||||
use crate::ice_transport::ice_parameters::RTCIceParameters;
|
||||
use crate::ice_transport::ice_server::RTCIceServer;
|
||||
use crate::peer_connection::policy::ice_transport_policy::RTCIceTransportPolicy;
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
use crate::stats::SourceStatsType::*;
|
||||
use crate::stats::{ICECandidatePairStats, StatsReportType};
|
||||
|
||||
/// ICEGatherOptions provides options relating to the gathering of ICE candidates.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct RTCIceGatherOptions {
|
||||
pub ice_servers: Vec<RTCIceServer>,
|
||||
pub ice_gather_policy: RTCIceTransportPolicy,
|
||||
}
|
||||
|
||||
pub type OnLocalCandidateHdlrFn = Box<
|
||||
dyn (FnMut(Option<RTCIceCandidate>) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
pub type OnICEGathererStateChangeHdlrFn = Box<
|
||||
dyn (FnMut(RTCIceGathererState) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
pub type OnGatheringCompleteHdlrFn =
|
||||
Box<dyn (FnMut() -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>) + Send + Sync>;
|
||||
|
||||
/// ICEGatherer gathers local host, server reflexive and relay
|
||||
/// candidates, as well as enabling the retrieval of local Interactive
|
||||
/// Connectivity Establishment (ICE) parameters which can be
|
||||
/// exchanged in signaling.
|
||||
#[derive(Default)]
|
||||
pub struct RTCIceGatherer {
|
||||
pub(crate) validated_servers: Vec<Url>,
|
||||
pub(crate) gather_policy: RTCIceTransportPolicy,
|
||||
pub(crate) setting_engine: Arc<SettingEngine>,
|
||||
|
||||
pub(crate) state: Arc<AtomicU8>, //ICEGathererState,
|
||||
pub(crate) agent: Mutex<Option<Arc<ice::agent::Agent>>>,
|
||||
|
||||
pub(crate) on_local_candidate_handler: Arc<ArcSwapOption<Mutex<OnLocalCandidateHdlrFn>>>,
|
||||
pub(crate) on_state_change_handler: Arc<ArcSwapOption<Mutex<OnICEGathererStateChangeHdlrFn>>>,
|
||||
|
||||
// Used for gathering_complete_promise
|
||||
pub(crate) on_gathering_complete_handler: Arc<ArcSwapOption<Mutex<OnGatheringCompleteHdlrFn>>>,
|
||||
}
|
||||
|
||||
impl RTCIceGatherer {
|
||||
pub(crate) fn new(
|
||||
validated_servers: Vec<Url>,
|
||||
gather_policy: RTCIceTransportPolicy,
|
||||
setting_engine: Arc<SettingEngine>,
|
||||
) -> Self {
|
||||
RTCIceGatherer {
|
||||
gather_policy,
|
||||
validated_servers,
|
||||
setting_engine,
|
||||
state: Arc::new(AtomicU8::new(RTCIceGathererState::New as u8)),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn create_agent(&self) -> Result<()> {
|
||||
// NOTE: A lock is held for the duration of this function in order to
|
||||
// avoid potential double-agent creations. Care should be taken to
|
||||
// ensure we do not do anything expensive other than the actual agent
|
||||
// creation in this function.
|
||||
let mut agent = self.agent.lock().await;
|
||||
|
||||
if agent.is_some() || self.state() != RTCIceGathererState::New {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut candidate_types = vec![];
|
||||
if self.setting_engine.candidates.ice_lite {
|
||||
candidate_types.push(ice::candidate::CandidateType::Host);
|
||||
} else if self.gather_policy == RTCIceTransportPolicy::Relay {
|
||||
candidate_types.push(ice::candidate::CandidateType::Relay);
|
||||
}
|
||||
|
||||
let nat_1to1_cand_type = match self.setting_engine.candidates.nat_1to1_ip_candidate_type {
|
||||
RTCIceCandidateType::Host => CandidateType::Host,
|
||||
RTCIceCandidateType::Srflx => CandidateType::ServerReflexive,
|
||||
_ => CandidateType::Unspecified,
|
||||
};
|
||||
|
||||
let mdns_mode = self.setting_engine.candidates.multicast_dns_mode;
|
||||
|
||||
let mut config = ice::agent::agent_config::AgentConfig {
|
||||
udp_network: self.setting_engine.udp_network.clone(),
|
||||
lite: self.setting_engine.candidates.ice_lite,
|
||||
urls: self.validated_servers.clone(),
|
||||
disconnected_timeout: self.setting_engine.timeout.ice_disconnected_timeout,
|
||||
failed_timeout: self.setting_engine.timeout.ice_failed_timeout,
|
||||
keepalive_interval: self.setting_engine.timeout.ice_keepalive_interval,
|
||||
candidate_types,
|
||||
host_acceptance_min_wait: self.setting_engine.timeout.ice_host_acceptance_min_wait,
|
||||
srflx_acceptance_min_wait: self.setting_engine.timeout.ice_srflx_acceptance_min_wait,
|
||||
prflx_acceptance_min_wait: self.setting_engine.timeout.ice_prflx_acceptance_min_wait,
|
||||
relay_acceptance_min_wait: self.setting_engine.timeout.ice_relay_acceptance_min_wait,
|
||||
interface_filter: self.setting_engine.candidates.interface_filter.clone(),
|
||||
ip_filter: self.setting_engine.candidates.ip_filter.clone(),
|
||||
nat_1to1_ips: self.setting_engine.candidates.nat_1to1_ips.clone(),
|
||||
nat_1to1_ip_candidate_type: nat_1to1_cand_type,
|
||||
net: self.setting_engine.vnet.clone(),
|
||||
multicast_dns_mode: mdns_mode,
|
||||
multicast_dns_host_name: self
|
||||
.setting_engine
|
||||
.candidates
|
||||
.multicast_dns_host_name
|
||||
.clone(),
|
||||
local_ufrag: self.setting_engine.candidates.username_fragment.clone(),
|
||||
local_pwd: self.setting_engine.candidates.password.clone(),
|
||||
//TODO: TCPMux: self.setting_engine.iceTCPMux,
|
||||
//TODO: ProxyDialer: self.setting_engine.iceProxyDialer,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let requested_network_types = if self.setting_engine.candidates.ice_network_types.is_empty()
|
||||
{
|
||||
ice::network_type::supported_network_types()
|
||||
} else {
|
||||
self.setting_engine.candidates.ice_network_types.clone()
|
||||
};
|
||||
|
||||
config.network_types.extend(requested_network_types);
|
||||
|
||||
*agent = Some(Arc::new(ice::agent::Agent::new(config).await?));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Gather ICE candidates.
|
||||
pub async fn gather(&self) -> Result<()> {
|
||||
self.create_agent().await?;
|
||||
self.set_state(RTCIceGathererState::Gathering).await;
|
||||
|
||||
if let Some(agent) = self.get_agent().await {
|
||||
let state = Arc::clone(&self.state);
|
||||
let on_local_candidate_handler = Arc::clone(&self.on_local_candidate_handler);
|
||||
let on_state_change_handler = Arc::clone(&self.on_state_change_handler);
|
||||
let on_gathering_complete_handler = Arc::clone(&self.on_gathering_complete_handler);
|
||||
|
||||
agent.on_candidate(Box::new(
|
||||
move |candidate: Option<Arc<dyn Candidate + Send + Sync>>| {
|
||||
let state_clone = Arc::clone(&state);
|
||||
let on_local_candidate_handler_clone = Arc::clone(&on_local_candidate_handler);
|
||||
let on_state_change_handler_clone = Arc::clone(&on_state_change_handler);
|
||||
let on_gathering_complete_handler_clone =
|
||||
Arc::clone(&on_gathering_complete_handler);
|
||||
|
||||
Box::pin(async move {
|
||||
if let Some(cand) = candidate {
|
||||
if let Some(handler) = &*on_local_candidate_handler_clone.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(Some(RTCIceCandidate::from(&cand))).await;
|
||||
}
|
||||
} else {
|
||||
state_clone
|
||||
.store(RTCIceGathererState::Complete as u8, Ordering::SeqCst);
|
||||
|
||||
if let Some(handler) = &*on_state_change_handler_clone.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(RTCIceGathererState::Complete).await;
|
||||
}
|
||||
|
||||
if let Some(handler) = &*on_gathering_complete_handler_clone.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f().await;
|
||||
}
|
||||
|
||||
if let Some(handler) = &*on_local_candidate_handler_clone.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(None).await;
|
||||
}
|
||||
}
|
||||
})
|
||||
},
|
||||
));
|
||||
|
||||
agent.gather_candidates()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Close prunes all local candidates, and closes the ports.
|
||||
pub async fn close(&self) -> Result<()> {
|
||||
self.set_state(RTCIceGathererState::Closed).await;
|
||||
|
||||
let agent = {
|
||||
let mut agent_opt = self.agent.lock().await;
|
||||
agent_opt.take()
|
||||
};
|
||||
|
||||
if let Some(agent) = agent {
|
||||
agent.close().await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// get_local_parameters returns the ICE parameters of the ICEGatherer.
|
||||
pub async fn get_local_parameters(&self) -> Result<RTCIceParameters> {
|
||||
self.create_agent().await?;
|
||||
|
||||
let (frag, pwd) = if let Some(agent) = self.get_agent().await {
|
||||
agent.get_local_user_credentials().await
|
||||
} else {
|
||||
return Err(Error::ErrICEAgentNotExist);
|
||||
};
|
||||
|
||||
Ok(RTCIceParameters {
|
||||
username_fragment: frag,
|
||||
password: pwd,
|
||||
ice_lite: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// get_local_candidates returns the sequence of valid local candidates associated with the ICEGatherer.
|
||||
pub async fn get_local_candidates(&self) -> Result<Vec<RTCIceCandidate>> {
|
||||
self.create_agent().await?;
|
||||
|
||||
let ice_candidates = if let Some(agent) = self.get_agent().await {
|
||||
agent.get_local_candidates().await?
|
||||
} else {
|
||||
return Err(Error::ErrICEAgentNotExist);
|
||||
};
|
||||
|
||||
Ok(rtc_ice_candidates_from_ice_candidates(&ice_candidates))
|
||||
}
|
||||
|
||||
/// on_local_candidate sets an event handler which fires when a new local ICE candidate is available
|
||||
/// Take note that the handler is gonna be called with a nil pointer when gathering is finished.
|
||||
pub fn on_local_candidate(&self, f: OnLocalCandidateHdlrFn) {
|
||||
self.on_local_candidate_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// on_state_change sets an event handler which fires any time the ICEGatherer changes
|
||||
pub fn on_state_change(&self, f: OnICEGathererStateChangeHdlrFn) {
|
||||
self.on_state_change_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// on_gathering_complete sets an event handler which fires any time the ICEGatherer changes
|
||||
pub fn on_gathering_complete(&self, f: OnGatheringCompleteHdlrFn) {
|
||||
self.on_gathering_complete_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// State indicates the current state of the ICE gatherer.
|
||||
pub fn state(&self) -> RTCIceGathererState {
|
||||
self.state.load(Ordering::SeqCst).into()
|
||||
}
|
||||
|
||||
pub async fn set_state(&self, s: RTCIceGathererState) {
|
||||
self.state.store(s as u8, Ordering::SeqCst);
|
||||
|
||||
if let Some(handler) = &*self.on_state_change_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(s).await;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_agent(&self) -> Option<Arc<Agent>> {
|
||||
let agent = self.agent.lock().await;
|
||||
agent.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(&self, collector: &StatsCollector) {
|
||||
if let Some(agent) = self.get_agent().await {
|
||||
let mut reports = HashMap::new();
|
||||
|
||||
for stats in agent.get_candidate_pairs_stats().await {
|
||||
let stats: ICECandidatePairStats = stats.into();
|
||||
reports.insert(stats.id.clone(), StatsReportType::CandidatePair(stats));
|
||||
}
|
||||
|
||||
for stats in agent.get_local_candidates_stats().await {
|
||||
reports.insert(
|
||||
stats.id.clone(),
|
||||
StatsReportType::from(LocalCandidate(stats)),
|
||||
);
|
||||
}
|
||||
|
||||
for stats in agent.get_remote_candidates_stats().await {
|
||||
reports.insert(
|
||||
stats.id.clone(),
|
||||
StatsReportType::from(RemoteCandidate(stats)),
|
||||
);
|
||||
}
|
||||
|
||||
collector.merge(reports);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use super::*;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::ice_transport::ice_gatherer::RTCIceGatherOptions;
|
||||
use crate::ice_transport::ice_server::RTCIceServer;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_new_ice_gatherer_success() -> Result<()> {
|
||||
let opts = RTCIceGatherOptions {
|
||||
ice_servers: vec![RTCIceServer {
|
||||
urls: vec!["stun:stun.l.google.com:19302".to_owned()],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let gatherer = APIBuilder::new().build().new_ice_gatherer(opts)?;
|
||||
|
||||
assert_eq!(
|
||||
gatherer.state(),
|
||||
RTCIceGathererState::New,
|
||||
"Expected gathering state new"
|
||||
);
|
||||
|
||||
let (gather_finished_tx, mut gather_finished_rx) = mpsc::channel::<()>(1);
|
||||
let gather_finished_tx = Arc::new(Mutex::new(Some(gather_finished_tx)));
|
||||
gatherer.on_local_candidate(Box::new(move |c: Option<RTCIceCandidate>| {
|
||||
let gather_finished_tx_clone = Arc::clone(&gather_finished_tx);
|
||||
Box::pin(async move {
|
||||
if c.is_none() {
|
||||
let mut tx = gather_finished_tx_clone.lock().await;
|
||||
tx.take();
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
gatherer.gather().await?;
|
||||
|
||||
let _ = gather_finished_rx.recv().await;
|
||||
|
||||
let params = gatherer.get_local_parameters().await?;
|
||||
|
||||
assert!(
|
||||
!params.username_fragment.is_empty() && !params.password.is_empty(),
|
||||
"Empty local username or password frag"
|
||||
);
|
||||
|
||||
let candidates = gatherer.get_local_candidates().await?;
|
||||
|
||||
assert!(!candidates.is_empty(), "No candidates gathered");
|
||||
|
||||
gatherer.close().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ice_gather_mdns_candidate_gathering() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
s.set_ice_multicast_dns_mode(ice::mdns::MulticastDnsMode::QueryAndGather);
|
||||
|
||||
let gatherer = APIBuilder::new()
|
||||
.with_setting_engine(s)
|
||||
.build()
|
||||
.new_ice_gatherer(RTCIceGatherOptions::default())?;
|
||||
|
||||
let (done_tx, mut done_rx) = mpsc::channel::<()>(1);
|
||||
let done_tx = Arc::new(Mutex::new(Some(done_tx)));
|
||||
gatherer.on_local_candidate(Box::new(move |c: Option<RTCIceCandidate>| {
|
||||
let done_tx_clone = Arc::clone(&done_tx);
|
||||
Box::pin(async move {
|
||||
if let Some(c) = c {
|
||||
if c.address.ends_with(".local") {
|
||||
let mut tx = done_tx_clone.lock().await;
|
||||
tx.take();
|
||||
}
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
gatherer.gather().await?;
|
||||
|
||||
let _ = done_rx.recv().await;
|
||||
|
||||
gatherer.close().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
use std::fmt;
|
||||
|
||||
/// ICEGathererState represents the current state of the ICE gatherer.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCIceGathererState {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICEGathererStateNew indicates object has been created but
|
||||
/// gather() has not been called.
|
||||
New,
|
||||
|
||||
/// ICEGathererStateGathering indicates gather() has been called,
|
||||
/// and the ICEGatherer is in the process of gathering candidates.
|
||||
Gathering,
|
||||
|
||||
/// ICEGathererStateComplete indicates the ICEGatherer has completed gathering.
|
||||
Complete,
|
||||
|
||||
/// ICEGathererStateClosed indicates the closed state can only be entered
|
||||
/// when the ICEGatherer has been closed intentionally by calling close().
|
||||
Closed,
|
||||
}
|
||||
|
||||
const ICE_GATHERED_STATE_NEW_STR: &str = "new";
|
||||
const ICE_GATHERED_STATE_GATHERING_STR: &str = "gathering";
|
||||
const ICE_GATHERED_STATE_COMPLETE_STR: &str = "complete";
|
||||
const ICE_GATHERED_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
impl From<&str> for RTCIceGathererState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_GATHERED_STATE_NEW_STR => RTCIceGathererState::New,
|
||||
ICE_GATHERED_STATE_GATHERING_STR => RTCIceGathererState::Gathering,
|
||||
ICE_GATHERED_STATE_COMPLETE_STR => RTCIceGathererState::Complete,
|
||||
ICE_GATHERED_STATE_CLOSED_STR => RTCIceGathererState::Closed,
|
||||
_ => RTCIceGathererState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCIceGathererState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCIceGathererState::New,
|
||||
2 => RTCIceGathererState::Gathering,
|
||||
3 => RTCIceGathererState::Complete,
|
||||
4 => RTCIceGathererState::Closed,
|
||||
_ => RTCIceGathererState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceGathererState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceGathererState::New => write!(f, "{ICE_GATHERED_STATE_NEW_STR}"),
|
||||
RTCIceGathererState::Gathering => write!(f, "{ICE_GATHERED_STATE_GATHERING_STR}"),
|
||||
RTCIceGathererState::Complete => {
|
||||
write!(f, "{ICE_GATHERED_STATE_COMPLETE_STR}")
|
||||
}
|
||||
RTCIceGathererState::Closed => {
|
||||
write!(f, "{ICE_GATHERED_STATE_CLOSED_STR}")
|
||||
}
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_ice_gatherer_state_string() {
|
||||
let tests = vec![
|
||||
(RTCIceGathererState::Unspecified, "Unspecified"),
|
||||
(RTCIceGathererState::New, "new"),
|
||||
(RTCIceGathererState::Gathering, "gathering"),
|
||||
(RTCIceGathererState::Complete, "complete"),
|
||||
(RTCIceGathererState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
use std::fmt;
|
||||
|
||||
/// ICEGatheringState describes the state of the candidate gathering process.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCIceGatheringState {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICEGatheringStateNew indicates that any of the ICETransports are
|
||||
/// in the "new" gathering state and none of the transports are in the
|
||||
/// "gathering" state, or there are no transports.
|
||||
New,
|
||||
|
||||
/// ICEGatheringStateGathering indicates that any of the ICETransports
|
||||
/// are in the "gathering" state.
|
||||
Gathering,
|
||||
|
||||
/// ICEGatheringStateComplete indicates that at least one ICETransport
|
||||
/// exists, and all ICETransports are in the "completed" gathering state.
|
||||
Complete,
|
||||
}
|
||||
|
||||
const ICE_GATHERING_STATE_NEW_STR: &str = "new";
|
||||
const ICE_GATHERING_STATE_GATHERING_STR: &str = "gathering";
|
||||
const ICE_GATHERING_STATE_COMPLETE_STR: &str = "complete";
|
||||
|
||||
/// takes a string and converts it to ICEGatheringState
|
||||
impl From<&str> for RTCIceGatheringState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_GATHERING_STATE_NEW_STR => RTCIceGatheringState::New,
|
||||
ICE_GATHERING_STATE_GATHERING_STR => RTCIceGatheringState::Gathering,
|
||||
ICE_GATHERING_STATE_COMPLETE_STR => RTCIceGatheringState::Complete,
|
||||
_ => RTCIceGatheringState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceGatheringState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceGatheringState::New => write!(f, "{ICE_GATHERING_STATE_NEW_STR}"),
|
||||
RTCIceGatheringState::Gathering => write!(f, "{ICE_GATHERING_STATE_GATHERING_STR}"),
|
||||
RTCIceGatheringState::Complete => {
|
||||
write!(f, "{ICE_GATHERING_STATE_COMPLETE_STR}")
|
||||
}
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_ice_gathering_state() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCIceGatheringState::Unspecified),
|
||||
("new", RTCIceGatheringState::New),
|
||||
("gathering", RTCIceGatheringState::Gathering),
|
||||
("complete", RTCIceGatheringState::Complete),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(RTCIceGatheringState::from(state_string), expected_state);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_gathering_state_string() {
|
||||
let tests = vec![
|
||||
(RTCIceGatheringState::Unspecified, "Unspecified"),
|
||||
(RTCIceGatheringState::New, "new"),
|
||||
(RTCIceGatheringState::Gathering, "gathering"),
|
||||
(RTCIceGatheringState::Complete, "complete"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ICEParameters includes the ICE username fragment
|
||||
/// and password and other ICE-related parameters.
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct RTCIceParameters {
|
||||
pub username_fragment: String,
|
||||
pub password: String,
|
||||
pub ice_lite: bool,
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ICEProtocol indicates the transport protocol type that is used in the
|
||||
/// ice.URL structure.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum RTCIceProtocol {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// UDP indicates the URL uses a UDP transport.
|
||||
#[serde(rename = "udp")]
|
||||
Udp,
|
||||
|
||||
/// TCP indicates the URL uses a TCP transport.
|
||||
#[serde(rename = "tcp")]
|
||||
Tcp,
|
||||
}
|
||||
|
||||
const ICE_PROTOCOL_UDP_STR: &str = "udp";
|
||||
const ICE_PROTOCOL_TCP_STR: &str = "tcp";
|
||||
|
||||
/// takes a string and converts it to ICEProtocol
|
||||
impl From<&str> for RTCIceProtocol {
|
||||
fn from(raw: &str) -> Self {
|
||||
if raw.to_uppercase() == ICE_PROTOCOL_UDP_STR.to_uppercase() {
|
||||
RTCIceProtocol::Udp
|
||||
} else if raw.to_uppercase() == ICE_PROTOCOL_TCP_STR.to_uppercase() {
|
||||
RTCIceProtocol::Tcp
|
||||
} else {
|
||||
RTCIceProtocol::Unspecified
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceProtocol {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceProtocol::Udp => write!(f, "{ICE_PROTOCOL_UDP_STR}"),
|
||||
RTCIceProtocol::Tcp => write!(f, "{ICE_PROTOCOL_TCP_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_ice_protocol() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCIceProtocol::Unspecified),
|
||||
("udp", RTCIceProtocol::Udp),
|
||||
("tcp", RTCIceProtocol::Tcp),
|
||||
("UDP", RTCIceProtocol::Udp),
|
||||
("TCP", RTCIceProtocol::Tcp),
|
||||
];
|
||||
|
||||
for (proto_string, expected_proto) in tests {
|
||||
let actual = RTCIceProtocol::from(proto_string);
|
||||
assert_eq!(actual, expected_proto);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_protocol_string() {
|
||||
let tests = vec![
|
||||
(RTCIceProtocol::Unspecified, "Unspecified"),
|
||||
(RTCIceProtocol::Udp, "udp"),
|
||||
(RTCIceProtocol::Tcp, "tcp"),
|
||||
];
|
||||
|
||||
for (proto, expected_string) in tests {
|
||||
assert_eq!(proto.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
use std::fmt;
|
||||
|
||||
/// ICERole describes the role ice.Agent is playing in selecting the
|
||||
/// preferred the candidate pair.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCIceRole {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICERoleControlling indicates that the ICE agent that is responsible
|
||||
/// for selecting the final choice of candidate pairs and signaling them
|
||||
/// through STUN and an updated offer, if needed. In any session, one agent
|
||||
/// is always controlling. The other is the controlled agent.
|
||||
Controlling,
|
||||
|
||||
/// ICERoleControlled indicates that an ICE agent that waits for the
|
||||
/// controlling agent to select the final choice of candidate pairs.
|
||||
Controlled,
|
||||
}
|
||||
|
||||
const ICE_ROLE_CONTROLLING_STR: &str = "controlling";
|
||||
const ICE_ROLE_CONTROLLED_STR: &str = "controlled";
|
||||
|
||||
impl From<&str> for RTCIceRole {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_ROLE_CONTROLLING_STR => RTCIceRole::Controlling,
|
||||
ICE_ROLE_CONTROLLED_STR => RTCIceRole::Controlled,
|
||||
_ => RTCIceRole::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceRole {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceRole::Controlling => write!(f, "{ICE_ROLE_CONTROLLING_STR}"),
|
||||
RTCIceRole::Controlled => write!(f, "{ICE_ROLE_CONTROLLED_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_ice_role() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCIceRole::Unspecified),
|
||||
("controlling", RTCIceRole::Controlling),
|
||||
("controlled", RTCIceRole::Controlled),
|
||||
];
|
||||
|
||||
for (role_string, expected_role) in tests {
|
||||
assert_eq!(RTCIceRole::from(role_string), expected_role);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_role_string() {
|
||||
let tests = vec![
|
||||
(RTCIceRole::Unspecified, "Unspecified"),
|
||||
(RTCIceRole::Controlling, "controlling"),
|
||||
(RTCIceRole::Controlled, "controlled"),
|
||||
];
|
||||
|
||||
for (proto, expected_string) in tests {
|
||||
assert_eq!(proto.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::ice_transport::ice_credential_type::RTCIceCredentialType;
|
||||
|
||||
/// ICEServer describes a single STUN and TURN server that can be used by
|
||||
/// the ICEAgent to establish a connection with a peer.
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize, Hash)]
|
||||
pub struct RTCIceServer {
|
||||
pub urls: Vec<String>,
|
||||
pub username: String,
|
||||
pub credential: String,
|
||||
pub credential_type: RTCIceCredentialType,
|
||||
}
|
||||
|
||||
impl RTCIceServer {
|
||||
pub(crate) fn parse_url(&self, url_str: &str) -> Result<ice::url::Url> {
|
||||
Ok(ice::url::Url::parse_url(url_str)?)
|
||||
}
|
||||
|
||||
pub(crate) fn validate(&self) -> Result<()> {
|
||||
self.urls()?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn urls(&self) -> Result<Vec<ice::url::Url>> {
|
||||
let mut urls = vec![];
|
||||
|
||||
for url_str in &self.urls {
|
||||
let mut url = self.parse_url(url_str)?;
|
||||
if url.scheme == ice::url::SchemeType::Turn || url.scheme == ice::url::SchemeType::Turns
|
||||
{
|
||||
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3.2)
|
||||
if self.username.is_empty() || self.credential.is_empty() {
|
||||
return Err(Error::ErrNoTurnCredentials);
|
||||
}
|
||||
url.username = self.username.clone();
|
||||
|
||||
match self.credential_type {
|
||||
RTCIceCredentialType::Password => {
|
||||
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3.3)
|
||||
url.password = self.credential.clone();
|
||||
}
|
||||
RTCIceCredentialType::Oauth => {
|
||||
// https://www.w3.org/TR/webrtc/#set-the-configuration (step #11.3.4)
|
||||
/*if _, ok: = s.Credential.(OAuthCredential); !ok {
|
||||
return nil,
|
||||
&rtcerr.InvalidAccessError{Err: ErrTurnCredentials
|
||||
}
|
||||
}*/
|
||||
}
|
||||
_ => return Err(Error::ErrTurnCredentials),
|
||||
};
|
||||
}
|
||||
|
||||
urls.push(url);
|
||||
}
|
||||
|
||||
Ok(urls)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_ice_server_validate_success() {
|
||||
let tests = vec![
|
||||
(
|
||||
RTCIceServer {
|
||||
urls: vec!["turn:192.158.29.39?transport=udp".to_owned()],
|
||||
username: "unittest".to_owned(),
|
||||
credential: "placeholder".to_owned(),
|
||||
credential_type: RTCIceCredentialType::Password,
|
||||
},
|
||||
true,
|
||||
),
|
||||
(
|
||||
RTCIceServer {
|
||||
urls: vec!["turn:[2001:db8:1234:5678::1]?transport=udp".to_owned()],
|
||||
username: "unittest".to_owned(),
|
||||
credential: "placeholder".to_owned(),
|
||||
credential_type: RTCIceCredentialType::Password,
|
||||
},
|
||||
true,
|
||||
),
|
||||
/*TODO:(ICEServer{
|
||||
URLs: []string{"turn:192.158.29.39?transport=udp"},
|
||||
Username: "unittest".to_owned(),
|
||||
Credential: OAuthCredential{
|
||||
MACKey: "WmtzanB3ZW9peFhtdm42NzUzNG0=",
|
||||
AccessToken: "AAwg3kPHWPfvk9bDFL936wYvkoctMADzQ5VhNDgeMR3+ZlZ35byg972fW8QjpEl7bx91YLBPFsIhsxloWcXPhA==",
|
||||
},
|
||||
CredentialType: ICECredentialTypeOauth,
|
||||
}, true),*/
|
||||
];
|
||||
|
||||
for (ice_server, expected_validate) in tests {
|
||||
let result = ice_server.urls();
|
||||
assert_eq!(result.is_ok(), expected_validate);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_server_validate_failure() {
|
||||
let tests = vec![
|
||||
(
|
||||
RTCIceServer {
|
||||
urls: vec!["turn:192.158.29.39?transport=udp".to_owned()],
|
||||
..Default::default()
|
||||
},
|
||||
Error::ErrNoTurnCredentials,
|
||||
),
|
||||
(
|
||||
RTCIceServer {
|
||||
urls: vec!["turn:192.158.29.39?transport=udp".to_owned()],
|
||||
username: "unittest".to_owned(),
|
||||
credential: String::new(),
|
||||
credential_type: RTCIceCredentialType::Password,
|
||||
},
|
||||
Error::ErrNoTurnCredentials,
|
||||
),
|
||||
(
|
||||
RTCIceServer {
|
||||
urls: vec!["turn:192.158.29.39?transport=udp".to_owned()],
|
||||
username: "unittest".to_owned(),
|
||||
credential: String::new(),
|
||||
credential_type: RTCIceCredentialType::Oauth,
|
||||
},
|
||||
Error::ErrNoTurnCredentials,
|
||||
),
|
||||
(
|
||||
RTCIceServer {
|
||||
urls: vec!["turn:192.158.29.39?transport=udp".to_owned()],
|
||||
username: "unittest".to_owned(),
|
||||
credential: String::new(),
|
||||
credential_type: RTCIceCredentialType::Unspecified,
|
||||
},
|
||||
Error::ErrNoTurnCredentials,
|
||||
),
|
||||
];
|
||||
|
||||
for (ice_server, expected_err) in tests {
|
||||
if let Err(err) = ice_server.urls() {
|
||||
assert_eq!(err, expected_err, "{ice_server:?} with err {err:?}");
|
||||
} else {
|
||||
panic!("expected error, but got ok");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_server_validate_failure_err_stun_query() {
|
||||
let tests = vec![(
|
||||
RTCIceServer {
|
||||
urls: vec!["stun:google.de?transport=udp".to_owned()],
|
||||
username: "unittest".to_owned(),
|
||||
credential: String::new(),
|
||||
credential_type: RTCIceCredentialType::Oauth,
|
||||
},
|
||||
ice::Error::ErrStunQuery,
|
||||
)];
|
||||
|
||||
for (ice_server, expected_err) in tests {
|
||||
if let Err(err) = ice_server.urls() {
|
||||
assert_eq!(err, expected_err, "{ice_server:?} with err {err:?}");
|
||||
} else {
|
||||
panic!("expected error, but got ok");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
use std::fmt;
|
||||
|
||||
use ice::state::ConnectionState;
|
||||
|
||||
/// ICETransportState represents the current state of the ICE transport.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCIceTransportState {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// ICETransportStateNew indicates the ICETransport is waiting
|
||||
/// for remote candidates to be supplied.
|
||||
New,
|
||||
|
||||
/// ICETransportStateChecking indicates the ICETransport has
|
||||
/// received at least one remote candidate, and a local and remote
|
||||
/// ICECandidateComplete dictionary was not added as the last candidate.
|
||||
Checking,
|
||||
|
||||
/// ICETransportStateConnected indicates the ICETransport has
|
||||
/// received a response to an outgoing connectivity check, or has
|
||||
/// received incoming DTLS/media after a successful response to an
|
||||
/// incoming connectivity check, but is still checking other candidate
|
||||
/// pairs to see if there is a better connection.
|
||||
Connected,
|
||||
|
||||
/// ICETransportStateCompleted indicates the ICETransport tested
|
||||
/// all appropriate candidate pairs and at least one functioning
|
||||
/// candidate pair has been found.
|
||||
Completed,
|
||||
|
||||
/// ICETransportStateFailed indicates the ICETransport the last
|
||||
/// candidate was added and all appropriate candidate pairs have either
|
||||
/// failed connectivity checks or have lost consent.
|
||||
Failed,
|
||||
|
||||
/// ICETransportStateDisconnected indicates the ICETransport has received
|
||||
/// at least one local and remote candidate, but the final candidate was
|
||||
/// received yet and all appropriate candidate pairs thus far have been
|
||||
/// tested and failed.
|
||||
Disconnected,
|
||||
|
||||
/// ICETransportStateClosed indicates the ICETransport has shut down
|
||||
/// and is no longer responding to STUN requests.
|
||||
Closed,
|
||||
}
|
||||
|
||||
const ICE_TRANSPORT_STATE_NEW_STR: &str = "new";
|
||||
const ICE_TRANSPORT_STATE_CHECKING_STR: &str = "checking";
|
||||
const ICE_TRANSPORT_STATE_CONNECTED_STR: &str = "connected";
|
||||
const ICE_TRANSPORT_STATE_COMPLETED_STR: &str = "completed";
|
||||
const ICE_TRANSPORT_STATE_FAILED_STR: &str = "failed";
|
||||
const ICE_TRANSPORT_STATE_DISCONNECTED_STR: &str = "disconnected";
|
||||
const ICE_TRANSPORT_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
impl From<&str> for RTCIceTransportState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_TRANSPORT_STATE_NEW_STR => RTCIceTransportState::New,
|
||||
ICE_TRANSPORT_STATE_CHECKING_STR => RTCIceTransportState::Checking,
|
||||
ICE_TRANSPORT_STATE_CONNECTED_STR => RTCIceTransportState::Connected,
|
||||
ICE_TRANSPORT_STATE_COMPLETED_STR => RTCIceTransportState::Completed,
|
||||
ICE_TRANSPORT_STATE_FAILED_STR => RTCIceTransportState::Failed,
|
||||
ICE_TRANSPORT_STATE_DISCONNECTED_STR => RTCIceTransportState::Disconnected,
|
||||
ICE_TRANSPORT_STATE_CLOSED_STR => RTCIceTransportState::Closed,
|
||||
_ => RTCIceTransportState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCIceTransportState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => Self::New,
|
||||
2 => Self::Checking,
|
||||
3 => Self::Connected,
|
||||
4 => Self::Completed,
|
||||
5 => Self::Failed,
|
||||
6 => Self::Disconnected,
|
||||
7 => Self::Closed,
|
||||
_ => Self::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceTransportState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCIceTransportState::New => write!(f, "{ICE_TRANSPORT_STATE_NEW_STR}"),
|
||||
RTCIceTransportState::Checking => write!(f, "{ICE_TRANSPORT_STATE_CHECKING_STR}"),
|
||||
RTCIceTransportState::Connected => {
|
||||
write!(f, "{ICE_TRANSPORT_STATE_CONNECTED_STR}")
|
||||
}
|
||||
RTCIceTransportState::Completed => write!(f, "{ICE_TRANSPORT_STATE_COMPLETED_STR}"),
|
||||
RTCIceTransportState::Failed => {
|
||||
write!(f, "{ICE_TRANSPORT_STATE_FAILED_STR}")
|
||||
}
|
||||
RTCIceTransportState::Disconnected => {
|
||||
write!(f, "{ICE_TRANSPORT_STATE_DISCONNECTED_STR}")
|
||||
}
|
||||
RTCIceTransportState::Closed => {
|
||||
write!(f, "{ICE_TRANSPORT_STATE_CLOSED_STR}")
|
||||
}
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ConnectionState> for RTCIceTransportState {
|
||||
fn from(raw: ConnectionState) -> Self {
|
||||
match raw {
|
||||
ConnectionState::New => RTCIceTransportState::New,
|
||||
ConnectionState::Checking => RTCIceTransportState::Checking,
|
||||
ConnectionState::Connected => RTCIceTransportState::Connected,
|
||||
ConnectionState::Completed => RTCIceTransportState::Completed,
|
||||
ConnectionState::Failed => RTCIceTransportState::Failed,
|
||||
ConnectionState::Disconnected => RTCIceTransportState::Disconnected,
|
||||
ConnectionState::Closed => RTCIceTransportState::Closed,
|
||||
_ => RTCIceTransportState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCIceTransportState {
|
||||
pub(crate) fn to_ice(self) -> ConnectionState {
|
||||
match self {
|
||||
RTCIceTransportState::New => ConnectionState::New,
|
||||
RTCIceTransportState::Checking => ConnectionState::Checking,
|
||||
RTCIceTransportState::Connected => ConnectionState::Connected,
|
||||
RTCIceTransportState::Completed => ConnectionState::Completed,
|
||||
RTCIceTransportState::Failed => ConnectionState::Failed,
|
||||
RTCIceTransportState::Disconnected => ConnectionState::Disconnected,
|
||||
RTCIceTransportState::Closed => ConnectionState::Closed,
|
||||
_ => ConnectionState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_ice_transport_state_string() {
|
||||
let tests = vec![
|
||||
(RTCIceTransportState::Unspecified, "Unspecified"),
|
||||
(RTCIceTransportState::New, "new"),
|
||||
(RTCIceTransportState::Checking, "checking"),
|
||||
(RTCIceTransportState::Connected, "connected"),
|
||||
(RTCIceTransportState::Completed, "completed"),
|
||||
(RTCIceTransportState::Failed, "failed"),
|
||||
(RTCIceTransportState::Disconnected, "disconnected"),
|
||||
(RTCIceTransportState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_transport_state_convert() {
|
||||
let tests = vec![
|
||||
(
|
||||
RTCIceTransportState::Unspecified,
|
||||
ConnectionState::Unspecified,
|
||||
),
|
||||
(RTCIceTransportState::New, ConnectionState::New),
|
||||
(RTCIceTransportState::Checking, ConnectionState::Checking),
|
||||
(RTCIceTransportState::Connected, ConnectionState::Connected),
|
||||
(RTCIceTransportState::Completed, ConnectionState::Completed),
|
||||
(RTCIceTransportState::Failed, ConnectionState::Failed),
|
||||
(
|
||||
RTCIceTransportState::Disconnected,
|
||||
ConnectionState::Disconnected,
|
||||
),
|
||||
(RTCIceTransportState::Closed, ConnectionState::Closed),
|
||||
];
|
||||
|
||||
for (native, ice_state) in tests {
|
||||
assert_eq!(native.to_ice(), ice_state);
|
||||
assert_eq!(native, RTCIceTransportState::from(ice_state));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
use std::sync::atomic::AtomicU32;
|
||||
|
||||
use tokio::time::Duration;
|
||||
use waitgroup::WaitGroup;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::error::Result;
|
||||
use crate::ice_transport::ice_connection_state::RTCIceConnectionState;
|
||||
use crate::peer_connection::peer_connection_state::RTCPeerConnectionState;
|
||||
use crate::peer_connection::peer_connection_test::{
|
||||
close_pair_now, new_pair, signal_pair, until_connection_state,
|
||||
};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ice_transport_on_selected_candidate_pair_change() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut pc_offer, mut pc_answer) = new_pair(&api).await?;
|
||||
|
||||
let (ice_complete_tx, mut ice_complete_rx) = mpsc::channel::<()>(1);
|
||||
let ice_complete_tx = Arc::new(Mutex::new(Some(ice_complete_tx)));
|
||||
pc_answer.on_ice_connection_state_change(Box::new(move |ice_state: RTCIceConnectionState| {
|
||||
let ice_complete_tx2 = Arc::clone(&ice_complete_tx);
|
||||
Box::pin(async move {
|
||||
if ice_state == RTCIceConnectionState::Connected {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let mut done = ice_complete_tx2.lock().await;
|
||||
done.take();
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
let sender_called_candidate_change = Arc::new(AtomicU32::new(0));
|
||||
let sender_called_candidate_change2 = Arc::clone(&sender_called_candidate_change);
|
||||
pc_offer
|
||||
.sctp()
|
||||
.transport()
|
||||
.ice_transport()
|
||||
.on_selected_candidate_pair_change(Box::new(move |_: RTCIceCandidatePair| {
|
||||
sender_called_candidate_change2.store(1, Ordering::SeqCst);
|
||||
Box::pin(async {})
|
||||
}));
|
||||
|
||||
signal_pair(&mut pc_offer, &mut pc_answer).await?;
|
||||
|
||||
let _ = ice_complete_rx.recv().await;
|
||||
assert_eq!(
|
||||
sender_called_candidate_change.load(Ordering::SeqCst),
|
||||
1,
|
||||
"Sender ICETransport OnSelectedCandidateChange was never called"
|
||||
);
|
||||
|
||||
close_pair_now(&pc_offer, &pc_answer).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_ice_transport_get_selected_candidate_pair() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut offerer, mut answerer) = new_pair(&api).await?;
|
||||
|
||||
let peer_connection_connected = WaitGroup::new();
|
||||
until_connection_state(
|
||||
&mut offerer,
|
||||
&peer_connection_connected,
|
||||
RTCPeerConnectionState::Connected,
|
||||
)
|
||||
.await;
|
||||
until_connection_state(
|
||||
&mut answerer,
|
||||
&peer_connection_connected,
|
||||
RTCPeerConnectionState::Connected,
|
||||
)
|
||||
.await;
|
||||
|
||||
let offerer_selected_pair = offerer
|
||||
.sctp()
|
||||
.transport()
|
||||
.ice_transport()
|
||||
.get_selected_candidate_pair()
|
||||
.await;
|
||||
assert!(offerer_selected_pair.is_none());
|
||||
|
||||
let answerer_selected_pair = answerer
|
||||
.sctp()
|
||||
.transport()
|
||||
.ice_transport()
|
||||
.get_selected_candidate_pair()
|
||||
.await;
|
||||
assert!(answerer_selected_pair.is_none());
|
||||
|
||||
signal_pair(&mut offerer, &mut answerer).await?;
|
||||
|
||||
peer_connection_connected.wait().await;
|
||||
|
||||
let offerer_selected_pair = offerer
|
||||
.sctp()
|
||||
.transport()
|
||||
.ice_transport()
|
||||
.get_selected_candidate_pair()
|
||||
.await;
|
||||
assert!(offerer_selected_pair.is_some());
|
||||
|
||||
let answerer_selected_pair = answerer
|
||||
.sctp()
|
||||
.transport()
|
||||
.ice_transport()
|
||||
.get_selected_candidate_pair()
|
||||
.await;
|
||||
assert!(answerer_selected_pair.is_some());
|
||||
|
||||
close_pair_now(&offerer, &answerer).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+355
@@ -0,0 +1,355 @@
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicU8, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use ice::candidate::Candidate;
|
||||
use ice::state::ConnectionState;
|
||||
use ice_candidate::RTCIceCandidate;
|
||||
use ice_candidate_pair::RTCIceCandidatePair;
|
||||
use ice_gatherer::RTCIceGatherer;
|
||||
use ice_role::RTCIceRole;
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use util::Conn;
|
||||
|
||||
use crate::error::{flatten_errs, Error, Result};
|
||||
use crate::ice_transport::ice_parameters::RTCIceParameters;
|
||||
use crate::ice_transport::ice_transport_state::RTCIceTransportState;
|
||||
use crate::mux::endpoint::Endpoint;
|
||||
use crate::mux::mux_func::MatchFunc;
|
||||
use crate::mux::{Config, Mux};
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
use crate::stats::ICETransportStats;
|
||||
use crate::stats::StatsReportType::Transport;
|
||||
|
||||
#[cfg(test)]
|
||||
mod ice_transport_test;
|
||||
|
||||
pub mod ice_candidate;
|
||||
pub mod ice_candidate_pair;
|
||||
pub mod ice_candidate_type;
|
||||
pub mod ice_connection_state;
|
||||
pub mod ice_credential_type;
|
||||
pub mod ice_gatherer;
|
||||
pub mod ice_gatherer_state;
|
||||
pub mod ice_gathering_state;
|
||||
pub mod ice_parameters;
|
||||
pub mod ice_protocol;
|
||||
pub mod ice_role;
|
||||
pub mod ice_server;
|
||||
pub mod ice_transport_state;
|
||||
|
||||
pub type OnConnectionStateChangeHdlrFn = Box<
|
||||
dyn (FnMut(RTCIceTransportState) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
pub type OnSelectedCandidatePairChangeHdlrFn = Box<
|
||||
dyn (FnMut(RTCIceCandidatePair) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
#[derive(Default)]
|
||||
struct ICETransportInternal {
|
||||
role: RTCIceRole,
|
||||
conn: Option<Arc<dyn Conn + Send + Sync>>, //AgentConn
|
||||
mux: Option<Mux>,
|
||||
cancel_tx: Option<mpsc::Sender<()>>,
|
||||
}
|
||||
|
||||
/// ICETransport allows an application access to information about the ICE
|
||||
/// transport over which packets are sent and received.
|
||||
#[derive(Default)]
|
||||
pub struct RTCIceTransport {
|
||||
pub(crate) gatherer: Arc<RTCIceGatherer>,
|
||||
on_connection_state_change_handler: Arc<ArcSwapOption<Mutex<OnConnectionStateChangeHdlrFn>>>,
|
||||
on_selected_candidate_pair_change_handler:
|
||||
Arc<ArcSwapOption<Mutex<OnSelectedCandidatePairChangeHdlrFn>>>,
|
||||
state: Arc<AtomicU8>, // ICETransportState
|
||||
internal: Mutex<ICETransportInternal>,
|
||||
}
|
||||
|
||||
impl RTCIceTransport {
|
||||
/// creates a new new_icetransport.
|
||||
pub(crate) fn new(gatherer: Arc<RTCIceGatherer>) -> Self {
|
||||
RTCIceTransport {
|
||||
state: Arc::new(AtomicU8::new(RTCIceTransportState::New as u8)),
|
||||
gatherer,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
/// get_selected_candidate_pair returns the selected candidate pair on which packets are sent
|
||||
/// if there is no selected pair nil is returned
|
||||
pub async fn get_selected_candidate_pair(&self) -> Option<RTCIceCandidatePair> {
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
if let Some(ice_pair) = agent.get_selected_candidate_pair() {
|
||||
let local = RTCIceCandidate::from(&ice_pair.local);
|
||||
let remote = RTCIceCandidate::from(&ice_pair.remote);
|
||||
return Some(RTCIceCandidatePair::new(local, remote));
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Start incoming connectivity checks based on its configured role.
|
||||
pub async fn start(&self, params: &RTCIceParameters, role: Option<RTCIceRole>) -> Result<()> {
|
||||
if self.state() != RTCIceTransportState::New {
|
||||
return Err(Error::ErrICETransportNotInNew);
|
||||
}
|
||||
|
||||
self.ensure_gatherer().await?;
|
||||
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
let state = Arc::clone(&self.state);
|
||||
|
||||
let on_connection_state_change_handler =
|
||||
Arc::clone(&self.on_connection_state_change_handler);
|
||||
agent.on_connection_state_change(Box::new(move |ice_state: ConnectionState| {
|
||||
let s = RTCIceTransportState::from(ice_state);
|
||||
let on_connection_state_change_handler_clone =
|
||||
Arc::clone(&on_connection_state_change_handler);
|
||||
state.store(s as u8, Ordering::SeqCst);
|
||||
Box::pin(async move {
|
||||
if let Some(handler) = &*on_connection_state_change_handler_clone.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(s).await;
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
let on_selected_candidate_pair_change_handler =
|
||||
Arc::clone(&self.on_selected_candidate_pair_change_handler);
|
||||
agent.on_selected_candidate_pair_change(Box::new(
|
||||
move |local: &Arc<dyn Candidate + Send + Sync>,
|
||||
remote: &Arc<dyn Candidate + Send + Sync>| {
|
||||
let on_selected_candidate_pair_change_handler_clone =
|
||||
Arc::clone(&on_selected_candidate_pair_change_handler);
|
||||
let local = RTCIceCandidate::from(local);
|
||||
let remote = RTCIceCandidate::from(remote);
|
||||
Box::pin(async move {
|
||||
if let Some(handler) =
|
||||
&*on_selected_candidate_pair_change_handler_clone.load()
|
||||
{
|
||||
let mut f = handler.lock().await;
|
||||
f(RTCIceCandidatePair::new(local, remote)).await;
|
||||
}
|
||||
})
|
||||
},
|
||||
));
|
||||
|
||||
let role = if let Some(role) = role {
|
||||
role
|
||||
} else {
|
||||
RTCIceRole::Controlled
|
||||
};
|
||||
|
||||
let (cancel_tx, cancel_rx) = mpsc::channel(1);
|
||||
{
|
||||
let mut internal = self.internal.lock().await;
|
||||
internal.role = role;
|
||||
internal.cancel_tx = Some(cancel_tx);
|
||||
}
|
||||
|
||||
let conn: Arc<dyn Conn + Send + Sync> = match role {
|
||||
RTCIceRole::Controlling => {
|
||||
agent
|
||||
.dial(
|
||||
cancel_rx,
|
||||
params.username_fragment.clone(),
|
||||
params.password.clone(),
|
||||
)
|
||||
.await?
|
||||
}
|
||||
|
||||
RTCIceRole::Controlled => {
|
||||
agent
|
||||
.accept(
|
||||
cancel_rx,
|
||||
params.username_fragment.clone(),
|
||||
params.password.clone(),
|
||||
)
|
||||
.await?
|
||||
}
|
||||
|
||||
_ => return Err(Error::ErrICERoleUnknown),
|
||||
};
|
||||
|
||||
let config = Config {
|
||||
conn: Arc::clone(&conn),
|
||||
buffer_size: self.gatherer.setting_engine.get_receive_mtu(),
|
||||
};
|
||||
|
||||
{
|
||||
let mut internal = self.internal.lock().await;
|
||||
internal.conn = Some(conn);
|
||||
internal.mux = Some(Mux::new(config));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ErrICEAgentNotExist)
|
||||
}
|
||||
}
|
||||
|
||||
/// restart is not exposed currently because ORTC has users create a whole new ICETransport
|
||||
/// so for now lets keep it private so we don't cause ORTC users to depend on non-standard APIs
|
||||
pub(crate) async fn restart(&self) -> Result<()> {
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
agent
|
||||
.restart(
|
||||
self.gatherer
|
||||
.setting_engine
|
||||
.candidates
|
||||
.username_fragment
|
||||
.clone(),
|
||||
self.gatherer.setting_engine.candidates.password.clone(),
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
return Err(Error::ErrICEAgentNotExist);
|
||||
}
|
||||
self.gatherer.gather().await
|
||||
}
|
||||
|
||||
/// Stop irreversibly stops the ICETransport.
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
self.set_state(RTCIceTransportState::Closed);
|
||||
|
||||
let mut errs: Vec<Error> = vec![];
|
||||
{
|
||||
let mut internal = self.internal.lock().await;
|
||||
internal.cancel_tx.take();
|
||||
if let Some(mut mux) = internal.mux.take() {
|
||||
mux.close().await;
|
||||
}
|
||||
if let Some(conn) = internal.conn.take() {
|
||||
if let Err(err) = conn.close().await {
|
||||
errs.push(err.into());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(err) = self.gatherer.close().await {
|
||||
errs.push(err);
|
||||
}
|
||||
|
||||
flatten_errs(errs)
|
||||
}
|
||||
|
||||
/// on_selected_candidate_pair_change sets a handler that is invoked when a new
|
||||
/// ICE candidate pair is selected
|
||||
pub fn on_selected_candidate_pair_change(&self, f: OnSelectedCandidatePairChangeHdlrFn) {
|
||||
self.on_selected_candidate_pair_change_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// on_connection_state_change sets a handler that is fired when the ICE
|
||||
/// connection state changes.
|
||||
pub fn on_connection_state_change(&self, f: OnConnectionStateChangeHdlrFn) {
|
||||
self.on_connection_state_change_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// Role indicates the current role of the ICE transport.
|
||||
pub async fn role(&self) -> RTCIceRole {
|
||||
let internal = self.internal.lock().await;
|
||||
internal.role
|
||||
}
|
||||
|
||||
/// set_remote_candidates sets the sequence of candidates associated with the remote ICETransport.
|
||||
pub async fn set_remote_candidates(&self, remote_candidates: &[RTCIceCandidate]) -> Result<()> {
|
||||
self.ensure_gatherer().await?;
|
||||
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
for rc in remote_candidates {
|
||||
let c: Arc<dyn Candidate + Send + Sync> = Arc::new(rc.to_ice()?);
|
||||
agent.add_remote_candidate(&c)?;
|
||||
}
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ErrICEAgentNotExist)
|
||||
}
|
||||
}
|
||||
|
||||
/// adds a candidate associated with the remote ICETransport.
|
||||
pub async fn add_remote_candidate(
|
||||
&self,
|
||||
remote_candidate: Option<RTCIceCandidate>,
|
||||
) -> Result<()> {
|
||||
self.ensure_gatherer().await?;
|
||||
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
if let Some(r) = remote_candidate {
|
||||
let c: Arc<dyn Candidate + Send + Sync> = Arc::new(r.to_ice()?);
|
||||
agent.add_remote_candidate(&c)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ErrICEAgentNotExist)
|
||||
}
|
||||
}
|
||||
|
||||
/// State returns the current ice transport state.
|
||||
pub fn state(&self) -> RTCIceTransportState {
|
||||
RTCIceTransportState::from(self.state.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
pub(crate) fn set_state(&self, s: RTCIceTransportState) {
|
||||
self.state.store(s as u8, Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) async fn new_endpoint(&self, f: MatchFunc) -> Option<Arc<Endpoint>> {
|
||||
let internal = self.internal.lock().await;
|
||||
if let Some(mux) = &internal.mux {
|
||||
Some(mux.new_endpoint(f).await)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn ensure_gatherer(&self) -> Result<()> {
|
||||
if self.gatherer.get_agent().await.is_none() {
|
||||
self.gatherer.create_agent().await
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(&self, collector: &StatsCollector) {
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
let stats = ICETransportStats::new("ice_transport".to_string(), agent);
|
||||
|
||||
collector.insert("ice_transport".to_string(), Transport(stats));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn have_remote_credentials_change(
|
||||
&self,
|
||||
new_ufrag: &str,
|
||||
new_pwd: &str,
|
||||
) -> bool {
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
let (ufrag, upwd) = agent.get_remote_user_credentials().await;
|
||||
ufrag != new_ufrag || upwd != new_pwd
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn set_remote_credentials(
|
||||
&self,
|
||||
new_ufrag: String,
|
||||
new_pwd: String,
|
||||
) -> Result<()> {
|
||||
if let Some(agent) = self.gatherer.get_agent().await {
|
||||
Ok(agent.set_remote_credentials(new_ufrag, new_pwd).await?)
|
||||
} else {
|
||||
Err(Error::ErrICEAgentNotExist)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+33
@@ -0,0 +1,33 @@
|
||||
#![warn(rust_2018_idioms)]
|
||||
#![allow(dead_code)]
|
||||
|
||||
// re-export sub-crates
|
||||
pub use {data, dtls, ice, interceptor, mdns, media, rtcp, rtp, sctp, sdp, srtp, stun, turn, util};
|
||||
|
||||
pub mod api;
|
||||
pub mod data_channel;
|
||||
pub mod dtls_transport;
|
||||
pub mod error;
|
||||
pub mod ice_transport;
|
||||
pub mod mux;
|
||||
pub mod peer_connection;
|
||||
pub mod rtp_transceiver;
|
||||
pub mod sctp_transport;
|
||||
pub mod stats;
|
||||
pub mod track;
|
||||
|
||||
pub use error::Error;
|
||||
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
pub(crate) const UNSPECIFIED_STR: &str = "Unspecified";
|
||||
|
||||
/// Equal to UDP MTU
|
||||
pub(crate) const RECEIVE_MTU: usize = 1460;
|
||||
|
||||
pub(crate) const SDP_ATTRIBUTE_RID: &str = "rid";
|
||||
pub(crate) const SDP_ATTRIBUTE_SIMULCAST: &str = "simulcast";
|
||||
pub(crate) const GENERATED_CERTIFICATE_ORIGIN: &str = "WebRTC";
|
||||
pub(crate) const SDES_REPAIR_RTP_STREAM_ID_URI: &str =
|
||||
"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id";
|
||||
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
use std::collections::HashMap;
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::Mutex;
|
||||
use util::{Buffer, Conn};
|
||||
|
||||
use crate::mux::mux_func::MatchFunc;
|
||||
|
||||
/// Endpoint implements net.Conn. It is used to read muxed packets.
|
||||
pub struct Endpoint {
|
||||
pub(crate) id: usize,
|
||||
pub(crate) buffer: Buffer,
|
||||
pub(crate) match_fn: MatchFunc,
|
||||
pub(crate) next_conn: Arc<dyn Conn + Send + Sync>,
|
||||
pub(crate) endpoints: Arc<Mutex<HashMap<usize, Arc<Endpoint>>>>,
|
||||
}
|
||||
|
||||
impl Endpoint {
|
||||
/// Close unregisters the endpoint from the Mux
|
||||
pub async fn close(&self) -> Result<()> {
|
||||
self.buffer.close().await;
|
||||
|
||||
let mut endpoints = self.endpoints.lock().await;
|
||||
endpoints.remove(&self.id);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, util::Error>;
|
||||
|
||||
#[async_trait]
|
||||
impl Conn for Endpoint {
|
||||
async fn connect(&self, _addr: SocketAddr) -> Result<()> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
/// reads a packet of len(p) bytes from the underlying conn
|
||||
/// that are matched by the associated MuxFunc
|
||||
async fn recv(&self, buf: &mut [u8]) -> Result<usize> {
|
||||
match self.buffer.read(buf, None).await {
|
||||
Ok(n) => Ok(n),
|
||||
Err(err) => Err(io::Error::new(io::ErrorKind::Other, err.to_string()).into()),
|
||||
}
|
||||
}
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
/// writes bytes to the underlying conn
|
||||
async fn send(&self, buf: &[u8]) -> Result<usize> {
|
||||
self.next_conn.send(buf).await
|
||||
}
|
||||
|
||||
async fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> Result<usize> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
fn local_addr(&self) -> Result<SocketAddr> {
|
||||
self.next_conn.local_addr()
|
||||
}
|
||||
|
||||
fn remote_addr(&self) -> Option<SocketAddr> {
|
||||
self.next_conn.remote_addr()
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<()> {
|
||||
self.next_conn.close().await
|
||||
}
|
||||
}
|
||||
Vendored
+156
@@ -0,0 +1,156 @@
|
||||
#[cfg(test)]
|
||||
mod mux_test;
|
||||
|
||||
pub mod endpoint;
|
||||
pub mod mux_func;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::{mpsc, Mutex};
|
||||
use util::{Buffer, Conn};
|
||||
|
||||
use crate::error::Result;
|
||||
use crate::mux::endpoint::Endpoint;
|
||||
use crate::mux::mux_func::MatchFunc;
|
||||
use crate::util::Error;
|
||||
|
||||
/// mux multiplexes packets on a single socket (RFC7983)
|
||||
|
||||
/// The maximum amount of data that can be buffered before returning errors.
|
||||
const MAX_BUFFER_SIZE: usize = 1000 * 1000; // 1MB
|
||||
|
||||
/// Config collects the arguments to mux.Mux construction into
|
||||
/// a single structure
|
||||
pub struct Config {
|
||||
pub conn: Arc<dyn Conn + Send + Sync>,
|
||||
pub buffer_size: usize,
|
||||
}
|
||||
|
||||
/// Mux allows multiplexing
|
||||
#[derive(Clone)]
|
||||
pub struct Mux {
|
||||
id: Arc<AtomicUsize>,
|
||||
next_conn: Arc<dyn Conn + Send + Sync>,
|
||||
endpoints: Arc<Mutex<HashMap<usize, Arc<Endpoint>>>>,
|
||||
buffer_size: usize,
|
||||
closed_ch_tx: Option<mpsc::Sender<()>>,
|
||||
}
|
||||
|
||||
impl Mux {
|
||||
pub fn new(config: Config) -> Self {
|
||||
let (closed_ch_tx, closed_ch_rx) = mpsc::channel(1);
|
||||
let m = Mux {
|
||||
id: Arc::new(AtomicUsize::new(0)),
|
||||
next_conn: Arc::clone(&config.conn),
|
||||
endpoints: Arc::new(Mutex::new(HashMap::new())),
|
||||
buffer_size: config.buffer_size,
|
||||
closed_ch_tx: Some(closed_ch_tx),
|
||||
};
|
||||
|
||||
let buffer_size = m.buffer_size;
|
||||
let next_conn = Arc::clone(&m.next_conn);
|
||||
let endpoints = Arc::clone(&m.endpoints);
|
||||
tokio::spawn(async move {
|
||||
Mux::read_loop(buffer_size, next_conn, closed_ch_rx, endpoints).await;
|
||||
});
|
||||
|
||||
m
|
||||
}
|
||||
|
||||
/// creates a new Endpoint
|
||||
pub async fn new_endpoint(&self, f: MatchFunc) -> Arc<Endpoint> {
|
||||
let mut endpoints = self.endpoints.lock().await;
|
||||
|
||||
let id = self.id.fetch_add(1, Ordering::SeqCst);
|
||||
// Set a maximum size of the buffer in bytes.
|
||||
let e = Arc::new(Endpoint {
|
||||
id,
|
||||
buffer: Buffer::new(0, MAX_BUFFER_SIZE),
|
||||
match_fn: f,
|
||||
next_conn: Arc::clone(&self.next_conn),
|
||||
endpoints: Arc::clone(&self.endpoints),
|
||||
});
|
||||
|
||||
endpoints.insert(e.id, Arc::clone(&e));
|
||||
|
||||
e
|
||||
}
|
||||
|
||||
/// remove_endpoint removes an endpoint from the Mux
|
||||
pub async fn remove_endpoint(&mut self, e: &Endpoint) {
|
||||
let mut endpoints = self.endpoints.lock().await;
|
||||
endpoints.remove(&e.id);
|
||||
}
|
||||
|
||||
/// Close closes the Mux and all associated Endpoints.
|
||||
pub async fn close(&mut self) {
|
||||
self.closed_ch_tx.take();
|
||||
|
||||
let mut endpoints = self.endpoints.lock().await;
|
||||
endpoints.clear();
|
||||
}
|
||||
|
||||
async fn read_loop(
|
||||
buffer_size: usize,
|
||||
next_conn: Arc<dyn Conn + Send + Sync>,
|
||||
mut closed_ch_rx: mpsc::Receiver<()>,
|
||||
endpoints: Arc<Mutex<HashMap<usize, Arc<Endpoint>>>>,
|
||||
) {
|
||||
let mut buf = vec![0u8; buffer_size];
|
||||
let mut n = 0usize;
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = closed_ch_rx.recv() => break,
|
||||
result = next_conn.recv(&mut buf) => {
|
||||
if let Ok(m) = result{
|
||||
n = m;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if let Err(err) = Mux::dispatch(&buf[..n], &endpoints).await {
|
||||
log::error!("mux: ending readLoop dispatch error {:?}", err);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn dispatch(
|
||||
buf: &[u8],
|
||||
endpoints: &Arc<Mutex<HashMap<usize, Arc<Endpoint>>>>,
|
||||
) -> Result<()> {
|
||||
let mut endpoint = None;
|
||||
|
||||
{
|
||||
let eps = endpoints.lock().await;
|
||||
for ep in eps.values() {
|
||||
if (ep.match_fn)(buf) {
|
||||
endpoint = Some(Arc::clone(ep));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(ep) = endpoint {
|
||||
match ep.buffer.write(buf).await {
|
||||
// Expected when bytes are received faster than the endpoint can process them
|
||||
Err(Error::ErrBufferFull) => {
|
||||
log::info!("mux: endpoint buffer is full, dropping packet")
|
||||
}
|
||||
Ok(_) => (),
|
||||
Err(e) => return Err(crate::Error::Util(e)),
|
||||
}
|
||||
} else if !buf.is_empty() {
|
||||
log::warn!(
|
||||
"Warning: mux: no endpoint for packet starting with {}",
|
||||
buf[0]
|
||||
);
|
||||
} else {
|
||||
log::warn!("Warning: mux: no endpoint for zero length packet");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Vendored
+63
@@ -0,0 +1,63 @@
|
||||
/// MatchFunc allows custom logic for mapping packets to an Endpoint
|
||||
pub type MatchFunc = Box<dyn (Fn(&[u8]) -> bool) + Send + Sync>;
|
||||
|
||||
/// match_all always returns true
|
||||
pub fn match_all(_b: &[u8]) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
/// match_range is a MatchFunc that accepts packets with the first byte in [lower..upper]
|
||||
pub fn match_range(lower: u8, upper: u8) -> MatchFunc {
|
||||
Box::new(move |buf: &[u8]| -> bool {
|
||||
if buf.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let b = buf[0];
|
||||
b >= lower && b <= upper
|
||||
})
|
||||
}
|
||||
|
||||
/// MatchFuncs as described in RFC7983
|
||||
/// <https://tools.ietf.org/html/rfc7983>
|
||||
/// +----------------+
|
||||
/// | [0..3] -+--> forward to STUN
|
||||
/// | |
|
||||
/// | [16..19] -+--> forward to ZRTP
|
||||
/// | |
|
||||
/// packet --> | [20..63] -+--> forward to DTLS
|
||||
/// | |
|
||||
/// | [64..79] -+--> forward to TURN Channel
|
||||
/// | |
|
||||
/// | [128..191] -+--> forward to RTP/RTCP
|
||||
/// +----------------+
|
||||
/// match_dtls is a MatchFunc that accepts packets with the first byte in [20..63]
|
||||
/// as defied in RFC7983
|
||||
pub fn match_dtls(b: &[u8]) -> bool {
|
||||
match_range(20, 63)(b)
|
||||
}
|
||||
|
||||
// match_srtp_or_srtcp is a MatchFunc that accepts packets with the first byte in [128..191]
|
||||
// as defied in RFC7983
|
||||
pub fn match_srtp_or_srtcp(b: &[u8]) -> bool {
|
||||
match_range(128, 191)(b)
|
||||
}
|
||||
|
||||
pub(crate) fn is_rtcp(buf: &[u8]) -> bool {
|
||||
// Not long enough to determine RTP/RTCP
|
||||
if buf.len() < 4 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let rtcp_packet_type = buf[1];
|
||||
(192..=223).contains(&rtcp_packet_type)
|
||||
}
|
||||
|
||||
/// match_srtp is a MatchFunc that only matches SRTP and not SRTCP
|
||||
pub fn match_srtp(buf: &[u8]) -> bool {
|
||||
match_srtp_or_srtcp(buf) && !is_rtcp(buf)
|
||||
}
|
||||
|
||||
/// match_srtcp is a MatchFunc that only matches SRTCP and not SRTP
|
||||
pub fn match_srtcp(buf: &[u8]) -> bool {
|
||||
match_srtp_or_srtcp(buf) && is_rtcp(buf)
|
||||
}
|
||||
Vendored
+137
@@ -0,0 +1,137 @@
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use util::conn::conn_pipe::pipe;
|
||||
|
||||
use super::*;
|
||||
use crate::mux::mux_func::{match_all, match_srtp};
|
||||
|
||||
const TEST_PIPE_BUFFER_SIZE: usize = 8192;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_no_endpoints() -> crate::error::Result<()> {
|
||||
// In memory pipe
|
||||
let (ca, _) = pipe();
|
||||
|
||||
let mut m = Mux::new(Config {
|
||||
conn: Arc::new(ca),
|
||||
buffer_size: TEST_PIPE_BUFFER_SIZE,
|
||||
});
|
||||
|
||||
Mux::dispatch(&[0], &m.endpoints).await?;
|
||||
m.close().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct MuxErrorConn {
|
||||
idx: AtomicUsize,
|
||||
data: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
type Result<T> = std::result::Result<T, util::Error>;
|
||||
|
||||
#[async_trait]
|
||||
impl Conn for MuxErrorConn {
|
||||
async fn connect(&self, _addr: SocketAddr) -> Result<()> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
async fn recv(&self, buf: &mut [u8]) -> Result<usize> {
|
||||
let idx = self.idx.fetch_add(1, Ordering::SeqCst);
|
||||
if idx < self.data.len() {
|
||||
let n = std::cmp::min(buf.len(), self.data[idx].len());
|
||||
buf[..n].copy_from_slice(&self.data[idx][..n]);
|
||||
Ok(n)
|
||||
} else {
|
||||
Err(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("idx {} >= data.len {}", idx, self.data.len()),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> Result<(usize, SocketAddr)> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
async fn send(&self, _buf: &[u8]) -> Result<usize> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
async fn send_to(&self, _buf: &[u8], _target: SocketAddr) -> Result<usize> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
fn local_addr(&self) -> Result<SocketAddr> {
|
||||
Err(io::Error::new(io::ErrorKind::Other, "Not applicable").into())
|
||||
}
|
||||
|
||||
fn remote_addr(&self) -> Option<SocketAddr> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn close(&self) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_non_fatal_read() -> Result<()> {
|
||||
let expected_data = b"expected_data".to_vec();
|
||||
|
||||
let conn = Arc::new(MuxErrorConn {
|
||||
idx: AtomicUsize::new(0),
|
||||
data: vec![
|
||||
expected_data.clone(),
|
||||
expected_data.clone(),
|
||||
expected_data.clone(),
|
||||
],
|
||||
});
|
||||
|
||||
let mut m = Mux::new(Config {
|
||||
conn,
|
||||
buffer_size: TEST_PIPE_BUFFER_SIZE,
|
||||
});
|
||||
|
||||
let e = m.new_endpoint(Box::new(match_all)).await;
|
||||
let mut buff = vec![0u8; TEST_PIPE_BUFFER_SIZE];
|
||||
|
||||
let n = e.recv(&mut buff).await?;
|
||||
assert_eq!(&buff[..n], expected_data);
|
||||
|
||||
let n = e.recv(&mut buff).await?;
|
||||
assert_eq!(&buff[..n], expected_data);
|
||||
|
||||
let n = e.recv(&mut buff).await?;
|
||||
assert_eq!(&buff[..n], expected_data);
|
||||
|
||||
m.close().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_non_fatal_dispatch() -> Result<()> {
|
||||
let (ca, cb) = pipe();
|
||||
|
||||
let mut m = Mux::new(Config {
|
||||
conn: Arc::new(ca),
|
||||
buffer_size: TEST_PIPE_BUFFER_SIZE,
|
||||
});
|
||||
|
||||
let e = m.new_endpoint(Box::new(match_srtp)).await;
|
||||
e.buffer.set_limit_size(1).await;
|
||||
|
||||
for _ in 0..25 {
|
||||
let srtp_packet = [128, 1, 2, 3, 4].to_vec();
|
||||
cb.send(&srtp_packet).await?;
|
||||
}
|
||||
|
||||
m.close().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+295
@@ -0,0 +1,295 @@
|
||||
use std::ops::Add;
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use dtls::crypto::{CryptoPrivateKey, CryptoPrivateKeyKind};
|
||||
use rcgen::{CertificateParams, KeyPair};
|
||||
use ring::rand::SystemRandom;
|
||||
use ring::rsa;
|
||||
use ring::signature::{EcdsaKeyPair, Ed25519KeyPair};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::dtls_transport::dtls_fingerprint::RTCDtlsFingerprint;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::peer_connection::math_rand_alpha;
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
use crate::stats::{CertificateStats, StatsReportType};
|
||||
|
||||
/// Certificate represents a X.509 certificate used to authenticate WebRTC communications.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct RTCCertificate {
|
||||
/// DTLS certificate.
|
||||
pub(crate) dtls_certificate: dtls::crypto::Certificate,
|
||||
/// Timestamp after which this certificate is no longer valid.
|
||||
pub(crate) expires: SystemTime,
|
||||
/// Certificate's ID used for statistics.
|
||||
///
|
||||
/// Example: "certificate-1667202302853538793"
|
||||
///
|
||||
/// See [`CertificateStats`].
|
||||
pub(crate) stats_id: String,
|
||||
}
|
||||
|
||||
impl PartialEq for RTCCertificate {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.dtls_certificate == other.dtls_certificate
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCCertificate {
|
||||
/// Generates a new certificate from the given parameters.
|
||||
///
|
||||
/// See [`rcgen::Certificate::from_params`].
|
||||
pub fn from_params(params: CertificateParams) -> Result<Self> {
|
||||
let not_after = params.not_after;
|
||||
let x509_cert = rcgen::Certificate::from_params(params)?;
|
||||
|
||||
let key_pair = x509_cert.get_key_pair();
|
||||
let serialized_der = key_pair.serialize_der();
|
||||
|
||||
let private_key = if key_pair.is_compatible(&rcgen::PKCS_ED25519) {
|
||||
CryptoPrivateKey {
|
||||
kind: CryptoPrivateKeyKind::Ed25519(
|
||||
Ed25519KeyPair::from_pkcs8(&serialized_der)
|
||||
.map_err(|e| Error::new(e.to_string()))?,
|
||||
),
|
||||
serialized_der,
|
||||
}
|
||||
} else if key_pair.is_compatible(&rcgen::PKCS_ECDSA_P256_SHA256) {
|
||||
CryptoPrivateKey {
|
||||
kind: CryptoPrivateKeyKind::Ecdsa256(
|
||||
EcdsaKeyPair::from_pkcs8(
|
||||
&ring::signature::ECDSA_P256_SHA256_ASN1_SIGNING,
|
||||
&serialized_der,
|
||||
&SystemRandom::new(),
|
||||
)
|
||||
.map_err(|e| Error::new(e.to_string()))?,
|
||||
),
|
||||
serialized_der,
|
||||
}
|
||||
} else if key_pair.is_compatible(&rcgen::PKCS_RSA_SHA256) {
|
||||
CryptoPrivateKey {
|
||||
kind: CryptoPrivateKeyKind::Rsa256(
|
||||
rsa::KeyPair::from_pkcs8(&serialized_der)
|
||||
.map_err(|e| Error::new(e.to_string()))?,
|
||||
),
|
||||
serialized_der,
|
||||
}
|
||||
} else {
|
||||
return Err(Error::new("Unsupported key_pair".to_owned()));
|
||||
};
|
||||
|
||||
let expires = if cfg!(target_arch = "arm") {
|
||||
// Workaround for issue overflow when adding duration to instant on armv7
|
||||
// https://github.com/webrtc-rs/examples/issues/5 https://github.com/chronotope/chrono/issues/343
|
||||
SystemTime::now().add(Duration::from_secs(172800)) //60*60*48 or 2 days
|
||||
} else {
|
||||
not_after.into()
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
dtls_certificate: dtls::crypto::Certificate {
|
||||
certificate: vec![rustls::Certificate(x509_cert.serialize_der()?)],
|
||||
private_key,
|
||||
},
|
||||
expires,
|
||||
stats_id: gen_stats_id(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Generates a new certificate with default [`CertificateParams`] using the given keypair.
|
||||
pub fn from_key_pair(key_pair: KeyPair) -> Result<Self> {
|
||||
let mut params = CertificateParams::new(vec![math_rand_alpha(16)]);
|
||||
|
||||
if key_pair.is_compatible(&rcgen::PKCS_ED25519) {
|
||||
params.alg = &rcgen::PKCS_ED25519;
|
||||
} else if key_pair.is_compatible(&rcgen::PKCS_ECDSA_P256_SHA256) {
|
||||
params.alg = &rcgen::PKCS_ECDSA_P256_SHA256;
|
||||
} else if key_pair.is_compatible(&rcgen::PKCS_RSA_SHA256) {
|
||||
params.alg = &rcgen::PKCS_RSA_SHA256;
|
||||
} else {
|
||||
return Err(Error::new("Unsupported key_pair".to_owned()));
|
||||
};
|
||||
params.key_pair = Some(key_pair);
|
||||
|
||||
RTCCertificate::from_params(params)
|
||||
}
|
||||
|
||||
/// Parses a certificate from the ASCII PEM format.
|
||||
#[cfg(feature = "pem")]
|
||||
pub fn from_pem(pem_str: &str) -> Result<Self> {
|
||||
let mut pem_blocks = pem_str.split("\n\n");
|
||||
let first_block = if let Some(b) = pem_blocks.next() {
|
||||
b
|
||||
} else {
|
||||
return Err(Error::InvalidPEM("empty PEM".into()));
|
||||
};
|
||||
let expires_pem =
|
||||
pem::parse(first_block).map_err(|e| Error::new(format!("can't parse PEM: {e}")))?;
|
||||
if expires_pem.tag() != "EXPIRES" {
|
||||
return Err(Error::InvalidPEM(format!(
|
||||
"invalid tag (expected: 'EXPIRES', got '{}')",
|
||||
expires_pem.tag()
|
||||
)));
|
||||
}
|
||||
let mut bytes = [0u8; 8];
|
||||
bytes.copy_from_slice(&expires_pem.contents()[..8]);
|
||||
let expires = if let Some(e) =
|
||||
SystemTime::UNIX_EPOCH.checked_add(Duration::from_secs(u64::from_le_bytes(bytes)))
|
||||
{
|
||||
e
|
||||
} else {
|
||||
return Err(Error::InvalidPEM("failed to calculate SystemTime".into()));
|
||||
};
|
||||
let dtls_certificate =
|
||||
dtls::crypto::Certificate::from_pem(&pem_blocks.collect::<Vec<&str>>().join("\n\n"))?;
|
||||
Ok(RTCCertificate::from_existing(dtls_certificate, expires))
|
||||
}
|
||||
|
||||
/// Builds a [`RTCCertificate`] using the existing DTLS certificate.
|
||||
///
|
||||
/// Use this method when you have a persistent certificate (i.e. you don't want to generate a
|
||||
/// new one for each DTLS connection).
|
||||
///
|
||||
/// NOTE: ID used for statistics will be different as it's neither derived from the given
|
||||
/// certificate nor persisted along it when using [`serialize_pem`].
|
||||
pub fn from_existing(dtls_certificate: dtls::crypto::Certificate, expires: SystemTime) -> Self {
|
||||
Self {
|
||||
dtls_certificate,
|
||||
expires,
|
||||
// TODO: figure out if it needs to be persisted
|
||||
stats_id: gen_stats_id(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Serializes the certificate (including the private key) in PKCS#8 format in PEM.
|
||||
#[cfg(feature = "pem")]
|
||||
pub fn serialize_pem(&self) -> String {
|
||||
// Encode `expires` as a PEM block.
|
||||
//
|
||||
// TODO: serialize as nanos when https://github.com/rust-lang/rust/issues/103332 is fixed.
|
||||
let expires_pem = pem::Pem::new(
|
||||
"EXPIRES".to_string(),
|
||||
self.expires
|
||||
.duration_since(SystemTime::UNIX_EPOCH)
|
||||
.expect("expires to be valid")
|
||||
.as_secs()
|
||||
.to_le_bytes()
|
||||
.to_vec(),
|
||||
);
|
||||
format!(
|
||||
"{}\n{}",
|
||||
pem::encode(&expires_pem),
|
||||
self.dtls_certificate.serialize_pem()
|
||||
)
|
||||
}
|
||||
|
||||
/// get_fingerprints returns a SHA-256 fingerprint of this certificate.
|
||||
///
|
||||
/// TODO: return a fingerprint computed with the digest algorithm used in the certificate
|
||||
/// signature.
|
||||
pub fn get_fingerprints(&self) -> Vec<RTCDtlsFingerprint> {
|
||||
let mut fingerprints = Vec::new();
|
||||
|
||||
for c in &self.dtls_certificate.certificate {
|
||||
let mut h = Sha256::new();
|
||||
h.update(c.as_ref());
|
||||
let hashed = h.finalize();
|
||||
let values: Vec<String> = hashed.iter().map(|x| format! {"{x:02x}"}).collect();
|
||||
|
||||
fingerprints.push(RTCDtlsFingerprint {
|
||||
algorithm: "sha-256".to_owned(),
|
||||
value: values.join(":"),
|
||||
});
|
||||
}
|
||||
|
||||
fingerprints
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(&self, collector: &StatsCollector) {
|
||||
if let Some(fingerprint) = self.get_fingerprints().into_iter().next() {
|
||||
let stats = CertificateStats::new(self, fingerprint);
|
||||
collector.insert(
|
||||
self.stats_id.clone(),
|
||||
StatsReportType::CertificateStats(stats),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn gen_stats_id() -> String {
|
||||
format!(
|
||||
"certificate-{}",
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_nanos() as u64
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_generate_certificate_rsa() -> Result<()> {
|
||||
let key_pair = KeyPair::generate(&rcgen::PKCS_RSA_SHA256);
|
||||
assert!(key_pair.is_err(), "RcgenError::KeyGenerationUnavailable");
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_certificate_ecdsa() -> Result<()> {
|
||||
let kp = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let _cert = RTCCertificate::from_key_pair(kp)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_certificate_eddsa() -> Result<()> {
|
||||
let kp = KeyPair::generate(&rcgen::PKCS_ED25519)?;
|
||||
let _cert = RTCCertificate::from_key_pair(kp)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_certificate_equal() -> Result<()> {
|
||||
let kp1 = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let cert1 = RTCCertificate::from_key_pair(kp1)?;
|
||||
|
||||
let kp2 = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let cert2 = RTCCertificate::from_key_pair(kp2)?;
|
||||
|
||||
assert_ne!(cert1, cert2);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generate_certificate_expires_and_stats_id() -> Result<()> {
|
||||
let kp = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let cert = RTCCertificate::from_key_pair(kp)?;
|
||||
|
||||
let now = SystemTime::now();
|
||||
assert!(cert.expires.duration_since(now).is_ok());
|
||||
assert!(cert.stats_id.contains("certificate"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "pem")]
|
||||
#[test]
|
||||
fn test_certificate_serialize_pem_and_from_pem() -> Result<()> {
|
||||
let kp = KeyPair::generate(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let cert = RTCCertificate::from_key_pair(kp)?;
|
||||
|
||||
let pem = cert.serialize_pem();
|
||||
let loaded_cert = RTCCertificate::from_pem(&pem)?;
|
||||
|
||||
assert_eq!(loaded_cert, cert);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
use crate::ice_transport::ice_server::RTCIceServer;
|
||||
use crate::peer_connection::certificate::RTCCertificate;
|
||||
use crate::peer_connection::policy::bundle_policy::RTCBundlePolicy;
|
||||
use crate::peer_connection::policy::ice_transport_policy::RTCIceTransportPolicy;
|
||||
use crate::peer_connection::policy::rtcp_mux_policy::RTCRtcpMuxPolicy;
|
||||
|
||||
/// A Configuration defines how peer-to-peer communication via PeerConnection
|
||||
/// is established or re-established.
|
||||
/// Configurations may be set up once and reused across multiple connections.
|
||||
/// Configurations are treated as readonly. As long as they are unmodified,
|
||||
/// they are safe for concurrent use.
|
||||
#[derive(Default, Clone)]
|
||||
pub struct RTCConfiguration {
|
||||
/// iceservers defines a slice describing servers available to be used by
|
||||
/// ICE, such as STUN and TURN servers.
|
||||
pub ice_servers: Vec<RTCIceServer>,
|
||||
|
||||
/// icetransport_policy indicates which candidates the ICEAgent is allowed
|
||||
/// to use.
|
||||
pub ice_transport_policy: RTCIceTransportPolicy,
|
||||
|
||||
/// bundle_policy indicates which media-bundling policy to use when gathering
|
||||
/// ICE candidates.
|
||||
pub bundle_policy: RTCBundlePolicy,
|
||||
|
||||
/// rtcp_mux_policy indicates which rtcp-mux policy to use when gathering ICE
|
||||
/// candidates.
|
||||
pub rtcp_mux_policy: RTCRtcpMuxPolicy,
|
||||
|
||||
/// peer_identity sets the target peer identity for the PeerConnection.
|
||||
/// The PeerConnection will not establish a connection to a remote peer
|
||||
/// unless it can be successfully authenticated with the provided name.
|
||||
pub peer_identity: String,
|
||||
|
||||
/// Certificates describes a set of certificates that the PeerConnection
|
||||
/// uses to authenticate. Valid values for this parameter are created
|
||||
/// through calls to the generate_certificate function. Although any given
|
||||
/// DTLS connection will use only one certificate, this attribute allows the
|
||||
/// caller to provide multiple certificates that support different
|
||||
/// algorithms. The final certificate will be selected based on the DTLS
|
||||
/// handshake, which establishes which certificates are allowed. The
|
||||
/// PeerConnection implementation selects which of the certificates is
|
||||
/// used for a given connection; how certificates are selected is outside
|
||||
/// the scope of this specification. If this value is absent, then a default
|
||||
/// set of certificates is generated for each PeerConnection instance.
|
||||
pub certificates: Vec<RTCCertificate>,
|
||||
|
||||
/// icecandidate_pool_size describes the size of the prefetched ICE pool.
|
||||
pub ice_candidate_pool_size: u8,
|
||||
}
|
||||
|
||||
impl RTCConfiguration {
|
||||
/// get_iceservers side-steps the strict parsing mode of the ice package
|
||||
/// (as defined in https://tools.ietf.org/html/rfc7064) by copying and then
|
||||
/// stripping any erroneous queries from "stun(s):" URLs before parsing.
|
||||
pub(crate) fn get_ice_servers(&self) -> Vec<RTCIceServer> {
|
||||
let mut ice_servers = self.ice_servers.clone();
|
||||
|
||||
for ice_server in &mut ice_servers {
|
||||
for raw_url in &mut ice_server.urls {
|
||||
if raw_url.starts_with("stun") {
|
||||
// strip the query from "stun(s):" if present
|
||||
let parts: Vec<&str> = raw_url.split('?').collect();
|
||||
*raw_url = parts[0].to_owned();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ice_servers
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_configuration_get_iceservers() {
|
||||
{
|
||||
let expected_server_str = "stun:stun.l.google.com:19302";
|
||||
let cfg = RTCConfiguration {
|
||||
ice_servers: vec![RTCIceServer {
|
||||
urls: vec![expected_server_str.to_owned()],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let parsed_urls = cfg.get_ice_servers();
|
||||
assert_eq!(parsed_urls[0].urls[0], expected_server_str);
|
||||
}
|
||||
|
||||
{
|
||||
// ignore the fact that stun URLs shouldn't have a query
|
||||
let server_str = "stun:global.stun.twilio.com:3478?transport=udp";
|
||||
let expected_server_str = "stun:global.stun.twilio.com:3478";
|
||||
let cfg = RTCConfiguration {
|
||||
ice_servers: vec![RTCIceServer {
|
||||
urls: vec![server_str.to_owned()],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let parsed_urls = cfg.get_ice_servers();
|
||||
assert_eq!(parsed_urls[0].urls[0], expected_server_str);
|
||||
}
|
||||
}
|
||||
|
||||
/*TODO:#[test] fn test_configuration_json() {
|
||||
|
||||
let j = r#"
|
||||
{
|
||||
"iceServers": [{"URLs": ["turn:turn.example.org"],
|
||||
"username": "jch",
|
||||
"credential": "topsecret"
|
||||
}],
|
||||
"iceTransportPolicy": "relay",
|
||||
"bundlePolicy": "balanced",
|
||||
"rtcpMuxPolicy": "require"
|
||||
}"#;
|
||||
|
||||
conf := Configuration{
|
||||
ICEServers: []ICEServer{
|
||||
{
|
||||
URLs: []string{"turn:turn.example.org"},
|
||||
Username: "jch",
|
||||
Credential: "topsecret",
|
||||
},
|
||||
},
|
||||
ICETransportPolicy: ICETransportPolicyRelay,
|
||||
BundlePolicy: BundlePolicyBalanced,
|
||||
RTCPMuxPolicy: RTCPMuxPolicyRequire,
|
||||
}
|
||||
|
||||
var conf2 Configuration
|
||||
assert.NoError(t, json.Unmarshal([]byte(j), &conf2))
|
||||
assert.Equal(t, conf, conf2)
|
||||
|
||||
j2, err := json.Marshal(conf2)
|
||||
assert.NoError(t, err)
|
||||
|
||||
var conf3 Configuration
|
||||
assert.NoError(t, json.Unmarshal(j2, &conf3))
|
||||
assert.Equal(t, conf2, conf3)
|
||||
}*/
|
||||
}
|
||||
+2108
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,22 @@
|
||||
/// AnswerOptions structure describes the options used to control the answer
|
||||
/// creation process.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
|
||||
pub struct RTCAnswerOptions {
|
||||
/// voice_activity_detection allows the application to provide information
|
||||
/// about whether it wishes voice detection feature to be enabled or disabled.
|
||||
pub voice_activity_detection: bool,
|
||||
}
|
||||
|
||||
/// OfferOptions structure describes the options used to control the offer
|
||||
/// creation process
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone)]
|
||||
pub struct RTCOfferOptions {
|
||||
/// voice_activity_detection allows the application to provide information
|
||||
/// about whether it wishes voice detection feature to be enabled or disabled.
|
||||
pub voice_activity_detection: bool,
|
||||
|
||||
/// ice_restart forces the underlying ice gathering process to be restarted.
|
||||
/// When this value is true, the generated description will have ICE
|
||||
/// credentials that are different from the current credentials
|
||||
pub ice_restart: bool,
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
#[cfg(test)]
|
||||
mod operation_test;
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use tokio::sync::mpsc;
|
||||
use waitgroup::WaitGroup;
|
||||
|
||||
use crate::error::Result;
|
||||
|
||||
/// Operation is a function
|
||||
pub struct Operation(
|
||||
pub Box<dyn (FnMut() -> Pin<Box<dyn Future<Output = bool> + Send + 'static>>) + Send + Sync>,
|
||||
pub &'static str,
|
||||
);
|
||||
|
||||
impl Operation {
|
||||
pub(crate) fn new(
|
||||
op: impl FnMut() -> Pin<Box<dyn Future<Output = bool> + Send + 'static>> + Send + Sync + 'static,
|
||||
description: &'static str,
|
||||
) -> Self {
|
||||
Self(Box::new(op), description)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Operation {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_tuple("Operation")
|
||||
.field(&"_")
|
||||
.field(&self.1)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// Operations is a task executor.
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Operations {
|
||||
length: Arc<AtomicUsize>,
|
||||
ops_tx: Option<Arc<mpsc::UnboundedSender<Operation>>>,
|
||||
close_tx: Option<mpsc::Sender<()>>,
|
||||
}
|
||||
|
||||
impl Operations {
|
||||
pub(crate) fn new() -> Self {
|
||||
let length = Arc::new(AtomicUsize::new(0));
|
||||
let (ops_tx, ops_rx) = mpsc::unbounded_channel();
|
||||
let (close_tx, close_rx) = mpsc::channel(1);
|
||||
let l = Arc::clone(&length);
|
||||
let ops_tx = Arc::new(ops_tx);
|
||||
let ops_tx2 = Arc::clone(&ops_tx);
|
||||
tokio::spawn(async move {
|
||||
Operations::start(l, ops_tx, ops_rx, close_rx).await;
|
||||
});
|
||||
|
||||
Operations {
|
||||
length,
|
||||
ops_tx: Some(ops_tx2),
|
||||
close_tx: Some(close_tx),
|
||||
}
|
||||
}
|
||||
|
||||
/// enqueue adds a new action to be executed. If there are no actions scheduled,
|
||||
/// the execution will start immediately in a new goroutine.
|
||||
pub(crate) async fn enqueue(&self, op: Operation) -> Result<()> {
|
||||
if let Some(ops_tx) = &self.ops_tx {
|
||||
return Operations::enqueue_inner(op, ops_tx, &self.length);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn enqueue_inner(
|
||||
op: Operation,
|
||||
ops_tx: &Arc<mpsc::UnboundedSender<Operation>>,
|
||||
length: &Arc<AtomicUsize>,
|
||||
) -> Result<()> {
|
||||
length.fetch_add(1, Ordering::SeqCst);
|
||||
ops_tx.send(op)?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// is_empty checks if there are tasks in the queue
|
||||
pub(crate) async fn is_empty(&self) -> bool {
|
||||
self.length.load(Ordering::SeqCst) == 0
|
||||
}
|
||||
|
||||
/// Done blocks until all currently enqueued operations are finished executing.
|
||||
/// For more complex synchronization, use Enqueue directly.
|
||||
pub(crate) async fn done(&self) {
|
||||
let wg = WaitGroup::new();
|
||||
let mut w = Some(wg.worker());
|
||||
let _ = self
|
||||
.enqueue(Operation::new(
|
||||
move || {
|
||||
let _d = w.take();
|
||||
Box::pin(async { false })
|
||||
},
|
||||
"Operation::done",
|
||||
))
|
||||
.await;
|
||||
wg.wait().await;
|
||||
}
|
||||
|
||||
pub(crate) async fn start(
|
||||
length: Arc<AtomicUsize>,
|
||||
ops_tx: Arc<mpsc::UnboundedSender<Operation>>,
|
||||
mut ops_rx: mpsc::UnboundedReceiver<Operation>,
|
||||
mut close_rx: mpsc::Receiver<()>,
|
||||
) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = close_rx.recv() => {
|
||||
break;
|
||||
}
|
||||
result = ops_rx.recv() => {
|
||||
if let Some(mut f) = result {
|
||||
length.fetch_sub(1, Ordering::SeqCst);
|
||||
if f.0().await {
|
||||
// Requeue this operation
|
||||
let _ = Operations::enqueue_inner(f, &ops_tx, &length);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn close(&self) -> Result<()> {
|
||||
if let Some(close_tx) = &self.close_tx {
|
||||
close_tx.send(()).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use super::*;
|
||||
use crate::error::Result;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_operations_enqueue() -> Result<()> {
|
||||
let ops = Operations::new();
|
||||
for _ in 0..100 {
|
||||
let results = Arc::new(Mutex::new(vec![0; 16]));
|
||||
for k in 0..16 {
|
||||
let r = Arc::clone(&results);
|
||||
ops.enqueue(Operation::new(
|
||||
move || {
|
||||
let r2 = Arc::clone(&r);
|
||||
Box::pin(async move {
|
||||
let mut r3 = r2.lock().await;
|
||||
r3[k] += k * k;
|
||||
r3[k] == 225
|
||||
})
|
||||
},
|
||||
"test_operations_enqueue",
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
|
||||
ops.done().await;
|
||||
let expected = vec![
|
||||
0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 450,
|
||||
];
|
||||
{
|
||||
let r = results.lock().await;
|
||||
assert_eq!(r.len(), expected.len());
|
||||
assert_eq!(&*r, &expected);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_operations_done() -> Result<()> {
|
||||
let ops = Operations::new();
|
||||
ops.done().await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,151 @@
|
||||
use std::fmt;
|
||||
|
||||
/// PeerConnectionState indicates the state of the PeerConnection.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCPeerConnectionState {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// PeerConnectionStateNew indicates that any of the ICETransports or
|
||||
/// DTLSTransports are in the "new" state and none of the transports are
|
||||
/// in the "connecting", "checking", "failed" or "disconnected" state, or
|
||||
/// all transports are in the "closed" state, or there are no transports.
|
||||
New,
|
||||
|
||||
/// PeerConnectionStateConnecting indicates that any of the
|
||||
/// ICETransports or DTLSTransports are in the "connecting" or
|
||||
/// "checking" state and none of them is in the "failed" state.
|
||||
Connecting,
|
||||
|
||||
/// PeerConnectionStateConnected indicates that all ICETransports and
|
||||
/// DTLSTransports are in the "connected", "completed" or "closed" state
|
||||
/// and at least one of them is in the "connected" or "completed" state.
|
||||
Connected,
|
||||
|
||||
/// PeerConnectionStateDisconnected indicates that any of the
|
||||
/// ICETransports or DTLSTransports are in the "disconnected" state
|
||||
/// and none of them are in the "failed" or "connecting" or "checking" state.
|
||||
Disconnected,
|
||||
|
||||
/// PeerConnectionStateFailed indicates that any of the ICETransports
|
||||
/// or DTLSTransports are in a "failed" state.
|
||||
Failed,
|
||||
|
||||
/// PeerConnectionStateClosed indicates the peer connection is closed
|
||||
/// and the isClosed member variable of PeerConnection is true.
|
||||
Closed,
|
||||
}
|
||||
|
||||
const PEER_CONNECTION_STATE_NEW_STR: &str = "new";
|
||||
const PEER_CONNECTION_STATE_CONNECTING_STR: &str = "connecting";
|
||||
const PEER_CONNECTION_STATE_CONNECTED_STR: &str = "connected";
|
||||
const PEER_CONNECTION_STATE_DISCONNECTED_STR: &str = "disconnected";
|
||||
const PEER_CONNECTION_STATE_FAILED_STR: &str = "failed";
|
||||
const PEER_CONNECTION_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
impl From<&str> for RTCPeerConnectionState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
PEER_CONNECTION_STATE_NEW_STR => RTCPeerConnectionState::New,
|
||||
PEER_CONNECTION_STATE_CONNECTING_STR => RTCPeerConnectionState::Connecting,
|
||||
PEER_CONNECTION_STATE_CONNECTED_STR => RTCPeerConnectionState::Connected,
|
||||
PEER_CONNECTION_STATE_DISCONNECTED_STR => RTCPeerConnectionState::Disconnected,
|
||||
PEER_CONNECTION_STATE_FAILED_STR => RTCPeerConnectionState::Failed,
|
||||
PEER_CONNECTION_STATE_CLOSED_STR => RTCPeerConnectionState::Closed,
|
||||
_ => RTCPeerConnectionState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCPeerConnectionState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCPeerConnectionState::New,
|
||||
2 => RTCPeerConnectionState::Connecting,
|
||||
3 => RTCPeerConnectionState::Connected,
|
||||
4 => RTCPeerConnectionState::Disconnected,
|
||||
5 => RTCPeerConnectionState::Failed,
|
||||
6 => RTCPeerConnectionState::Closed,
|
||||
_ => RTCPeerConnectionState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCPeerConnectionState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCPeerConnectionState::New => PEER_CONNECTION_STATE_NEW_STR,
|
||||
RTCPeerConnectionState::Connecting => PEER_CONNECTION_STATE_CONNECTING_STR,
|
||||
RTCPeerConnectionState::Connected => PEER_CONNECTION_STATE_CONNECTED_STR,
|
||||
RTCPeerConnectionState::Disconnected => PEER_CONNECTION_STATE_DISCONNECTED_STR,
|
||||
RTCPeerConnectionState::Failed => PEER_CONNECTION_STATE_FAILED_STR,
|
||||
RTCPeerConnectionState::Closed => PEER_CONNECTION_STATE_CLOSED_STR,
|
||||
RTCPeerConnectionState::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum NegotiationNeededState {
|
||||
/// NegotiationNeededStateEmpty not running and queue is empty
|
||||
#[default]
|
||||
Empty,
|
||||
/// NegotiationNeededStateEmpty running and queue is empty
|
||||
Run,
|
||||
/// NegotiationNeededStateEmpty running and queue
|
||||
Queue,
|
||||
}
|
||||
|
||||
impl From<u8> for NegotiationNeededState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => NegotiationNeededState::Run,
|
||||
2 => NegotiationNeededState::Queue,
|
||||
_ => NegotiationNeededState::Empty,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_peer_connection_state() {
|
||||
let tests = vec![
|
||||
(crate::UNSPECIFIED_STR, RTCPeerConnectionState::Unspecified),
|
||||
("new", RTCPeerConnectionState::New),
|
||||
("connecting", RTCPeerConnectionState::Connecting),
|
||||
("connected", RTCPeerConnectionState::Connected),
|
||||
("disconnected", RTCPeerConnectionState::Disconnected),
|
||||
("failed", RTCPeerConnectionState::Failed),
|
||||
("closed", RTCPeerConnectionState::Closed),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(
|
||||
RTCPeerConnectionState::from(state_string),
|
||||
expected_state,
|
||||
"testCase: {expected_state}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_peer_connection_state_string() {
|
||||
let tests = vec![
|
||||
(RTCPeerConnectionState::Unspecified, crate::UNSPECIFIED_STR),
|
||||
(RTCPeerConnectionState::New, "new"),
|
||||
(RTCPeerConnectionState::Connecting, "connecting"),
|
||||
(RTCPeerConnectionState::Connected, "connected"),
|
||||
(RTCPeerConnectionState::Disconnected, "disconnected"),
|
||||
(RTCPeerConnectionState::Failed, "failed"),
|
||||
(RTCPeerConnectionState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,423 @@
|
||||
use std::sync::atomic::AtomicU32;
|
||||
use std::sync::Arc;
|
||||
|
||||
use bytes::Bytes;
|
||||
use interceptor::registry::Registry;
|
||||
use media::Sample;
|
||||
use tokio::time::Duration;
|
||||
use util::vnet::net::{Net, NetConfig};
|
||||
use util::vnet::router::{Router, RouterConfig};
|
||||
use waitgroup::WaitGroup;
|
||||
|
||||
use super::*;
|
||||
use crate::api::interceptor_registry::register_default_interceptors;
|
||||
use crate::api::media_engine::{MediaEngine, MIME_TYPE_VP8};
|
||||
use crate::api::APIBuilder;
|
||||
use crate::ice_transport::ice_candidate_pair::RTCIceCandidatePair;
|
||||
use crate::ice_transport::ice_server::RTCIceServer;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
use crate::rtp_transceiver::rtp_codec::RTCRtpCodecCapability;
|
||||
use crate::stats::StatsReportType;
|
||||
use crate::track::track_local::track_local_static_sample::TrackLocalStaticSample;
|
||||
use crate::Error;
|
||||
|
||||
pub(crate) async fn create_vnet_pair(
|
||||
) -> Result<(RTCPeerConnection, RTCPeerConnection, Arc<Mutex<Router>>)> {
|
||||
// Create a root router
|
||||
let wan = Arc::new(Mutex::new(Router::new(RouterConfig {
|
||||
cidr: "1.2.3.0/24".to_owned(),
|
||||
..Default::default()
|
||||
})?));
|
||||
|
||||
// Create a network interface for offerer
|
||||
let offer_vnet = Arc::new(Net::new(Some(NetConfig {
|
||||
static_ips: vec!["1.2.3.4".to_owned()],
|
||||
..Default::default()
|
||||
})));
|
||||
|
||||
// Add the network interface to the router
|
||||
let nic = offer_vnet.get_nic()?;
|
||||
{
|
||||
let mut w = wan.lock().await;
|
||||
w.add_net(Arc::clone(&nic)).await?;
|
||||
}
|
||||
{
|
||||
let n = nic.lock().await;
|
||||
n.set_router(Arc::clone(&wan)).await?;
|
||||
}
|
||||
|
||||
let mut offer_setting_engine = SettingEngine::default();
|
||||
offer_setting_engine.set_vnet(Some(offer_vnet));
|
||||
offer_setting_engine.set_ice_timeouts(
|
||||
Some(Duration::from_secs(1)),
|
||||
Some(Duration::from_secs(1)),
|
||||
Some(Duration::from_millis(200)),
|
||||
);
|
||||
|
||||
// Create a network interface for answerer
|
||||
let answer_vnet = Arc::new(Net::new(Some(NetConfig {
|
||||
static_ips: vec!["1.2.3.5".to_owned()],
|
||||
..Default::default()
|
||||
})));
|
||||
|
||||
// Add the network interface to the router
|
||||
let nic = answer_vnet.get_nic()?;
|
||||
{
|
||||
let mut w = wan.lock().await;
|
||||
w.add_net(Arc::clone(&nic)).await?;
|
||||
}
|
||||
{
|
||||
let n = nic.lock().await;
|
||||
n.set_router(Arc::clone(&wan)).await?;
|
||||
}
|
||||
|
||||
let mut answer_setting_engine = SettingEngine::default();
|
||||
answer_setting_engine.set_vnet(Some(answer_vnet));
|
||||
answer_setting_engine.set_ice_timeouts(
|
||||
Some(Duration::from_secs(1)),
|
||||
Some(Duration::from_secs(1)),
|
||||
Some(Duration::from_millis(200)),
|
||||
);
|
||||
|
||||
// Start the virtual network by calling Start() on the root router
|
||||
{
|
||||
let mut w = wan.lock().await;
|
||||
w.start().await?;
|
||||
}
|
||||
|
||||
let mut offer_media_engine = MediaEngine::default();
|
||||
offer_media_engine.register_default_codecs()?;
|
||||
let offer_peer_connection = APIBuilder::new()
|
||||
.with_setting_engine(offer_setting_engine)
|
||||
.with_media_engine(offer_media_engine)
|
||||
.build()
|
||||
.new_peer_connection(RTCConfiguration::default())
|
||||
.await?;
|
||||
|
||||
let mut answer_media_engine = MediaEngine::default();
|
||||
answer_media_engine.register_default_codecs()?;
|
||||
let answer_peer_connection = APIBuilder::new()
|
||||
.with_setting_engine(answer_setting_engine)
|
||||
.with_media_engine(answer_media_engine)
|
||||
.build()
|
||||
.new_peer_connection(RTCConfiguration::default())
|
||||
.await?;
|
||||
|
||||
Ok((offer_peer_connection, answer_peer_connection, wan))
|
||||
}
|
||||
|
||||
/// new_pair creates two new peer connections (an offerer and an answerer)
|
||||
/// *without* using an api (i.e. using the default settings).
|
||||
pub(crate) async fn new_pair(api: &API) -> Result<(RTCPeerConnection, RTCPeerConnection)> {
|
||||
let pca = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
let pcb = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
|
||||
Ok((pca, pcb))
|
||||
}
|
||||
|
||||
pub(crate) async fn signal_pair(
|
||||
pc_offer: &mut RTCPeerConnection,
|
||||
pc_answer: &mut RTCPeerConnection,
|
||||
) -> Result<()> {
|
||||
// Note(albrow): We need to create a data channel in order to trigger ICE
|
||||
// candidate gathering in the background for the JavaScript/Wasm bindings. If
|
||||
// we don't do this, the complete offer including ICE candidates will never be
|
||||
// generated.
|
||||
pc_offer
|
||||
.create_data_channel("initial_data_channel", None)
|
||||
.await?;
|
||||
|
||||
let offer = pc_offer.create_offer(None).await?;
|
||||
|
||||
let mut offer_gathering_complete = pc_offer.gathering_complete_promise().await;
|
||||
pc_offer.set_local_description(offer).await?;
|
||||
|
||||
let _ = offer_gathering_complete.recv().await;
|
||||
|
||||
pc_answer
|
||||
.set_remote_description(
|
||||
pc_offer
|
||||
.local_description()
|
||||
.await
|
||||
.ok_or(Error::new("non local description".to_owned()))?,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let answer = pc_answer.create_answer(None).await?;
|
||||
|
||||
let mut answer_gathering_complete = pc_answer.gathering_complete_promise().await;
|
||||
pc_answer.set_local_description(answer).await?;
|
||||
|
||||
let _ = answer_gathering_complete.recv().await;
|
||||
|
||||
pc_offer
|
||||
.set_remote_description(
|
||||
pc_answer
|
||||
.local_description()
|
||||
.await
|
||||
.ok_or(Error::new("non local description".to_owned()))?,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn close_pair_now(pc1: &RTCPeerConnection, pc2: &RTCPeerConnection) {
|
||||
let mut fail = false;
|
||||
if let Err(err) = pc1.close().await {
|
||||
log::error!("Failed to close PeerConnection: {}", err);
|
||||
fail = true;
|
||||
}
|
||||
if let Err(err) = pc2.close().await {
|
||||
log::error!("Failed to close PeerConnection: {}", err);
|
||||
fail = true;
|
||||
}
|
||||
|
||||
assert!(!fail);
|
||||
}
|
||||
|
||||
pub(crate) async fn close_pair(
|
||||
pc1: &RTCPeerConnection,
|
||||
pc2: &RTCPeerConnection,
|
||||
mut done_rx: mpsc::Receiver<()>,
|
||||
) {
|
||||
let timeout = tokio::time::sleep(Duration::from_secs(10));
|
||||
tokio::pin!(timeout);
|
||||
|
||||
tokio::select! {
|
||||
_ = timeout.as_mut() =>{
|
||||
panic!("close_pair timed out waiting for done signal");
|
||||
}
|
||||
_ = done_rx.recv() =>{
|
||||
close_pair_now(pc1, pc2).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
func offerMediaHasDirection(offer SessionDescription, kind RTPCodecType, direction RTPTransceiverDirection) bool {
|
||||
parsed := &sdp.SessionDescription{}
|
||||
if err := parsed.Unmarshal([]byte(offer.SDP)); err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
for _, media := range parsed.MediaDescriptions {
|
||||
if media.MediaName.Media == kind.String() {
|
||||
_, exists := media.Attribute(direction.String())
|
||||
return exists
|
||||
}
|
||||
}
|
||||
return false
|
||||
}*/
|
||||
|
||||
pub(crate) async fn send_video_until_done(
|
||||
mut done_rx: mpsc::Receiver<()>,
|
||||
tracks: Vec<Arc<TrackLocalStaticSample>>,
|
||||
data: Bytes,
|
||||
max_sends: Option<usize>,
|
||||
) -> bool {
|
||||
let mut sends = 0;
|
||||
|
||||
loop {
|
||||
let timeout = tokio::time::sleep(Duration::from_millis(20));
|
||||
tokio::pin!(timeout);
|
||||
|
||||
tokio::select! {
|
||||
biased;
|
||||
|
||||
_ = done_rx.recv() =>{
|
||||
log::debug!("sendVideoUntilDone received done");
|
||||
return false;
|
||||
}
|
||||
|
||||
_ = timeout.as_mut() =>{
|
||||
if max_sends.map(|s| sends >= s).unwrap_or(false) {
|
||||
continue;
|
||||
}
|
||||
|
||||
log::debug!("sendVideoUntilDone timeout");
|
||||
for track in &tracks {
|
||||
log::debug!("sendVideoUntilDone track.WriteSample");
|
||||
let result = track.write_sample(&Sample{
|
||||
data: data.clone(),
|
||||
duration: Duration::from_secs(1),
|
||||
..Default::default()
|
||||
}).await;
|
||||
assert!(result.is_ok());
|
||||
sends += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn until_connection_state(
|
||||
pc: &mut RTCPeerConnection,
|
||||
wg: &WaitGroup,
|
||||
state: RTCPeerConnectionState,
|
||||
) {
|
||||
let w = Arc::new(Mutex::new(Some(wg.worker())));
|
||||
pc.on_peer_connection_state_change(Box::new(move |pcs: RTCPeerConnectionState| {
|
||||
let w2 = Arc::clone(&w);
|
||||
Box::pin(async move {
|
||||
if pcs == state {
|
||||
let mut worker = w2.lock().await;
|
||||
worker.take();
|
||||
}
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_get_stats() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut pc_offer, mut pc_answer) = new_pair(&api).await?;
|
||||
|
||||
let (ice_complete_tx, mut ice_complete_rx) = mpsc::channel::<()>(1);
|
||||
let ice_complete_tx = Arc::new(Mutex::new(Some(ice_complete_tx)));
|
||||
pc_answer.on_ice_connection_state_change(Box::new(move |ice_state: RTCIceConnectionState| {
|
||||
let ice_complete_tx2 = Arc::clone(&ice_complete_tx);
|
||||
Box::pin(async move {
|
||||
if ice_state == RTCIceConnectionState::Connected {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let mut done = ice_complete_tx2.lock().await;
|
||||
done.take();
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
let sender_called_candidate_change = Arc::new(AtomicU32::new(0));
|
||||
let sender_called_candidate_change2 = Arc::clone(&sender_called_candidate_change);
|
||||
pc_offer
|
||||
.sctp()
|
||||
.transport()
|
||||
.ice_transport()
|
||||
.on_selected_candidate_pair_change(Box::new(move |_: RTCIceCandidatePair| {
|
||||
sender_called_candidate_change2.store(1, Ordering::SeqCst);
|
||||
Box::pin(async {})
|
||||
}));
|
||||
let track = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
pc_offer
|
||||
.add_track(track.clone())
|
||||
.await
|
||||
.expect("Failed to add track");
|
||||
let (packet_tx, packet_rx) = mpsc::channel(1);
|
||||
|
||||
pc_answer.on_track(Box::new(move |track, _, _| {
|
||||
let packet_tx = packet_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
while let Ok((pkt, _)) = track.read_rtp().await {
|
||||
dbg!(&pkt);
|
||||
let last = pkt.payload[pkt.payload.len() - 1];
|
||||
|
||||
if last == 0xAA {
|
||||
let _ = packet_tx.send(()).await;
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Box::pin(async move {})
|
||||
}));
|
||||
|
||||
signal_pair(&mut pc_offer, &mut pc_answer).await?;
|
||||
|
||||
let _ = ice_complete_rx.recv().await;
|
||||
send_video_until_done(
|
||||
packet_rx,
|
||||
vec![track],
|
||||
Bytes::from_static(b"\xDE\xAD\xBE\xEF\xAA"),
|
||||
Some(1),
|
||||
)
|
||||
.await;
|
||||
|
||||
let offer_stats = pc_offer.get_stats().await;
|
||||
assert!(!offer_stats.reports.is_empty());
|
||||
|
||||
match offer_stats.reports.get("ice_transport") {
|
||||
Some(StatsReportType::Transport(ice_transport_stats)) => {
|
||||
assert!(ice_transport_stats.bytes_received > 0);
|
||||
assert!(ice_transport_stats.bytes_sent > 0);
|
||||
}
|
||||
Some(_other) => panic!("found the wrong type"),
|
||||
None => panic!("missed it"),
|
||||
}
|
||||
let outbound_stats = offer_stats
|
||||
.reports
|
||||
.values()
|
||||
.find_map(|v| match v {
|
||||
StatsReportType::OutboundRTP(d) => Some(d),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Should have produced an RTP Outbound stat");
|
||||
assert_eq!(outbound_stats.packets_sent, 1);
|
||||
assert_eq!(outbound_stats.kind, "video");
|
||||
assert_eq!(outbound_stats.bytes_sent, 8);
|
||||
assert_eq!(outbound_stats.header_bytes_sent, 12);
|
||||
|
||||
let answer_stats = pc_answer.get_stats().await;
|
||||
let inbound_stats = answer_stats
|
||||
.reports
|
||||
.values()
|
||||
.find_map(|v| match v {
|
||||
StatsReportType::InboundRTP(d) => Some(d),
|
||||
_ => None,
|
||||
})
|
||||
.expect("Should have produced an RTP inbound stat");
|
||||
assert_eq!(inbound_stats.packets_received, 1);
|
||||
assert_eq!(inbound_stats.kind, "video");
|
||||
assert_eq!(inbound_stats.bytes_received, 8);
|
||||
assert_eq!(inbound_stats.header_bytes_received, 12);
|
||||
|
||||
close_pair_now(&pc_offer, &pc_answer).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_peer_connection_close_is_send() -> Result<()> {
|
||||
let handle = tokio::spawn(async move { peer().await });
|
||||
tokio::join!(handle).0.unwrap()
|
||||
}
|
||||
|
||||
async fn peer() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let mut registry = Registry::new();
|
||||
registry = register_default_interceptors(registry, &mut m)?;
|
||||
let api = APIBuilder::new()
|
||||
.with_media_engine(m)
|
||||
.with_interceptor_registry(registry)
|
||||
.build();
|
||||
|
||||
let config = RTCConfiguration {
|
||||
ice_servers: vec![RTCIceServer {
|
||||
urls: vec!["stun:stun.l.google.com:19302".to_owned()],
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let peer_connection = Arc::new(api.new_peer_connection(config).await?);
|
||||
|
||||
let offer = peer_connection.create_offer(None).await?;
|
||||
let mut gather_complete = peer_connection.gathering_complete_promise().await;
|
||||
peer_connection.set_local_description(offer).await?;
|
||||
let _ = gather_complete.recv().await;
|
||||
|
||||
if peer_connection.local_description().await.is_some() {
|
||||
//TODO?
|
||||
}
|
||||
|
||||
peer_connection.close().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// BundlePolicy affects which media tracks are negotiated if the remote
|
||||
/// endpoint is not bundle-aware, and what ICE candidates are gathered. If the
|
||||
/// remote endpoint is bundle-aware, all media tracks and data channels are
|
||||
/// bundled onto the same transport.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum RTCBundlePolicy {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// BundlePolicyBalanced indicates to gather ICE candidates for each
|
||||
/// media type in use (audio, video, and data). If the remote endpoint is
|
||||
/// not bundle-aware, negotiate only one audio and video track on separate
|
||||
/// transports.
|
||||
#[serde(rename = "balanced")]
|
||||
Balanced = 1,
|
||||
|
||||
/// BundlePolicyMaxCompat indicates to gather ICE candidates for each
|
||||
/// track. If the remote endpoint is not bundle-aware, negotiate all media
|
||||
/// tracks on separate transports.
|
||||
#[serde(rename = "max-compat")]
|
||||
MaxCompat = 2,
|
||||
|
||||
/// BundlePolicyMaxBundle indicates to gather ICE candidates for only
|
||||
/// one track. If the remote endpoint is not bundle-aware, negotiate only
|
||||
/// one media track.
|
||||
#[serde(rename = "max-bundle")]
|
||||
MaxBundle = 3,
|
||||
}
|
||||
|
||||
/// This is done this way because of a linter.
|
||||
const BUNDLE_POLICY_BALANCED_STR: &str = "balanced";
|
||||
const BUNDLE_POLICY_MAX_COMPAT_STR: &str = "max-compat";
|
||||
const BUNDLE_POLICY_MAX_BUNDLE_STR: &str = "max-bundle";
|
||||
|
||||
impl From<&str> for RTCBundlePolicy {
|
||||
/// NewSchemeType defines a procedure for creating a new SchemeType from a raw
|
||||
/// string naming the scheme type.
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
BUNDLE_POLICY_BALANCED_STR => RTCBundlePolicy::Balanced,
|
||||
BUNDLE_POLICY_MAX_COMPAT_STR => RTCBundlePolicy::MaxCompat,
|
||||
BUNDLE_POLICY_MAX_BUNDLE_STR => RTCBundlePolicy::MaxBundle,
|
||||
_ => RTCBundlePolicy::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCBundlePolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCBundlePolicy::Balanced => write!(f, "{BUNDLE_POLICY_BALANCED_STR}"),
|
||||
RTCBundlePolicy::MaxCompat => write!(f, "{BUNDLE_POLICY_MAX_COMPAT_STR}"),
|
||||
RTCBundlePolicy::MaxBundle => write!(f, "{BUNDLE_POLICY_MAX_BUNDLE_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_bundle_policy() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCBundlePolicy::Unspecified),
|
||||
("balanced", RTCBundlePolicy::Balanced),
|
||||
("max-compat", RTCBundlePolicy::MaxCompat),
|
||||
("max-bundle", RTCBundlePolicy::MaxBundle),
|
||||
];
|
||||
|
||||
for (policy_string, expected_policy) in tests {
|
||||
assert_eq!(RTCBundlePolicy::from(policy_string), expected_policy);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_bundle_policy_string() {
|
||||
let tests = vec![
|
||||
(RTCBundlePolicy::Unspecified, "Unspecified"),
|
||||
(RTCBundlePolicy::Balanced, "balanced"),
|
||||
(RTCBundlePolicy::MaxCompat, "max-compat"),
|
||||
(RTCBundlePolicy::MaxBundle, "max-bundle"),
|
||||
];
|
||||
|
||||
for (policy, expected_string) in tests {
|
||||
assert_eq!(policy.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// ICETransportPolicy defines the ICE candidate policy surface the
|
||||
/// permitted candidates. Only these candidates are used for connectivity checks.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum RTCIceTransportPolicy {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// ICETransportPolicyAll indicates any type of candidate is used.
|
||||
#[serde(rename = "all")]
|
||||
All = 1,
|
||||
|
||||
/// ICETransportPolicyRelay indicates only media relay candidates such
|
||||
/// as candidates passing through a TURN server are used.
|
||||
#[serde(rename = "relay")]
|
||||
Relay = 2,
|
||||
}
|
||||
|
||||
/// ICEGatherPolicy is the ORTC equivalent of ICETransportPolicy
|
||||
pub type ICEGatherPolicy = RTCIceTransportPolicy;
|
||||
|
||||
const ICE_TRANSPORT_POLICY_RELAY_STR: &str = "relay";
|
||||
const ICE_TRANSPORT_POLICY_ALL_STR: &str = "all";
|
||||
|
||||
/// takes a string and converts it to ICETransportPolicy
|
||||
impl From<&str> for RTCIceTransportPolicy {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
ICE_TRANSPORT_POLICY_RELAY_STR => RTCIceTransportPolicy::Relay,
|
||||
ICE_TRANSPORT_POLICY_ALL_STR => RTCIceTransportPolicy::All,
|
||||
_ => RTCIceTransportPolicy::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCIceTransportPolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCIceTransportPolicy::Relay => ICE_TRANSPORT_POLICY_RELAY_STR,
|
||||
RTCIceTransportPolicy::All => ICE_TRANSPORT_POLICY_ALL_STR,
|
||||
RTCIceTransportPolicy::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_ice_transport_policy() {
|
||||
let tests = vec![
|
||||
("relay", RTCIceTransportPolicy::Relay),
|
||||
("all", RTCIceTransportPolicy::All),
|
||||
];
|
||||
|
||||
for (policy_string, expected_policy) in tests {
|
||||
assert_eq!(RTCIceTransportPolicy::from(policy_string), expected_policy);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_ice_transport_policy_string() {
|
||||
let tests = vec![
|
||||
(RTCIceTransportPolicy::Relay, "relay"),
|
||||
(RTCIceTransportPolicy::All, "all"),
|
||||
];
|
||||
|
||||
for (policy, expected_string) in tests {
|
||||
assert_eq!(policy.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
pub mod bundle_policy;
|
||||
pub mod ice_transport_policy;
|
||||
pub mod rtcp_mux_policy;
|
||||
pub mod sdp_semantics;
|
||||
@@ -0,0 +1,79 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// RTCPMuxPolicy affects what ICE candidates are gathered to support
|
||||
/// non-multiplexed RTCP.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum RTCRtcpMuxPolicy {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// RTCPMuxPolicyNegotiate indicates to gather ICE candidates for both
|
||||
/// RTP and RTCP candidates. If the remote-endpoint is capable of
|
||||
/// multiplexing RTCP, multiplex RTCP on the RTP candidates. If it is not,
|
||||
/// use both the RTP and RTCP candidates separately.
|
||||
#[serde(rename = "negotiate")]
|
||||
Negotiate = 1,
|
||||
|
||||
/// RTCPMuxPolicyRequire indicates to gather ICE candidates only for
|
||||
/// RTP and multiplex RTCP on the RTP candidates. If the remote endpoint is
|
||||
/// not capable of rtcp-mux, session negotiation will fail.
|
||||
#[serde(rename = "require")]
|
||||
Require = 2,
|
||||
}
|
||||
|
||||
const RTCP_MUX_POLICY_NEGOTIATE_STR: &str = "negotiate";
|
||||
const RTCP_MUX_POLICY_REQUIRE_STR: &str = "require";
|
||||
|
||||
impl From<&str> for RTCRtcpMuxPolicy {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
RTCP_MUX_POLICY_NEGOTIATE_STR => RTCRtcpMuxPolicy::Negotiate,
|
||||
RTCP_MUX_POLICY_REQUIRE_STR => RTCRtcpMuxPolicy::Require,
|
||||
_ => RTCRtcpMuxPolicy::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCRtcpMuxPolicy {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCRtcpMuxPolicy::Negotiate => RTCP_MUX_POLICY_NEGOTIATE_STR,
|
||||
RTCRtcpMuxPolicy::Require => RTCP_MUX_POLICY_REQUIRE_STR,
|
||||
RTCRtcpMuxPolicy::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_rtcp_mux_policy() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCRtcpMuxPolicy::Unspecified),
|
||||
("negotiate", RTCRtcpMuxPolicy::Negotiate),
|
||||
("require", RTCRtcpMuxPolicy::Require),
|
||||
];
|
||||
|
||||
for (policy_string, expected_policy) in tests {
|
||||
assert_eq!(RTCRtcpMuxPolicy::from(policy_string), expected_policy);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtcp_mux_policy_string() {
|
||||
let tests = vec![
|
||||
(RTCRtcpMuxPolicy::Unspecified, "Unspecified"),
|
||||
(RTCRtcpMuxPolicy::Negotiate, "negotiate"),
|
||||
(RTCRtcpMuxPolicy::Require, "require"),
|
||||
];
|
||||
|
||||
for (policy, expected_string) in tests {
|
||||
assert_eq!(policy.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// SDPSemantics determines which style of SDP offers and answers
|
||||
/// can be used.
|
||||
///
|
||||
/// This is unused, we only support UnifiedPlan.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum RTCSdpSemantics {
|
||||
Unspecified = 0,
|
||||
|
||||
/// UnifiedPlan uses unified-plan offers and answers
|
||||
/// (the default in Chrome since M72)
|
||||
/// <https://tools.ietf.org/html/draft-roach-mmusic-unified-plan-00>
|
||||
#[serde(rename = "unified-plan")]
|
||||
#[default]
|
||||
UnifiedPlan = 1,
|
||||
|
||||
/// PlanB uses plan-b offers and answers
|
||||
/// NB: This format should be considered deprecated
|
||||
/// <https://tools.ietf.org/html/draft-uberti-rtcweb-plan-00>
|
||||
#[serde(rename = "plan-b")]
|
||||
PlanB = 2,
|
||||
|
||||
/// UnifiedPlanWithFallback prefers unified-plan
|
||||
/// offers and answers, but will respond to a plan-b offer
|
||||
/// with a plan-b answer
|
||||
#[serde(rename = "unified-plan-with-fallback")]
|
||||
UnifiedPlanWithFallback = 3,
|
||||
}
|
||||
|
||||
const SDP_SEMANTICS_UNIFIED_PLAN_WITH_FALLBACK: &str = "unified-plan-with-fallback";
|
||||
const SDP_SEMANTICS_UNIFIED_PLAN: &str = "unified-plan";
|
||||
const SDP_SEMANTICS_PLAN_B: &str = "plan-b";
|
||||
|
||||
impl From<&str> for RTCSdpSemantics {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
SDP_SEMANTICS_UNIFIED_PLAN_WITH_FALLBACK => RTCSdpSemantics::UnifiedPlanWithFallback,
|
||||
SDP_SEMANTICS_UNIFIED_PLAN => RTCSdpSemantics::UnifiedPlan,
|
||||
SDP_SEMANTICS_PLAN_B => RTCSdpSemantics::PlanB,
|
||||
_ => RTCSdpSemantics::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCSdpSemantics {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCSdpSemantics::UnifiedPlanWithFallback => SDP_SEMANTICS_UNIFIED_PLAN_WITH_FALLBACK,
|
||||
RTCSdpSemantics::UnifiedPlan => SDP_SEMANTICS_UNIFIED_PLAN,
|
||||
RTCSdpSemantics::PlanB => SDP_SEMANTICS_PLAN_B,
|
||||
RTCSdpSemantics::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use std::collections::HashSet;
|
||||
|
||||
use sdp::description::media::MediaDescription;
|
||||
use sdp::description::session::{SessionDescription, ATTR_KEY_SSRC};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_sdp_semantics_string() {
|
||||
let tests = vec![
|
||||
(RTCSdpSemantics::Unspecified, "Unspecified"),
|
||||
(
|
||||
RTCSdpSemantics::UnifiedPlanWithFallback,
|
||||
"unified-plan-with-fallback",
|
||||
),
|
||||
(RTCSdpSemantics::PlanB, "plan-b"),
|
||||
(RTCSdpSemantics::UnifiedPlan, "unified-plan"),
|
||||
];
|
||||
|
||||
for (value, expected_string) in tests {
|
||||
assert_eq!(value.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
|
||||
// The following tests are for non-standard SDP semantics
|
||||
// (i.e. not unified-unified)
|
||||
fn get_md_names(sdp: &SessionDescription) -> Vec<String> {
|
||||
sdp.media_descriptions
|
||||
.iter()
|
||||
.map(|md| md.media_name.media.clone())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn extract_ssrc_list(md: &MediaDescription) -> Vec<String> {
|
||||
let mut ssrcs = HashSet::new();
|
||||
for attr in &md.attributes {
|
||||
if attr.key == ATTR_KEY_SSRC {
|
||||
if let Some(value) = &attr.value {
|
||||
let fields: Vec<&str> = value.split_whitespace().collect();
|
||||
if let Some(ssrc) = fields.first() {
|
||||
ssrcs.insert(*ssrc);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ssrcs
|
||||
.into_iter()
|
||||
.map(|ssrc| ssrc.to_owned())
|
||||
.collect::<Vec<String>>()
|
||||
}
|
||||
}
|
||||
+1096
File diff suppressed because it is too large.
Load diff
+1150
File diff suppressed because it is too large.
Load diff
+101
@@ -0,0 +1,101 @@
|
||||
use std::fmt;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// SDPType describes the type of an SessionDescription.
|
||||
#[derive(Default, Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
|
||||
pub enum RTCSdpType {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// indicates that a description MUST be treated as an SDP offer.
|
||||
#[serde(rename = "offer")]
|
||||
Offer,
|
||||
|
||||
/// indicates that a description MUST be treated as an
|
||||
/// SDP answer, but not a final answer. A description used as an SDP
|
||||
/// pranswer may be applied as a response to an SDP offer, or an update to
|
||||
/// a previously sent SDP pranswer.
|
||||
#[serde(rename = "pranswer")]
|
||||
Pranswer,
|
||||
|
||||
/// indicates that a description MUST be treated as an SDP
|
||||
/// final answer, and the offer-answer exchange MUST be considered complete.
|
||||
/// A description used as an SDP answer may be applied as a response to an
|
||||
/// SDP offer or as an update to a previously sent SDP pranswer.
|
||||
#[serde(rename = "answer")]
|
||||
Answer,
|
||||
|
||||
/// indicates that a description MUST be treated as
|
||||
/// canceling the current SDP negotiation and moving the SDP offer and
|
||||
/// answer back to what it was in the previous stable state. Note the
|
||||
/// local or remote SDP descriptions in the previous stable state could be
|
||||
/// null if there has not yet been a successful offer-answer negotiation.
|
||||
#[serde(rename = "rollback")]
|
||||
Rollback,
|
||||
}
|
||||
|
||||
const SDP_TYPE_OFFER_STR: &str = "offer";
|
||||
const SDP_TYPE_PRANSWER_STR: &str = "pranswer";
|
||||
const SDP_TYPE_ANSWER_STR: &str = "answer";
|
||||
const SDP_TYPE_ROLLBACK_STR: &str = "rollback";
|
||||
|
||||
/// creates an SDPType from a string
|
||||
impl From<&str> for RTCSdpType {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
SDP_TYPE_OFFER_STR => RTCSdpType::Offer,
|
||||
SDP_TYPE_PRANSWER_STR => RTCSdpType::Pranswer,
|
||||
SDP_TYPE_ANSWER_STR => RTCSdpType::Answer,
|
||||
SDP_TYPE_ROLLBACK_STR => RTCSdpType::Rollback,
|
||||
_ => RTCSdpType::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCSdpType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCSdpType::Offer => write!(f, "{SDP_TYPE_OFFER_STR}"),
|
||||
RTCSdpType::Pranswer => write!(f, "{SDP_TYPE_PRANSWER_STR}"),
|
||||
RTCSdpType::Answer => write!(f, "{SDP_TYPE_ANSWER_STR}"),
|
||||
RTCSdpType::Rollback => write!(f, "{SDP_TYPE_ROLLBACK_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_sdp_type() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCSdpType::Unspecified),
|
||||
("offer", RTCSdpType::Offer),
|
||||
("pranswer", RTCSdpType::Pranswer),
|
||||
("answer", RTCSdpType::Answer),
|
||||
("rollback", RTCSdpType::Rollback),
|
||||
];
|
||||
|
||||
for (sdp_type_string, expected_sdp_type) in tests {
|
||||
assert_eq!(RTCSdpType::from(sdp_type_string), expected_sdp_type);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sdp_type_string() {
|
||||
let tests = vec![
|
||||
(RTCSdpType::Unspecified, "Unspecified"),
|
||||
(RTCSdpType::Offer, "offer"),
|
||||
(RTCSdpType::Pranswer, "pranswer"),
|
||||
(RTCSdpType::Answer, "answer"),
|
||||
(RTCSdpType::Rollback, "rollback"),
|
||||
];
|
||||
|
||||
for (sdp_type, expected_string) in tests {
|
||||
assert_eq!(sdp_type.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
use std::io::Cursor;
|
||||
|
||||
use sdp::description::session::SessionDescription;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::sdp_type::RTCSdpType;
|
||||
use crate::error::Result;
|
||||
|
||||
/// SessionDescription is used to expose local and remote session descriptions.
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RTCSessionDescription {
|
||||
#[serde(rename = "type")]
|
||||
pub sdp_type: RTCSdpType,
|
||||
|
||||
pub sdp: String,
|
||||
|
||||
/// This will never be initialized by callers, internal use only
|
||||
#[serde(skip)]
|
||||
pub(crate) parsed: Option<SessionDescription>,
|
||||
}
|
||||
|
||||
impl RTCSessionDescription {
|
||||
/// Given SDP representing an answer, wrap it in an RTCSessionDescription
|
||||
/// that can be given to an RTCPeerConnection.
|
||||
pub fn answer(sdp: String) -> Result<RTCSessionDescription> {
|
||||
let mut desc = RTCSessionDescription {
|
||||
sdp,
|
||||
sdp_type: RTCSdpType::Answer,
|
||||
parsed: None,
|
||||
};
|
||||
|
||||
let parsed = desc.unmarshal()?;
|
||||
desc.parsed = Some(parsed);
|
||||
|
||||
Ok(desc)
|
||||
}
|
||||
|
||||
/// Given SDP representing an offer, wrap it in an RTCSessionDescription
|
||||
/// that can be given to an RTCPeerConnection.
|
||||
pub fn offer(sdp: String) -> Result<RTCSessionDescription> {
|
||||
let mut desc = RTCSessionDescription {
|
||||
sdp,
|
||||
sdp_type: RTCSdpType::Offer,
|
||||
parsed: None,
|
||||
};
|
||||
|
||||
let parsed = desc.unmarshal()?;
|
||||
desc.parsed = Some(parsed);
|
||||
|
||||
Ok(desc)
|
||||
}
|
||||
|
||||
/// Given SDP representing an answer, wrap it in an RTCSessionDescription
|
||||
/// that can be given to an RTCPeerConnection. `pranswer` is used when the
|
||||
/// answer may not be final, or when updating a previously sent pranswer.
|
||||
pub fn pranswer(sdp: String) -> Result<RTCSessionDescription> {
|
||||
let mut desc = RTCSessionDescription {
|
||||
sdp,
|
||||
sdp_type: RTCSdpType::Pranswer,
|
||||
parsed: None,
|
||||
};
|
||||
|
||||
let parsed = desc.unmarshal()?;
|
||||
desc.parsed = Some(parsed);
|
||||
|
||||
Ok(desc)
|
||||
}
|
||||
|
||||
/// Unmarshal is a helper to deserialize the sdp
|
||||
pub fn unmarshal(&self) -> Result<SessionDescription> {
|
||||
let mut reader = Cursor::new(self.sdp.as_bytes());
|
||||
let parsed = SessionDescription::unmarshal(&mut reader)?;
|
||||
Ok(parsed)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
|
||||
#[test]
|
||||
fn test_session_description_json() {
|
||||
let tests = vec![
|
||||
(
|
||||
RTCSessionDescription {
|
||||
sdp_type: RTCSdpType::Offer,
|
||||
sdp: "sdp".to_owned(),
|
||||
parsed: None,
|
||||
},
|
||||
r#"{"type":"offer","sdp":"sdp"}"#,
|
||||
),
|
||||
(
|
||||
RTCSessionDescription {
|
||||
sdp_type: RTCSdpType::Pranswer,
|
||||
sdp: "sdp".to_owned(),
|
||||
parsed: None,
|
||||
},
|
||||
r#"{"type":"pranswer","sdp":"sdp"}"#,
|
||||
),
|
||||
(
|
||||
RTCSessionDescription {
|
||||
sdp_type: RTCSdpType::Answer,
|
||||
sdp: "sdp".to_owned(),
|
||||
parsed: None,
|
||||
},
|
||||
r#"{"type":"answer","sdp":"sdp"}"#,
|
||||
),
|
||||
(
|
||||
RTCSessionDescription {
|
||||
sdp_type: RTCSdpType::Rollback,
|
||||
sdp: "sdp".to_owned(),
|
||||
parsed: None,
|
||||
},
|
||||
r#"{"type":"rollback","sdp":"sdp"}"#,
|
||||
),
|
||||
(
|
||||
RTCSessionDescription {
|
||||
sdp_type: RTCSdpType::Unspecified,
|
||||
sdp: "sdp".to_owned(),
|
||||
parsed: None,
|
||||
},
|
||||
r#"{"type":"Unspecified","sdp":"sdp"}"#,
|
||||
),
|
||||
];
|
||||
|
||||
for (desc, expected_string) in tests {
|
||||
let result = serde_json::to_string(&desc);
|
||||
assert!(result.is_ok(), "testCase: marshal err: {result:?}");
|
||||
let desc_data = result.unwrap();
|
||||
assert_eq!(desc_data, expected_string, "string is not expected");
|
||||
|
||||
let result = serde_json::from_str::<RTCSessionDescription>(&desc_data);
|
||||
assert!(result.is_ok(), "testCase: unmarshal err: {result:?}");
|
||||
if let Ok(sd) = result {
|
||||
assert!(sd.sdp == desc.sdp && sd.sdp_type == desc.sdp_type);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_description_answer() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let offer_pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
let answer_pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
|
||||
let _ = offer_pc.create_data_channel("foo", None).await?;
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
|
||||
let desc = RTCSessionDescription::answer(answer.sdp.clone())?;
|
||||
|
||||
assert!(desc.sdp_type == RTCSdpType::Answer);
|
||||
assert!(desc.parsed.is_some());
|
||||
|
||||
assert_eq!(answer.unmarshal()?.marshal(), desc.unmarshal()?.marshal());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_description_offer() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
let offer = pc.create_offer(None).await?;
|
||||
|
||||
let desc = RTCSessionDescription::offer(offer.sdp.clone())?;
|
||||
|
||||
assert!(desc.sdp_type == RTCSdpType::Offer);
|
||||
assert!(desc.parsed.is_some());
|
||||
|
||||
assert_eq!(offer.unmarshal()?.marshal(), desc.unmarshal()?.marshal());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_description_pranswer() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let offer_pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
let answer_pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
|
||||
let _ = offer_pc.create_data_channel("foo", None).await?;
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
|
||||
let desc = RTCSessionDescription::pranswer(answer.sdp)?;
|
||||
|
||||
assert!(desc.sdp_type == RTCSdpType::Pranswer);
|
||||
assert!(desc.parsed.is_some());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_description_unmarshal() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
|
||||
let offer = pc.create_offer(None).await?;
|
||||
|
||||
let desc = RTCSessionDescription {
|
||||
sdp_type: offer.sdp_type,
|
||||
sdp: offer.sdp,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(desc.parsed.is_none());
|
||||
|
||||
let parsed1 = desc.unmarshal()?;
|
||||
let parsed2 = desc.unmarshal()?;
|
||||
|
||||
pc.close().await?;
|
||||
|
||||
// check if the two parsed results _really_ match, could be affected by internal caching
|
||||
assert_eq!(parsed1.marshal(), parsed2.marshal());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
use std::fmt;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::peer_connection::sdp::sdp_type::RTCSdpType;
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum StateChangeOp {
|
||||
#[default]
|
||||
SetLocal,
|
||||
SetRemote,
|
||||
}
|
||||
|
||||
impl fmt::Display for StateChangeOp {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
StateChangeOp::SetLocal => write!(f, "SetLocal"),
|
||||
StateChangeOp::SetRemote => write!(f, "SetRemote"),
|
||||
//_ => write!(f, UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// SignalingState indicates the signaling state of the offer/answer process.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCSignalingState {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// SignalingStateStable indicates there is no offer/answer exchange in
|
||||
/// progress. This is also the initial state, in which case the local and
|
||||
/// remote descriptions are nil.
|
||||
Stable,
|
||||
|
||||
/// SignalingStateHaveLocalOffer indicates that a local description, of
|
||||
/// type "offer", has been successfully applied.
|
||||
HaveLocalOffer,
|
||||
|
||||
/// SignalingStateHaveRemoteOffer indicates that a remote description, of
|
||||
/// type "offer", has been successfully applied.
|
||||
HaveRemoteOffer,
|
||||
|
||||
/// SignalingStateHaveLocalPranswer indicates that a remote description
|
||||
/// of type "offer" has been successfully applied and a local description
|
||||
/// of type "pranswer" has been successfully applied.
|
||||
HaveLocalPranswer,
|
||||
|
||||
/// SignalingStateHaveRemotePranswer indicates that a local description
|
||||
/// of type "offer" has been successfully applied and a remote description
|
||||
/// of type "pranswer" has been successfully applied.
|
||||
HaveRemotePranswer,
|
||||
|
||||
/// SignalingStateClosed indicates The PeerConnection has been closed.
|
||||
Closed,
|
||||
}
|
||||
|
||||
const SIGNALING_STATE_STABLE_STR: &str = "stable";
|
||||
const SIGNALING_STATE_HAVE_LOCAL_OFFER_STR: &str = "have-local-offer";
|
||||
const SIGNALING_STATE_HAVE_REMOTE_OFFER_STR: &str = "have-remote-offer";
|
||||
const SIGNALING_STATE_HAVE_LOCAL_PRANSWER_STR: &str = "have-local-pranswer";
|
||||
const SIGNALING_STATE_HAVE_REMOTE_PRANSWER_STR: &str = "have-remote-pranswer";
|
||||
const SIGNALING_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
impl From<&str> for RTCSignalingState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
SIGNALING_STATE_STABLE_STR => RTCSignalingState::Stable,
|
||||
SIGNALING_STATE_HAVE_LOCAL_OFFER_STR => RTCSignalingState::HaveLocalOffer,
|
||||
SIGNALING_STATE_HAVE_REMOTE_OFFER_STR => RTCSignalingState::HaveRemoteOffer,
|
||||
SIGNALING_STATE_HAVE_LOCAL_PRANSWER_STR => RTCSignalingState::HaveLocalPranswer,
|
||||
SIGNALING_STATE_HAVE_REMOTE_PRANSWER_STR => RTCSignalingState::HaveRemotePranswer,
|
||||
SIGNALING_STATE_CLOSED_STR => RTCSignalingState::Closed,
|
||||
_ => RTCSignalingState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCSignalingState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCSignalingState::Stable => write!(f, "{SIGNALING_STATE_STABLE_STR}"),
|
||||
RTCSignalingState::HaveLocalOffer => {
|
||||
write!(f, "{SIGNALING_STATE_HAVE_LOCAL_OFFER_STR}")
|
||||
}
|
||||
RTCSignalingState::HaveRemoteOffer => {
|
||||
write!(f, "{SIGNALING_STATE_HAVE_REMOTE_OFFER_STR}")
|
||||
}
|
||||
RTCSignalingState::HaveLocalPranswer => {
|
||||
write!(f, "{SIGNALING_STATE_HAVE_LOCAL_PRANSWER_STR}")
|
||||
}
|
||||
RTCSignalingState::HaveRemotePranswer => {
|
||||
write!(f, "{SIGNALING_STATE_HAVE_REMOTE_PRANSWER_STR}")
|
||||
}
|
||||
RTCSignalingState::Closed => write!(f, "{SIGNALING_STATE_CLOSED_STR}"),
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCSignalingState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCSignalingState::Stable,
|
||||
2 => RTCSignalingState::HaveLocalOffer,
|
||||
3 => RTCSignalingState::HaveRemoteOffer,
|
||||
4 => RTCSignalingState::HaveLocalPranswer,
|
||||
5 => RTCSignalingState::HaveRemotePranswer,
|
||||
6 => RTCSignalingState::Closed,
|
||||
_ => RTCSignalingState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn check_next_signaling_state(
|
||||
cur: RTCSignalingState,
|
||||
next: RTCSignalingState,
|
||||
op: StateChangeOp,
|
||||
sdp_type: RTCSdpType,
|
||||
) -> Result<RTCSignalingState> {
|
||||
// Special case for rollbacks
|
||||
if sdp_type == RTCSdpType::Rollback && cur == RTCSignalingState::Stable {
|
||||
return Err(Error::ErrSignalingStateCannotRollback);
|
||||
}
|
||||
|
||||
// 4.3.1 valid state transitions
|
||||
match cur {
|
||||
RTCSignalingState::Stable => {
|
||||
match op {
|
||||
StateChangeOp::SetLocal => {
|
||||
// stable->SetLocal(offer)->have-local-offer
|
||||
if sdp_type == RTCSdpType::Offer && next == RTCSignalingState::HaveLocalOffer {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
StateChangeOp::SetRemote => {
|
||||
// stable->SetRemote(offer)->have-remote-offer
|
||||
if sdp_type == RTCSdpType::Offer && next == RTCSignalingState::HaveRemoteOffer {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
RTCSignalingState::HaveLocalOffer => {
|
||||
if op == StateChangeOp::SetRemote {
|
||||
match sdp_type {
|
||||
// have-local-offer->SetRemote(answer)->stable
|
||||
RTCSdpType::Answer => {
|
||||
if next == RTCSignalingState::Stable {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
// have-local-offer->SetRemote(pranswer)->have-remote-pranswer
|
||||
RTCSdpType::Pranswer => {
|
||||
if next == RTCSignalingState::HaveRemotePranswer {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
} else if op == StateChangeOp::SetLocal
|
||||
&& sdp_type == RTCSdpType::Offer
|
||||
&& next == RTCSignalingState::HaveLocalOffer
|
||||
{
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
RTCSignalingState::HaveRemotePranswer => {
|
||||
if op == StateChangeOp::SetRemote && sdp_type == RTCSdpType::Answer {
|
||||
// have-remote-pranswer->SetRemote(answer)->stable
|
||||
if next == RTCSignalingState::Stable {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
RTCSignalingState::HaveRemoteOffer => {
|
||||
if op == StateChangeOp::SetLocal {
|
||||
match sdp_type {
|
||||
// have-remote-offer->SetLocal(answer)->stable
|
||||
RTCSdpType::Answer => {
|
||||
if next == RTCSignalingState::Stable {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
// have-remote-offer->SetLocal(pranswer)->have-local-pranswer
|
||||
RTCSdpType::Pranswer => {
|
||||
if next == RTCSignalingState::HaveLocalPranswer {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
RTCSignalingState::HaveLocalPranswer => {
|
||||
if op == StateChangeOp::SetLocal && sdp_type == RTCSdpType::Answer {
|
||||
// have-local-pranswer->SetLocal(answer)->stable
|
||||
if next == RTCSignalingState::Stable {
|
||||
return Ok(next);
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
return Err(Error::ErrSignalingStateProposedTransitionInvalid {
|
||||
from: cur,
|
||||
applying: sdp_type,
|
||||
is_local: op == StateChangeOp::SetLocal,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
Err(Error::ErrSignalingStateProposedTransitionInvalid {
|
||||
from: cur,
|
||||
is_local: op == StateChangeOp::SetLocal,
|
||||
applying: sdp_type,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_signaling_state() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCSignalingState::Unspecified),
|
||||
("stable", RTCSignalingState::Stable),
|
||||
("have-local-offer", RTCSignalingState::HaveLocalOffer),
|
||||
("have-remote-offer", RTCSignalingState::HaveRemoteOffer),
|
||||
("have-local-pranswer", RTCSignalingState::HaveLocalPranswer),
|
||||
(
|
||||
"have-remote-pranswer",
|
||||
RTCSignalingState::HaveRemotePranswer,
|
||||
),
|
||||
("closed", RTCSignalingState::Closed),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(RTCSignalingState::from(state_string), expected_state);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_signaling_state_string() {
|
||||
let tests = vec![
|
||||
(RTCSignalingState::Unspecified, "Unspecified"),
|
||||
(RTCSignalingState::Stable, "stable"),
|
||||
(RTCSignalingState::HaveLocalOffer, "have-local-offer"),
|
||||
(RTCSignalingState::HaveRemoteOffer, "have-remote-offer"),
|
||||
(RTCSignalingState::HaveLocalPranswer, "have-local-pranswer"),
|
||||
(
|
||||
RTCSignalingState::HaveRemotePranswer,
|
||||
"have-remote-pranswer",
|
||||
),
|
||||
(RTCSignalingState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_signaling_state_transitions() {
|
||||
let tests = vec![
|
||||
(
|
||||
"stable->SetLocal(offer)->have-local-offer",
|
||||
RTCSignalingState::Stable,
|
||||
RTCSignalingState::HaveLocalOffer,
|
||||
StateChangeOp::SetLocal,
|
||||
RTCSdpType::Offer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"stable->SetRemote(offer)->have-remote-offer",
|
||||
RTCSignalingState::Stable,
|
||||
RTCSignalingState::HaveRemoteOffer,
|
||||
StateChangeOp::SetRemote,
|
||||
RTCSdpType::Offer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"have-local-offer->SetRemote(answer)->stable",
|
||||
RTCSignalingState::HaveLocalOffer,
|
||||
RTCSignalingState::Stable,
|
||||
StateChangeOp::SetRemote,
|
||||
RTCSdpType::Answer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"have-local-offer->SetRemote(pranswer)->have-remote-pranswer",
|
||||
RTCSignalingState::HaveLocalOffer,
|
||||
RTCSignalingState::HaveRemotePranswer,
|
||||
StateChangeOp::SetRemote,
|
||||
RTCSdpType::Pranswer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"have-remote-pranswer->SetRemote(answer)->stable",
|
||||
RTCSignalingState::HaveRemotePranswer,
|
||||
RTCSignalingState::Stable,
|
||||
StateChangeOp::SetRemote,
|
||||
RTCSdpType::Answer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"have-remote-offer->SetLocal(answer)->stable",
|
||||
RTCSignalingState::HaveRemoteOffer,
|
||||
RTCSignalingState::Stable,
|
||||
StateChangeOp::SetLocal,
|
||||
RTCSdpType::Answer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"have-remote-offer->SetLocal(pranswer)->have-local-pranswer",
|
||||
RTCSignalingState::HaveRemoteOffer,
|
||||
RTCSignalingState::HaveLocalPranswer,
|
||||
StateChangeOp::SetLocal,
|
||||
RTCSdpType::Pranswer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"have-local-pranswer->SetLocal(answer)->stable",
|
||||
RTCSignalingState::HaveLocalPranswer,
|
||||
RTCSignalingState::Stable,
|
||||
StateChangeOp::SetLocal,
|
||||
RTCSdpType::Answer,
|
||||
None,
|
||||
),
|
||||
(
|
||||
"(invalid) stable->SetRemote(pranswer)->have-remote-pranswer",
|
||||
RTCSignalingState::Stable,
|
||||
RTCSignalingState::HaveRemotePranswer,
|
||||
StateChangeOp::SetRemote,
|
||||
RTCSdpType::Pranswer,
|
||||
Some(Error::ErrSignalingStateProposedTransitionInvalid {
|
||||
from: RTCSignalingState::Stable,
|
||||
is_local: false,
|
||||
applying: RTCSdpType::Pranswer,
|
||||
}),
|
||||
),
|
||||
(
|
||||
"(invalid) stable->SetRemote(rollback)->have-local-offer",
|
||||
RTCSignalingState::Stable,
|
||||
RTCSignalingState::HaveLocalOffer,
|
||||
StateChangeOp::SetRemote,
|
||||
RTCSdpType::Rollback,
|
||||
Some(Error::ErrSignalingStateCannotRollback),
|
||||
),
|
||||
];
|
||||
|
||||
for (desc, cur, next, op, sdp_type, expected_err) in tests {
|
||||
let result = check_next_signaling_state(cur, next, op, sdp_type);
|
||||
match (&result, &expected_err) {
|
||||
(Ok(got), None) => {
|
||||
assert_eq!(*got, next, "{desc} state mismatch");
|
||||
}
|
||||
(Err(got), Some(err)) => {
|
||||
assert_eq!(got.to_string(), err.to_string(), "{desc} error mismatch");
|
||||
}
|
||||
_ => {
|
||||
panic!("{desc}: expected {expected_err:?}, but got {result:?}");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_generic_fmtp_parse() {
|
||||
let tests: Vec<(&str, &str, Box<dyn Fmtp>)> = vec![
|
||||
(
|
||||
"OneParam",
|
||||
"key-name=value",
|
||||
Box::new(GenericFmtp {
|
||||
mime_type: "generic".to_owned(),
|
||||
parameters: [("key-name".to_owned(), "value".to_owned())]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"OneParamWithWhiteSpeces",
|
||||
"\tkey-name=value ",
|
||||
Box::new(GenericFmtp {
|
||||
mime_type: "generic".to_owned(),
|
||||
parameters: [("key-name".to_owned(), "value".to_owned())]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"TwoParams",
|
||||
"key-name=value;key2=value2",
|
||||
Box::new(GenericFmtp {
|
||||
mime_type: "generic".to_owned(),
|
||||
parameters: [
|
||||
("key-name".to_owned(), "value".to_owned()),
|
||||
("key2".to_owned(), "value2".to_owned()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"TwoParamsWithWhiteSpeces",
|
||||
"key-name=value; \n\tkey2=value2 ",
|
||||
Box::new(GenericFmtp {
|
||||
mime_type: "generic".to_owned(),
|
||||
parameters: [
|
||||
("key-name".to_owned(), "value".to_owned()),
|
||||
("key2".to_owned(), "value2".to_owned()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
for (name, input, expected) in tests {
|
||||
let f = parse("generic", input);
|
||||
assert_eq!(&f, &expected, "{name} failed");
|
||||
|
||||
assert_eq!(f.mime_type(), "generic");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_fmtp_compare() {
|
||||
let consist_string: HashMap<bool, String> = [
|
||||
(true, "consist".to_owned()),
|
||||
(false, "inconsist".to_owned()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
let tests = vec![
|
||||
(
|
||||
"Equal",
|
||||
"key1=value1;key2=value2;key3=value3",
|
||||
"key1=value1;key2=value2;key3=value3",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"EqualWithWhitespaceVariants",
|
||||
"key1=value1;key2=value2;key3=value3",
|
||||
" key1=value1; \nkey2=value2;\t\nkey3=value3",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"EqualWithCase",
|
||||
"key1=value1;key2=value2;key3=value3",
|
||||
"key1=value1;key2=Value2;Key3=value3",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"OneHasExtraParam",
|
||||
"key1=value1;key2=value2;key3=value3",
|
||||
"key1=value1;key2=value2;key3=value3;key4=value4",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"Inconsistent",
|
||||
"key1=value1;key2=value2;key3=value3",
|
||||
"key1=value1;key2=different_value;key3=value3",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"Inconsistent_OneHasExtraParam",
|
||||
"key1=value1;key2=value2;key3=value3;key4=value4",
|
||||
"key1=value1;key2=different_value;key3=value3",
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
for (name, a, b, consist) in tests {
|
||||
let check = |a, b| {
|
||||
let aa = parse("", a);
|
||||
let bb = parse("", b);
|
||||
|
||||
// test forward case here
|
||||
let c = aa.match_fmtp(&*bb);
|
||||
assert_eq!(
|
||||
c,
|
||||
consist,
|
||||
"{}: '{}' and '{}' are expected to be {:?}, but treated as {:?}",
|
||||
name,
|
||||
a,
|
||||
b,
|
||||
consist_string.get(&consist),
|
||||
consist_string.get(&c),
|
||||
);
|
||||
|
||||
// test reverse case here
|
||||
let c = bb.match_fmtp(&*aa);
|
||||
assert_eq!(
|
||||
c,
|
||||
consist,
|
||||
"{}: '{}' and '{}' are expected to be {:?}, but treated as {:?}",
|
||||
name,
|
||||
a,
|
||||
b,
|
||||
consist_string.get(&consist),
|
||||
consist_string.get(&c),
|
||||
);
|
||||
};
|
||||
|
||||
check(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_generic_fmtp_compare_mime_type_case_mismatch() {
|
||||
let a = parse("video/vp8", "");
|
||||
let b = parse("video/VP8", "");
|
||||
|
||||
assert!(
|
||||
b.match_fmtp(&*a),
|
||||
"fmtp lines should match even if they use different casing"
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#[cfg(test)]
|
||||
mod generic_test;
|
||||
|
||||
use super::*;
|
||||
|
||||
/// fmtp_consist checks that two FMTP parameters are not inconsistent.
|
||||
fn fmtp_consist(a: &HashMap<String, String>, b: &HashMap<String, String>) -> bool {
|
||||
//TODO: add unicode case-folding equal support
|
||||
for (k, v) in a {
|
||||
if let Some(vb) = b.get(k) {
|
||||
if vb.to_uppercase() != v.to_uppercase() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
for (k, v) in b {
|
||||
if let Some(va) = a.get(k) {
|
||||
if va.to_uppercase() != v.to_uppercase() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct GenericFmtp {
|
||||
pub(crate) mime_type: String,
|
||||
pub(crate) parameters: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Fmtp for GenericFmtp {
|
||||
fn mime_type(&self) -> &str {
|
||||
self.mime_type.as_str()
|
||||
}
|
||||
|
||||
/// Match returns true if g and b are compatible fmtp descriptions
|
||||
/// The generic implementation is used for MimeTypes that are not defined
|
||||
fn match_fmtp(&self, f: &(dyn Fmtp)) -> bool {
|
||||
if let Some(c) = f.as_any().downcast_ref::<GenericFmtp>() {
|
||||
if self.mime_type.to_lowercase() != c.mime_type().to_lowercase() {
|
||||
return false;
|
||||
}
|
||||
|
||||
fmtp_consist(&self.parameters, &c.parameters)
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn parameter(&self, key: &str) -> Option<&String> {
|
||||
self.parameters.get(key)
|
||||
}
|
||||
|
||||
fn equal(&self, other: &(dyn Fmtp)) -> bool {
|
||||
other
|
||||
.as_any()
|
||||
.downcast_ref::<GenericFmtp>()
|
||||
.map_or(false, |a| self == a)
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &(dyn Any) {
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_h264_fmtp_parse() {
|
||||
let tests: Vec<(&str, &str, Box<dyn Fmtp>)> = vec![
|
||||
(
|
||||
"OneParam",
|
||||
"key-name=value",
|
||||
Box::new(H264Fmtp {
|
||||
parameters: [("key-name".to_owned(), "value".to_owned())]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"OneParamWithWhiteSpeces",
|
||||
"\tkey-name=value ",
|
||||
Box::new(H264Fmtp {
|
||||
parameters: [("key-name".to_owned(), "value".to_owned())]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"TwoParams",
|
||||
"key-name=value;key2=value2",
|
||||
Box::new(H264Fmtp {
|
||||
parameters: [
|
||||
("key-name".to_owned(), "value".to_owned()),
|
||||
("key2".to_owned(), "value2".to_owned()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
"TwoParamsWithWhiteSpeces",
|
||||
"key-name=value; \n\tkey2=value2 ",
|
||||
Box::new(H264Fmtp {
|
||||
parameters: [
|
||||
("key-name".to_owned(), "value".to_owned()),
|
||||
("key2".to_owned(), "value2".to_owned()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect(),
|
||||
}),
|
||||
),
|
||||
];
|
||||
|
||||
for (name, input, expected) in tests {
|
||||
let f = parse("video/h264", input);
|
||||
assert_eq!(&f, &expected, "{name} failed");
|
||||
|
||||
assert_eq!(f.mime_type(), "video/h264");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_h264_fmtp_compare() {
|
||||
let consist_string: HashMap<bool, String> = [
|
||||
(true, "consist".to_owned()),
|
||||
(false, "inconsist".to_owned()),
|
||||
]
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
let tests = vec![
|
||||
(
|
||||
"Equal",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"EqualWithWhitespaceVariants",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
" level-asymmetry-allowed=1; \npacketization-mode=1;\t\nprofile-level-id=42e01f",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"EqualWithCase",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;PROFILE-LEVEL-ID=42e01f",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"OneHasExtraParam",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
"packetization-mode=1;profile-level-id=42e01f",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"DifferentProfileLevelIDVersions",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=42e01f",
|
||||
"packetization-mode=1;profile-level-id=42e029",
|
||||
true,
|
||||
),
|
||||
(
|
||||
"Inconsistent",
|
||||
"packetization-mode=1;profile-level-id=42e029",
|
||||
"packetization-mode=0;profile-level-id=42e029",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"Inconsistent_MissingPacketizationMode",
|
||||
"packetization-mode=1;profile-level-id=42e029",
|
||||
"profile-level-id=42e029",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"Inconsistent_MissingProfileLevelID",
|
||||
"packetization-mode=1;profile-level-id=42e029",
|
||||
"packetization-mode=1",
|
||||
false,
|
||||
),
|
||||
(
|
||||
"Inconsistent_InvalidProfileLevelID",
|
||||
"packetization-mode=1;profile-level-id=42e029",
|
||||
"level-asymmetry-allowed=1;packetization-mode=1;profile-level-id=41e029",
|
||||
false,
|
||||
),
|
||||
];
|
||||
|
||||
for (name, a, b, consist) in tests {
|
||||
let check = |a, b| {
|
||||
let aa = parse("video/h264", a);
|
||||
let bb = parse("video/h264", b);
|
||||
|
||||
// test forward case here
|
||||
let c = aa.match_fmtp(&*bb);
|
||||
assert_eq!(
|
||||
c,
|
||||
consist,
|
||||
"{}: '{}' and '{}' are expected to be {:?}, but treated as {:?}",
|
||||
name,
|
||||
a,
|
||||
b,
|
||||
consist_string.get(&consist),
|
||||
consist_string.get(&c),
|
||||
);
|
||||
|
||||
// test reverse case here
|
||||
let c = bb.match_fmtp(&*aa);
|
||||
assert_eq!(
|
||||
c,
|
||||
consist,
|
||||
"{}: '{}' and '{}' are expected to be {:?}, but treated as {:?}",
|
||||
name,
|
||||
a,
|
||||
b,
|
||||
consist_string.get(&consist),
|
||||
consist_string.get(&c),
|
||||
);
|
||||
};
|
||||
|
||||
check(a, b);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
#[cfg(test)]
|
||||
mod h264_test;
|
||||
|
||||
use super::*;
|
||||
|
||||
fn profile_level_id_matches(a: &str, b: &str) -> bool {
|
||||
let aa = match hex::decode(a) {
|
||||
Ok(aa) => {
|
||||
if aa.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
aa
|
||||
}
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
let bb = match hex::decode(b) {
|
||||
Ok(bb) => {
|
||||
if bb.len() < 2 {
|
||||
return false;
|
||||
}
|
||||
bb
|
||||
}
|
||||
Err(_) => return false,
|
||||
};
|
||||
|
||||
aa[0] == bb[0] && aa[1] == bb[1]
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub(crate) struct H264Fmtp {
|
||||
pub(crate) parameters: HashMap<String, String>,
|
||||
}
|
||||
|
||||
impl Fmtp for H264Fmtp {
|
||||
fn mime_type(&self) -> &str {
|
||||
"video/h264"
|
||||
}
|
||||
|
||||
/// Match returns true if h and b are compatible fmtp descriptions
|
||||
/// Based on RFC6184 Section 8.2.2:
|
||||
/// The parameters identifying a media format configuration for H.264
|
||||
/// are profile-level-id and packetization-mode. These media format
|
||||
/// configuration parameters (except for the level part of profile-
|
||||
/// level-id) MUST be used symmetrically; that is, the answerer MUST
|
||||
/// either maintain all configuration parameters or remove the media
|
||||
/// format (payload type) completely if one or more of the parameter
|
||||
/// values are not supported.
|
||||
/// Informative note: The requirement for symmetric use does not
|
||||
/// apply for the level part of profile-level-id and does not apply
|
||||
/// for the other stream properties and capability parameters.
|
||||
fn match_fmtp(&self, f: &(dyn Fmtp)) -> bool {
|
||||
if let Some(c) = f.as_any().downcast_ref::<H264Fmtp>() {
|
||||
// test packetization-mode
|
||||
let hpmode = match self.parameters.get("packetization-mode") {
|
||||
Some(s) => s,
|
||||
None => return false,
|
||||
};
|
||||
let cpmode = match c.parameters.get("packetization-mode") {
|
||||
Some(s) => s,
|
||||
None => return false,
|
||||
};
|
||||
|
||||
if hpmode != cpmode {
|
||||
return false;
|
||||
}
|
||||
|
||||
// test profile-level-id
|
||||
let hplid = match self.parameters.get("profile-level-id") {
|
||||
Some(s) => s,
|
||||
None => return false,
|
||||
};
|
||||
let cplid = match c.parameters.get("profile-level-id") {
|
||||
Some(s) => s,
|
||||
None => return false,
|
||||
};
|
||||
|
||||
if !profile_level_id_matches(hplid, cplid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn parameter(&self, key: &str) -> Option<&String> {
|
||||
self.parameters.get(key)
|
||||
}
|
||||
|
||||
fn equal(&self, other: &(dyn Fmtp)) -> bool {
|
||||
other
|
||||
.as_any()
|
||||
.downcast_ref::<H264Fmtp>()
|
||||
.map_or(false, |a| self == a)
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &(dyn Any) {
|
||||
self
|
||||
}
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
pub(crate) mod generic;
|
||||
pub(crate) mod h264;
|
||||
|
||||
use std::any::Any;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt;
|
||||
|
||||
use crate::rtp_transceiver::fmtp::generic::GenericFmtp;
|
||||
use crate::rtp_transceiver::fmtp::h264::H264Fmtp;
|
||||
|
||||
/// Fmtp interface for implementing custom
|
||||
/// Fmtp parsers based on mime_type
|
||||
pub trait Fmtp: fmt::Debug {
|
||||
/// mime_type returns the mime_type associated with
|
||||
/// the fmtp
|
||||
fn mime_type(&self) -> &str;
|
||||
|
||||
/// match_fmtp compares two fmtp descriptions for
|
||||
/// compatibility based on the mime_type
|
||||
fn match_fmtp(&self, f: &(dyn Fmtp)) -> bool;
|
||||
|
||||
/// parameter returns a value for the associated key
|
||||
/// if contained in the parsed fmtp string
|
||||
fn parameter(&self, key: &str) -> Option<&String>;
|
||||
|
||||
fn equal(&self, other: &(dyn Fmtp)) -> bool;
|
||||
fn as_any(&self) -> &(dyn Any);
|
||||
}
|
||||
|
||||
impl PartialEq for dyn Fmtp {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.equal(other)
|
||||
}
|
||||
}
|
||||
|
||||
/// parse parses an fmtp string based on the MimeType
|
||||
pub fn parse(mime_type: &str, line: &str) -> Box<dyn Fmtp> {
|
||||
let mut parameters = HashMap::new();
|
||||
for p in line.split(';').collect::<Vec<&str>>() {
|
||||
let pp: Vec<&str> = p.trim().splitn(2, '=').collect();
|
||||
let key = pp[0].to_lowercase();
|
||||
let value = if pp.len() > 1 {
|
||||
pp[1].to_owned()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
parameters.insert(key, value);
|
||||
}
|
||||
|
||||
if mime_type.to_uppercase() == "video/h264".to_uppercase() {
|
||||
Box::new(H264Fmtp { parameters })
|
||||
} else {
|
||||
Box::new(GenericFmtp {
|
||||
mime_type: mime_type.to_owned(),
|
||||
parameters,
|
||||
})
|
||||
}
|
||||
}
|
||||
+560
@@ -0,0 +1,560 @@
|
||||
#[cfg(test)]
|
||||
mod rtp_transceiver_test;
|
||||
|
||||
use std::fmt;
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use interceptor::stream_info::{RTPHeaderExtension, StreamInfo};
|
||||
use interceptor::Attributes;
|
||||
use log::trace;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use smol_str::SmolStr;
|
||||
use tokio::sync::{Mutex, OnceCell};
|
||||
use util::Unmarshal;
|
||||
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rtp_transceiver::rtp_codec::*;
|
||||
use crate::rtp_transceiver::rtp_receiver::{RTCRtpReceiver, RTPReceiverInternal};
|
||||
use crate::rtp_transceiver::rtp_sender::RTCRtpSender;
|
||||
use crate::rtp_transceiver::rtp_transceiver_direction::RTCRtpTransceiverDirection;
|
||||
use crate::track::track_local::TrackLocal;
|
||||
|
||||
pub(crate) mod fmtp;
|
||||
pub mod rtp_codec;
|
||||
pub mod rtp_receiver;
|
||||
pub mod rtp_sender;
|
||||
pub mod rtp_transceiver_direction;
|
||||
pub(crate) mod srtp_writer_future;
|
||||
|
||||
/// SSRC represents a synchronization source
|
||||
/// A synchronization source is a randomly chosen
|
||||
/// value meant to be globally unique within a particular
|
||||
/// RTP session. Used to identify a single stream of media.
|
||||
/// <https://tools.ietf.org/html/rfc3550#section-3>
|
||||
#[allow(clippy::upper_case_acronyms)]
|
||||
pub type SSRC = u32;
|
||||
|
||||
/// PayloadType identifies the format of the RTP payload and determines
|
||||
/// its interpretation by the application. Each codec in a RTP Session
|
||||
/// will have a different PayloadType
|
||||
/// <https://tools.ietf.org/html/rfc3550#section-3>
|
||||
pub type PayloadType = u8;
|
||||
|
||||
/// TYPE_RTCP_FBT_RANSPORT_CC ..
|
||||
pub const TYPE_RTCP_FB_TRANSPORT_CC: &str = "transport-cc";
|
||||
|
||||
/// TYPE_RTCP_FB_GOOG_REMB ..
|
||||
pub const TYPE_RTCP_FB_GOOG_REMB: &str = "goog-remb";
|
||||
|
||||
/// TYPE_RTCP_FB_ACK ..
|
||||
pub const TYPE_RTCP_FB_ACK: &str = "ack";
|
||||
|
||||
/// TYPE_RTCP_FB_CCM ..
|
||||
pub const TYPE_RTCP_FB_CCM: &str = "ccm";
|
||||
|
||||
/// TYPE_RTCP_FB_NACK ..
|
||||
pub const TYPE_RTCP_FB_NACK: &str = "nack";
|
||||
|
||||
/// rtcpfeedback signals the connection to use additional RTCP packet types.
|
||||
/// <https://draft.ortc.org/#dom-rtcrtcpfeedback>
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RTCPFeedback {
|
||||
/// Type is the type of feedback.
|
||||
/// see: <https://draft.ortc.org/#dom-rtcrtcpfeedback>
|
||||
/// valid: ack, ccm, nack, goog-remb, transport-cc
|
||||
pub typ: String,
|
||||
|
||||
/// The parameter value depends on the type.
|
||||
/// For example, type="nack" parameter="pli" will send Picture Loss Indicator packets.
|
||||
pub parameter: String,
|
||||
}
|
||||
|
||||
/// RTPCapabilities represents the capabilities of a transceiver
|
||||
/// <https://w3c.github.io/webrtc-pc/#rtcrtpcapabilities>
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct RTCRtpCapabilities {
|
||||
pub codecs: Vec<RTCRtpCodecCapability>,
|
||||
pub header_extensions: Vec<RTCRtpHeaderExtensionCapability>,
|
||||
}
|
||||
|
||||
/// RTPRtxParameters dictionary contains information relating to retransmission (RTX) settings.
|
||||
/// <https://draft.ortc.org/#dom-rtcrtprtxparameters>
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RTCRtpRtxParameters {
|
||||
pub ssrc: SSRC,
|
||||
}
|
||||
|
||||
/// RTPCodingParameters provides information relating to both encoding and decoding.
|
||||
/// This is a subset of the RFC since Pion WebRTC doesn't implement encoding/decoding itself
|
||||
/// <http://draft.ortc.org/#dom-rtcrtpcodingparameters>
|
||||
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct RTCRtpCodingParameters {
|
||||
pub rid: SmolStr,
|
||||
pub ssrc: SSRC,
|
||||
pub payload_type: PayloadType,
|
||||
pub rtx: RTCRtpRtxParameters,
|
||||
}
|
||||
|
||||
/// RTPDecodingParameters provides information relating to both encoding and decoding.
|
||||
/// This is a subset of the RFC since Pion WebRTC doesn't implement decoding itself
|
||||
/// <http://draft.ortc.org/#dom-rtcrtpdecodingparameters>
|
||||
pub type RTCRtpDecodingParameters = RTCRtpCodingParameters;
|
||||
|
||||
/// RTPEncodingParameters provides information relating to both encoding and decoding.
|
||||
/// This is a subset of the RFC since Pion WebRTC doesn't implement encoding itself
|
||||
/// <http://draft.ortc.org/#dom-rtcrtpencodingparameters>
|
||||
pub type RTCRtpEncodingParameters = RTCRtpCodingParameters;
|
||||
|
||||
/// RTPReceiveParameters contains the RTP stack settings used by receivers
|
||||
#[derive(Debug)]
|
||||
pub struct RTCRtpReceiveParameters {
|
||||
pub encodings: Vec<RTCRtpDecodingParameters>,
|
||||
}
|
||||
|
||||
/// RTPSendParameters contains the RTP stack settings used by receivers
|
||||
#[derive(Debug)]
|
||||
pub struct RTCRtpSendParameters {
|
||||
pub rtp_parameters: RTCRtpParameters,
|
||||
pub encodings: Vec<RTCRtpEncodingParameters>,
|
||||
}
|
||||
|
||||
/// RTPTransceiverInit dictionary is used when calling the WebRTC function addTransceiver() to provide configuration options for the new transceiver.
|
||||
pub struct RTCRtpTransceiverInit {
|
||||
pub direction: RTCRtpTransceiverDirection,
|
||||
pub send_encodings: Vec<RTCRtpEncodingParameters>,
|
||||
// Streams []*Track
|
||||
}
|
||||
|
||||
pub(crate) fn create_stream_info(
|
||||
id: String,
|
||||
ssrc: SSRC,
|
||||
payload_type: PayloadType,
|
||||
codec: RTCRtpCodecCapability,
|
||||
webrtc_header_extensions: &[RTCRtpHeaderExtensionParameters],
|
||||
) -> StreamInfo {
|
||||
let header_extensions: Vec<RTPHeaderExtension> = webrtc_header_extensions
|
||||
.iter()
|
||||
.map(|h| RTPHeaderExtension {
|
||||
id: h.id,
|
||||
uri: h.uri.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let feedbacks: Vec<_> = codec
|
||||
.rtcp_feedback
|
||||
.iter()
|
||||
.map(|f| interceptor::stream_info::RTCPFeedback {
|
||||
typ: f.typ.clone(),
|
||||
parameter: f.parameter.clone(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
StreamInfo {
|
||||
id,
|
||||
attributes: Attributes::new(),
|
||||
ssrc,
|
||||
payload_type,
|
||||
rtp_header_extensions: header_extensions,
|
||||
mime_type: codec.mime_type,
|
||||
clock_rate: codec.clock_rate,
|
||||
channels: codec.channels,
|
||||
sdp_fmtp_line: codec.sdp_fmtp_line,
|
||||
rtcp_feedback: feedbacks,
|
||||
}
|
||||
}
|
||||
|
||||
pub type TriggerNegotiationNeededFnOption =
|
||||
Option<Box<dyn Fn() -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> + Send + Sync>>;
|
||||
|
||||
/// RTPTransceiver represents a combination of an RTPSender and an RTPReceiver that share a common mid.
|
||||
pub struct RTCRtpTransceiver {
|
||||
mid: OnceCell<SmolStr>, //atomic.Value
|
||||
sender: Mutex<Arc<RTCRtpSender>>, //atomic.Value
|
||||
receiver: Mutex<Arc<RTCRtpReceiver>>, //atomic.Value
|
||||
|
||||
direction: AtomicU8, //RTPTransceiverDirection
|
||||
current_direction: AtomicU8, //RTPTransceiverDirection
|
||||
|
||||
codecs: Arc<Mutex<Vec<RTCRtpCodecParameters>>>, // User provided codecs via set_codec_preferences
|
||||
|
||||
pub(crate) stopped: AtomicBool,
|
||||
pub(crate) kind: RTPCodecType,
|
||||
|
||||
media_engine: Arc<MediaEngine>,
|
||||
|
||||
trigger_negotiation_needed: Mutex<TriggerNegotiationNeededFnOption>,
|
||||
}
|
||||
|
||||
impl RTCRtpTransceiver {
|
||||
pub async fn new(
|
||||
receiver: Arc<RTCRtpReceiver>,
|
||||
sender: Arc<RTCRtpSender>,
|
||||
direction: RTCRtpTransceiverDirection,
|
||||
kind: RTPCodecType,
|
||||
codecs: Vec<RTCRtpCodecParameters>,
|
||||
media_engine: Arc<MediaEngine>,
|
||||
trigger_negotiation_needed: TriggerNegotiationNeededFnOption,
|
||||
) -> Arc<Self> {
|
||||
let codecs = Arc::new(Mutex::new(codecs));
|
||||
receiver.set_transceiver_codecs(Some(Arc::clone(&codecs)));
|
||||
|
||||
let t = Arc::new(RTCRtpTransceiver {
|
||||
mid: OnceCell::new(),
|
||||
sender: Mutex::new(sender),
|
||||
receiver: Mutex::new(receiver),
|
||||
|
||||
direction: AtomicU8::new(direction as u8),
|
||||
current_direction: AtomicU8::new(RTCRtpTransceiverDirection::Unspecified as u8),
|
||||
|
||||
codecs,
|
||||
stopped: AtomicBool::new(false),
|
||||
kind,
|
||||
media_engine,
|
||||
trigger_negotiation_needed: Mutex::new(trigger_negotiation_needed),
|
||||
});
|
||||
t.sender()
|
||||
.await
|
||||
.set_rtp_transceiver(Some(Arc::downgrade(&t)));
|
||||
|
||||
t
|
||||
}
|
||||
|
||||
/// set_codec_preferences sets preferred list of supported codecs
|
||||
/// if codecs is empty or nil we reset to default from MediaEngine
|
||||
pub async fn set_codec_preferences(&self, codecs: Vec<RTCRtpCodecParameters>) -> Result<()> {
|
||||
for codec in &codecs {
|
||||
let media_engine_codecs = self.media_engine.get_codecs_by_kind(self.kind);
|
||||
let (_, match_type) = codec_parameters_fuzzy_search(codec, &media_engine_codecs);
|
||||
if match_type == CodecMatch::None {
|
||||
return Err(Error::ErrRTPTransceiverCodecUnsupported);
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
let mut c = self.codecs.lock().await;
|
||||
*c = codecs;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Codecs returns list of supported codecs
|
||||
pub(crate) async fn get_codecs(&self) -> Vec<RTCRtpCodecParameters> {
|
||||
let mut codecs = self.codecs.lock().await;
|
||||
RTPReceiverInternal::get_codecs(&mut codecs, self.kind, &self.media_engine)
|
||||
}
|
||||
|
||||
/// sender returns the RTPTransceiver's RTPSender if it has one
|
||||
pub async fn sender(&self) -> Arc<RTCRtpSender> {
|
||||
let sender = self.sender.lock().await;
|
||||
sender.clone()
|
||||
}
|
||||
|
||||
/// set_sender_track sets the RTPSender and Track to current transceiver
|
||||
pub async fn set_sender_track(
|
||||
self: &Arc<Self>,
|
||||
sender: Arc<RTCRtpSender>,
|
||||
track: Option<Arc<dyn TrackLocal + Send + Sync>>,
|
||||
) -> Result<()> {
|
||||
self.set_sender(sender).await;
|
||||
self.set_sending_track(track).await
|
||||
}
|
||||
|
||||
pub async fn set_sender(self: &Arc<Self>, s: Arc<RTCRtpSender>) {
|
||||
s.set_rtp_transceiver(Some(Arc::downgrade(self)));
|
||||
|
||||
let prev_sender = self.sender().await;
|
||||
prev_sender.set_rtp_transceiver(None);
|
||||
|
||||
{
|
||||
let mut sender = self.sender.lock().await;
|
||||
*sender = s;
|
||||
}
|
||||
}
|
||||
|
||||
/// receiver returns the RTPTransceiver's RTPReceiver if it has one
|
||||
pub async fn receiver(&self) -> Arc<RTCRtpReceiver> {
|
||||
let receiver = self.receiver.lock().await;
|
||||
receiver.clone()
|
||||
}
|
||||
|
||||
pub(crate) async fn set_receiver(&self, r: Arc<RTCRtpReceiver>) {
|
||||
r.set_transceiver_codecs(Some(Arc::clone(&self.codecs)));
|
||||
|
||||
{
|
||||
let mut receiver = self.receiver.lock().await;
|
||||
(*receiver).set_transceiver_codecs(None);
|
||||
|
||||
*receiver = r;
|
||||
}
|
||||
}
|
||||
|
||||
/// set_mid sets the RTPTransceiver's mid. If it was already set, will return an error.
|
||||
pub(crate) fn set_mid(&self, mid: SmolStr) -> Result<()> {
|
||||
self.mid
|
||||
.set(mid)
|
||||
.map_err(|_| Error::ErrRTPTransceiverCannotChangeMid)
|
||||
}
|
||||
|
||||
/// mid gets the Transceiver's mid value. When not already set, this value will be set in CreateOffer or create_answer.
|
||||
pub fn mid(&self) -> Option<SmolStr> {
|
||||
self.mid.get().map(Clone::clone)
|
||||
}
|
||||
|
||||
/// kind returns RTPTransceiver's kind.
|
||||
pub fn kind(&self) -> RTPCodecType {
|
||||
self.kind
|
||||
}
|
||||
|
||||
/// direction returns the RTPTransceiver's desired direction.
|
||||
pub fn direction(&self) -> RTCRtpTransceiverDirection {
|
||||
self.direction.load(Ordering::SeqCst).into()
|
||||
}
|
||||
|
||||
/// Set the direction of this transceiver. This might trigger a renegotiation.
|
||||
pub async fn set_direction(&self, d: RTCRtpTransceiverDirection) {
|
||||
let changed = self.set_direction_internal(d);
|
||||
|
||||
if changed {
|
||||
let lock = self.trigger_negotiation_needed.lock().await;
|
||||
if let Some(trigger) = &*lock {
|
||||
(trigger)().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_direction_internal(&self, d: RTCRtpTransceiverDirection) -> bool {
|
||||
let previous: RTCRtpTransceiverDirection =
|
||||
self.direction.swap(d as u8, Ordering::SeqCst).into();
|
||||
|
||||
let changed = d != previous;
|
||||
|
||||
if changed {
|
||||
trace!(
|
||||
"Changing direction of transceiver from {} to {}",
|
||||
previous,
|
||||
d
|
||||
);
|
||||
}
|
||||
|
||||
changed
|
||||
}
|
||||
|
||||
/// current_direction returns the RTPTransceiver's current direction as negotiated.
|
||||
///
|
||||
/// If this transceiver has never been negotiated or if it's stopped this returns [`RTCRtpTransceiverDirection::Unspecified`].
|
||||
pub fn current_direction(&self) -> RTCRtpTransceiverDirection {
|
||||
if self.stopped.load(Ordering::SeqCst) {
|
||||
return RTCRtpTransceiverDirection::Unspecified;
|
||||
}
|
||||
|
||||
self.current_direction.load(Ordering::SeqCst).into()
|
||||
}
|
||||
|
||||
pub(crate) fn set_current_direction(&self, d: RTCRtpTransceiverDirection) {
|
||||
let previous: RTCRtpTransceiverDirection = self
|
||||
.current_direction
|
||||
.swap(d as u8, Ordering::SeqCst)
|
||||
.into();
|
||||
|
||||
if d != previous {
|
||||
trace!(
|
||||
"Changing current direction of transceiver from {} to {}",
|
||||
previous,
|
||||
d,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Perform any subsequent actions after altering the transceiver's direction.
|
||||
///
|
||||
/// After changing the transceiver's direction this method should be called to perform any
|
||||
/// side-effects that results from the new direction, such as pausing/resuming the RTP receiver.
|
||||
pub(crate) async fn process_new_current_direction(
|
||||
&self,
|
||||
previous_direction: RTCRtpTransceiverDirection,
|
||||
) -> Result<()> {
|
||||
if self.stopped.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let current_direction = self.current_direction();
|
||||
if previous_direction != current_direction {
|
||||
let mid = self.mid();
|
||||
trace!(
|
||||
"Processing transceiver({:?}) direction change from {} to {}",
|
||||
mid,
|
||||
previous_direction,
|
||||
current_direction
|
||||
);
|
||||
} else {
|
||||
// no change.
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
{
|
||||
let receiver = self.receiver.lock().await;
|
||||
let pause_receiver = !current_direction.has_recv();
|
||||
|
||||
if pause_receiver {
|
||||
receiver.pause().await?;
|
||||
} else {
|
||||
receiver.resume().await?;
|
||||
}
|
||||
}
|
||||
|
||||
let pause_sender = !current_direction.has_send();
|
||||
{
|
||||
let sender = &*self.sender.lock().await;
|
||||
sender.set_paused(pause_sender);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// stop irreversibly stops the RTPTransceiver
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
if self.stopped.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.stopped.store(true, Ordering::SeqCst);
|
||||
|
||||
{
|
||||
let sender = self.sender.lock().await;
|
||||
sender.stop().await?;
|
||||
}
|
||||
{
|
||||
let r = self.receiver.lock().await;
|
||||
r.stop().await?;
|
||||
}
|
||||
|
||||
self.set_direction_internal(RTCRtpTransceiverDirection::Inactive);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn set_sending_track(
|
||||
&self,
|
||||
track: Option<Arc<dyn TrackLocal + Send + Sync>>,
|
||||
) -> Result<()> {
|
||||
let track_is_none = track.is_none();
|
||||
{
|
||||
let sender = self.sender.lock().await;
|
||||
sender.replace_track(track).await?;
|
||||
}
|
||||
|
||||
let direction = self.direction();
|
||||
let should_send = !track_is_none;
|
||||
let should_recv = direction.has_recv();
|
||||
self.set_direction_internal(RTCRtpTransceiverDirection::from_send_recv(
|
||||
should_send,
|
||||
should_recv,
|
||||
));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for RTCRtpTransceiver {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("RTCRtpTransceiver")
|
||||
.field("mid", &self.mid)
|
||||
.field("sender", &self.sender)
|
||||
.field("receiver", &self.receiver)
|
||||
.field("direction", &self.direction)
|
||||
.field("current_direction", &self.current_direction)
|
||||
.field("codecs", &self.codecs)
|
||||
.field("stopped", &self.stopped)
|
||||
.field("kind", &self.kind)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn find_by_mid(
|
||||
mid: &str,
|
||||
local_transceivers: &mut Vec<Arc<RTCRtpTransceiver>>,
|
||||
) -> Option<Arc<RTCRtpTransceiver>> {
|
||||
for (i, t) in local_transceivers.iter().enumerate() {
|
||||
if t.mid() == Some(SmolStr::from(mid)) {
|
||||
return Some(local_transceivers.remove(i));
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// Given a direction+type pluck a transceiver from the passed list
|
||||
/// if no entry satisfies the requested type+direction return a inactive Transceiver
|
||||
pub(crate) async fn satisfy_type_and_direction(
|
||||
remote_kind: RTPCodecType,
|
||||
remote_direction: RTCRtpTransceiverDirection,
|
||||
local_transceivers: &mut Vec<Arc<RTCRtpTransceiver>>,
|
||||
) -> Option<Arc<RTCRtpTransceiver>> {
|
||||
// Get direction order from most preferred to least
|
||||
let get_preferred_directions = || -> Vec<RTCRtpTransceiverDirection> {
|
||||
match remote_direction {
|
||||
RTCRtpTransceiverDirection::Sendrecv => vec![
|
||||
RTCRtpTransceiverDirection::Recvonly,
|
||||
RTCRtpTransceiverDirection::Sendrecv,
|
||||
],
|
||||
RTCRtpTransceiverDirection::Sendonly => vec![RTCRtpTransceiverDirection::Recvonly],
|
||||
RTCRtpTransceiverDirection::Recvonly => vec![
|
||||
RTCRtpTransceiverDirection::Sendonly,
|
||||
RTCRtpTransceiverDirection::Sendrecv,
|
||||
],
|
||||
_ => vec![],
|
||||
}
|
||||
};
|
||||
|
||||
for possible_direction in get_preferred_directions() {
|
||||
for (i, t) in local_transceivers.iter().enumerate() {
|
||||
if t.mid().is_none() && t.kind == remote_kind && possible_direction == t.direction() {
|
||||
return Some(local_transceivers.remove(i));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
/// handle_unknown_rtp_packet consumes a single RTP Packet and returns information that is helpful
|
||||
/// for demuxing and handling an unknown SSRC (usually for Simulcast)
|
||||
pub(crate) fn handle_unknown_rtp_packet(
|
||||
buf: &[u8],
|
||||
mid_extension_id: u8,
|
||||
sid_extension_id: u8,
|
||||
rsid_extension_id: u8,
|
||||
) -> Result<(String, String, String, PayloadType)> {
|
||||
let mut reader = buf;
|
||||
let rp = rtp::packet::Packet::unmarshal(&mut reader)?;
|
||||
|
||||
if !rp.header.extension {
|
||||
return Ok((String::new(), String::new(), String::new(), 0));
|
||||
}
|
||||
|
||||
let payload_type = rp.header.payload_type;
|
||||
|
||||
let mid = if let Some(payload) = rp.header.get_extension(mid_extension_id) {
|
||||
String::from_utf8(payload.to_vec())?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let rid = if let Some(payload) = rp.header.get_extension(sid_extension_id) {
|
||||
String::from_utf8(payload.to_vec())?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
let srid = if let Some(payload) = rp.header.get_extension(rsid_extension_id) {
|
||||
String::from_utf8(payload.to_vec())?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
|
||||
Ok((mid, rid, srid, payload_type))
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
use std::fmt;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::*;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rtp_transceiver::fmtp;
|
||||
|
||||
/// RTPCodecType determines the type of a codec
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTPCodecType {
|
||||
#[default]
|
||||
Unspecified = 0,
|
||||
|
||||
/// RTPCodecTypeAudio indicates this is an audio codec
|
||||
Audio = 1,
|
||||
|
||||
/// RTPCodecTypeVideo indicates this is a video codec
|
||||
Video = 2,
|
||||
}
|
||||
|
||||
impl From<&str> for RTPCodecType {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
"audio" => RTPCodecType::Audio,
|
||||
"video" => RTPCodecType::Video,
|
||||
_ => RTPCodecType::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTPCodecType {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTPCodecType::Audio,
|
||||
2 => RTPCodecType::Video,
|
||||
_ => RTPCodecType::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTPCodecType {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTPCodecType::Audio => "audio",
|
||||
RTPCodecType::Video => "video",
|
||||
RTPCodecType::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
/// RTPCodecCapability provides information about codec capabilities.
|
||||
/// <https://w3c.github.io/webrtc-pc/#dictionary-rtcrtpcodeccapability-members>
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RTCRtpCodecCapability {
|
||||
pub mime_type: String,
|
||||
pub clock_rate: u32,
|
||||
pub channels: u16,
|
||||
pub sdp_fmtp_line: String,
|
||||
pub rtcp_feedback: Vec<RTCPFeedback>,
|
||||
}
|
||||
|
||||
impl RTCRtpCodecCapability {
|
||||
/// Turn codec capability into a `packetizer::Payloader`
|
||||
pub fn payloader_for_codec(&self) -> Result<Box<dyn rtp::packetizer::Payloader + Send + Sync>> {
|
||||
let mime_type = self.mime_type.to_lowercase();
|
||||
if mime_type == MIME_TYPE_H264.to_lowercase() {
|
||||
Ok(Box::<rtp::codecs::h264::H264Payloader>::default())
|
||||
} else if mime_type == MIME_TYPE_VP8.to_lowercase() {
|
||||
let mut vp8_payloader = rtp::codecs::vp8::Vp8Payloader::default();
|
||||
vp8_payloader.enable_picture_id = true;
|
||||
Ok(Box::new(vp8_payloader))
|
||||
} else if mime_type == MIME_TYPE_VP9.to_lowercase() {
|
||||
Ok(Box::<rtp::codecs::vp9::Vp9Payloader>::default())
|
||||
} else if mime_type == MIME_TYPE_OPUS.to_lowercase() {
|
||||
Ok(Box::<rtp::codecs::opus::OpusPayloader>::default())
|
||||
} else if mime_type == MIME_TYPE_G722.to_lowercase()
|
||||
|| mime_type == MIME_TYPE_PCMU.to_lowercase()
|
||||
|| mime_type == MIME_TYPE_PCMA.to_lowercase()
|
||||
|| mime_type == MIME_TYPE_TELEPHONE_EVENT.to_lowercase()
|
||||
{
|
||||
Ok(Box::<rtp::codecs::g7xx::G7xxPayloader>::default())
|
||||
} else if mime_type == MIME_TYPE_AV1.to_lowercase() {
|
||||
Ok(Box::<rtp::codecs::av1::Av1Payloader>::default())
|
||||
} else {
|
||||
Err(Error::ErrNoPayloaderForCodec)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// RTPHeaderExtensionCapability is used to define a RFC5285 RTP header extension supported by the codec.
|
||||
/// <https://w3c.github.io/webrtc-pc/#dom-rtcrtpcapabilities-headerextensions>
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct RTCRtpHeaderExtensionCapability {
|
||||
pub uri: String,
|
||||
}
|
||||
|
||||
/// RTPHeaderExtensionParameter represents a negotiated RFC5285 RTP header extension.
|
||||
/// <https://w3c.github.io/webrtc-pc/#dictionary-rtcrtpheaderextensionparameters-members>
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RTCRtpHeaderExtensionParameters {
|
||||
pub uri: String,
|
||||
pub id: isize,
|
||||
}
|
||||
|
||||
/// RTPCodecParameters is a sequence containing the media codecs that an RtpSender
|
||||
/// will choose from, as well as entries for RTX, RED and FEC mechanisms. This also
|
||||
/// includes the PayloadType that has been negotiated
|
||||
/// <https://w3c.github.io/webrtc-pc/#rtcrtpcodecparameters>
|
||||
#[derive(Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RTCRtpCodecParameters {
|
||||
pub capability: RTCRtpCodecCapability,
|
||||
pub payload_type: PayloadType,
|
||||
pub stats_id: String,
|
||||
}
|
||||
|
||||
/// RTPParameters is a list of negotiated codecs and header extensions
|
||||
/// <https://w3c.github.io/webrtc-pc/#dictionary-rtcrtpparameters-members>
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct RTCRtpParameters {
|
||||
pub header_extensions: Vec<RTCRtpHeaderExtensionParameters>,
|
||||
pub codecs: Vec<RTCRtpCodecParameters>,
|
||||
}
|
||||
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq)]
|
||||
pub(crate) enum CodecMatch {
|
||||
#[default]
|
||||
None = 0,
|
||||
Partial = 1,
|
||||
Exact = 2,
|
||||
}
|
||||
|
||||
/// Do a fuzzy find for a codec in the list of codecs
|
||||
/// Used for lookup up a codec in an existing list to find a match
|
||||
/// Returns codecMatchExact, codecMatchPartial, or codecMatchNone
|
||||
pub(crate) fn codec_parameters_fuzzy_search(
|
||||
needle: &RTCRtpCodecParameters,
|
||||
haystack: &[RTCRtpCodecParameters],
|
||||
) -> (RTCRtpCodecParameters, CodecMatch) {
|
||||
let needle_fmtp = fmtp::parse(
|
||||
&needle.capability.mime_type,
|
||||
&needle.capability.sdp_fmtp_line,
|
||||
);
|
||||
|
||||
//TODO: add unicode case-folding equal support
|
||||
|
||||
// First attempt to match on mime_type + sdpfmtp_line
|
||||
for c in haystack {
|
||||
let cfmpt = fmtp::parse(&c.capability.mime_type, &c.capability.sdp_fmtp_line);
|
||||
if needle_fmtp.match_fmtp(&*cfmpt) {
|
||||
return (c.clone(), CodecMatch::Exact);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to just mime_type
|
||||
for c in haystack {
|
||||
if c.capability.mime_type.to_uppercase() == needle.capability.mime_type.to_uppercase() {
|
||||
return (c.clone(), CodecMatch::Partial);
|
||||
}
|
||||
}
|
||||
|
||||
(RTCRtpCodecParameters::default(), CodecMatch::None)
|
||||
}
|
||||
@@ -0,0 +1,861 @@
|
||||
#[cfg(test)]
|
||||
mod rtp_receiver_test;
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use interceptor::stream_info::RTPHeaderExtension;
|
||||
use interceptor::{Attributes, Interceptor};
|
||||
use log::trace;
|
||||
use smol_str::SmolStr;
|
||||
use tokio::sync::{watch, Mutex, RwLock};
|
||||
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::dtls_transport::RTCDtlsTransport;
|
||||
use crate::error::{flatten_errs, Error, Result};
|
||||
use crate::peer_connection::sdp::TrackDetails;
|
||||
use crate::rtp_transceiver::rtp_codec::{
|
||||
codec_parameters_fuzzy_search, CodecMatch, RTCRtpCodecCapability, RTCRtpCodecParameters,
|
||||
RTCRtpParameters, RTPCodecType,
|
||||
};
|
||||
use crate::rtp_transceiver::rtp_transceiver_direction::RTCRtpTransceiverDirection;
|
||||
use crate::rtp_transceiver::{
|
||||
create_stream_info, RTCRtpDecodingParameters, RTCRtpReceiveParameters, SSRC,
|
||||
};
|
||||
use crate::track::track_remote::TrackRemote;
|
||||
use crate::track::{TrackStream, TrackStreams};
|
||||
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum State {
|
||||
/// We haven't started yet.
|
||||
Unstarted = 0,
|
||||
/// We haven't started yet and additionally we've been paused.
|
||||
UnstartedPaused = 1,
|
||||
|
||||
/// We have started and are running.
|
||||
Started = 2,
|
||||
|
||||
/// We have been paused after starting.
|
||||
Paused = 3,
|
||||
|
||||
/// We have been stopped.
|
||||
Stopped = 4,
|
||||
}
|
||||
|
||||
impl From<u8> for State {
|
||||
fn from(value: u8) -> Self {
|
||||
match value {
|
||||
v if v == State::Unstarted as u8 => State::Unstarted,
|
||||
v if v == State::UnstartedPaused as u8 => State::UnstartedPaused,
|
||||
v if v == State::Started as u8 => State::Started,
|
||||
v if v == State::Paused as u8 => State::Paused,
|
||||
v if v == State::Stopped as u8 => State::Stopped,
|
||||
_ => unreachable!(
|
||||
"Invalid serialization of {}: {}",
|
||||
std::any::type_name::<Self>(),
|
||||
value
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for State {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
State::Unstarted => write!(f, "Unstarted"),
|
||||
State::UnstartedPaused => write!(f, "UnstartedPaused"),
|
||||
State::Started => write!(f, "Running"),
|
||||
State::Paused => write!(f, "Paused"),
|
||||
State::Stopped => write!(f, "Closed"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn transition(to: Self, tx: &watch::Sender<State>) -> Result<()> {
|
||||
let current = *tx.borrow();
|
||||
if current == to {
|
||||
// Already in this state
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
match current {
|
||||
Self::Unstarted
|
||||
if matches!(to, Self::Started | Self::Stopped | Self::UnstartedPaused) =>
|
||||
{
|
||||
let _ = tx.send(to);
|
||||
return Ok(());
|
||||
}
|
||||
Self::UnstartedPaused
|
||||
if matches!(to, Self::Unstarted | Self::Stopped | Self::Paused) =>
|
||||
{
|
||||
let _ = tx.send(to);
|
||||
return Ok(());
|
||||
}
|
||||
State::Started if matches!(to, Self::Paused | Self::Stopped) => {
|
||||
let _ = tx.send(to);
|
||||
return Ok(());
|
||||
}
|
||||
State::Paused if matches!(to, Self::Started | Self::Stopped) => {
|
||||
let _ = tx.send(to);
|
||||
return Ok(());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
Err(Error::ErrRTPReceiverStateChangeInvalid { from: current, to })
|
||||
}
|
||||
|
||||
async fn wait_for(rx: &mut watch::Receiver<State>, states: &[State]) -> Result<()> {
|
||||
loop {
|
||||
let state = *rx.borrow();
|
||||
|
||||
match state {
|
||||
_ if states.contains(&state) => return Ok(()),
|
||||
State::Stopped => {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if rx.changed().await.is_err() {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn error_on_close(rx: &mut watch::Receiver<State>) -> Result<()> {
|
||||
if rx.changed().await.is_err() {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
|
||||
let state = *rx.borrow();
|
||||
if state == State::Stopped {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn is_started(&self) -> bool {
|
||||
matches!(self, Self::Started | Self::Paused)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct RTPReceiverInternal {
|
||||
pub(crate) kind: RTPCodecType,
|
||||
|
||||
// State is stored within the channel
|
||||
state_tx: watch::Sender<State>,
|
||||
state_rx: watch::Receiver<State>,
|
||||
|
||||
tracks: RwLock<Vec<TrackStreams>>,
|
||||
|
||||
transceiver_codecs: ArcSwapOption<Mutex<Vec<RTCRtpCodecParameters>>>,
|
||||
|
||||
transport: Arc<RTCDtlsTransport>,
|
||||
media_engine: Arc<MediaEngine>,
|
||||
interceptor: Arc<dyn Interceptor + Send + Sync>,
|
||||
}
|
||||
|
||||
impl RTPReceiverInternal {
|
||||
/// read reads incoming RTCP for this RTPReceiver
|
||||
async fn read(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let mut state_watch_rx = self.state_tx.subscribe();
|
||||
// Ensure we are running or paused. When paused we still receive RTCP even if RTP traffic
|
||||
// isn't flowing.
|
||||
State::wait_for(&mut state_watch_rx, &[State::Started, State::Paused]).await?;
|
||||
|
||||
let tracks = self.tracks.read().await;
|
||||
if let Some(t) = tracks.first() {
|
||||
if let Some(rtcp_interceptor) = &t.stream.rtcp_interceptor {
|
||||
let a = Attributes::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
res = State::error_on_close(&mut state_watch_rx) => {
|
||||
res?
|
||||
}
|
||||
result = rtcp_interceptor.read(b, &a) => {
|
||||
return Ok(result?)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Err(Error::ErrInterceptorNotBind)
|
||||
}
|
||||
} else {
|
||||
Err(Error::ErrExistingTrack)
|
||||
}
|
||||
}
|
||||
|
||||
/// read_simulcast reads incoming RTCP for this RTPReceiver for given rid
|
||||
async fn read_simulcast(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
rid: &str,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let mut state_watch_rx = self.state_tx.subscribe();
|
||||
|
||||
// Ensure we are running or paused. When paused we still receive RTCP even if RTP traffic
|
||||
// isn't flowing.
|
||||
State::wait_for(&mut state_watch_rx, &[State::Started, State::Paused]).await?;
|
||||
|
||||
let tracks = self.tracks.read().await;
|
||||
for t in &*tracks {
|
||||
if t.track.rid() == rid {
|
||||
if let Some(rtcp_interceptor) = &t.stream.rtcp_interceptor {
|
||||
let a = Attributes::new();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
res = State::error_on_close(&mut state_watch_rx) => {
|
||||
res?
|
||||
}
|
||||
result = rtcp_interceptor.read(b, &a) => {
|
||||
return Ok(result?);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return Err(Error::ErrInterceptorNotBind);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(Error::ErrRTPReceiverForRIDTrackStreamNotFound)
|
||||
}
|
||||
|
||||
/// read_rtcp is a convenience method that wraps Read and unmarshal for you.
|
||||
/// It also runs any configured interceptors.
|
||||
async fn read_rtcp(
|
||||
&self,
|
||||
receive_mtu: usize,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let mut b = vec![0u8; receive_mtu];
|
||||
let (pkts, attributes) = self.read(&mut b).await?;
|
||||
|
||||
Ok((pkts, attributes))
|
||||
}
|
||||
|
||||
/// read_simulcast_rtcp is a convenience method that wraps ReadSimulcast and unmarshal for you
|
||||
async fn read_simulcast_rtcp(
|
||||
&self,
|
||||
rid: &str,
|
||||
receive_mtu: usize,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let mut b = vec![0u8; receive_mtu];
|
||||
let (pkts, attributes) = self.read_simulcast(&mut b, rid).await?;
|
||||
|
||||
Ok((pkts, attributes))
|
||||
}
|
||||
|
||||
pub(crate) async fn read_rtp(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
tid: usize,
|
||||
) -> Result<(rtp::packet::Packet, Attributes)> {
|
||||
let mut state_watch_rx = self.state_tx.subscribe();
|
||||
|
||||
// Ensure we are running.
|
||||
State::wait_for(&mut state_watch_rx, &[State::Started]).await?;
|
||||
|
||||
//log::debug!("read_rtp enter tracks tid {}", tid);
|
||||
let mut rtp_interceptor = None;
|
||||
//let mut ssrc = 0;
|
||||
{
|
||||
let tracks = self.tracks.read().await;
|
||||
for t in &*tracks {
|
||||
if t.track.tid() == tid {
|
||||
rtp_interceptor = t.stream.rtp_interceptor.clone();
|
||||
//ssrc = t.track.ssrc();
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
/*log::debug!(
|
||||
"read_rtp exit tracks with rtp_interceptor {} with tid {}",
|
||||
rtp_interceptor.is_some(),
|
||||
tid,
|
||||
);*/
|
||||
|
||||
if let Some(rtp_interceptor) = rtp_interceptor {
|
||||
let a = Attributes::new();
|
||||
//println!(
|
||||
// "read_rtp rtp_interceptor.read enter with tid {} ssrc {}",
|
||||
// tid, ssrc
|
||||
//);
|
||||
let mut current_state = *state_watch_rx.borrow();
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = state_watch_rx.changed() => {
|
||||
let new_state = *state_watch_rx.borrow();
|
||||
|
||||
if new_state == State::Stopped {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
current_state = new_state;
|
||||
}
|
||||
result = rtp_interceptor.read(b, &a) => {
|
||||
let result = result?;
|
||||
|
||||
if current_state == State::Paused {
|
||||
trace!("Dropping {} read bytes received while RTPReceiver was paused", result.0);
|
||||
continue;
|
||||
}
|
||||
return Ok(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//log::debug!("read_rtp exit tracks with ErrRTPReceiverWithSSRCTrackStreamNotFound");
|
||||
Err(Error::ErrRTPReceiverWithSSRCTrackStreamNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_parameters(&self) -> RTCRtpParameters {
|
||||
let mut parameters = self
|
||||
.media_engine
|
||||
.get_rtp_parameters_by_kind(self.kind, RTCRtpTransceiverDirection::Recvonly);
|
||||
|
||||
let transceiver_codecs = self.transceiver_codecs.load();
|
||||
if let Some(codecs) = &*transceiver_codecs {
|
||||
let mut c = codecs.lock().await;
|
||||
parameters.codecs =
|
||||
RTPReceiverInternal::get_codecs(&mut c, self.kind, &self.media_engine);
|
||||
}
|
||||
|
||||
parameters
|
||||
}
|
||||
|
||||
pub(crate) fn get_codecs(
|
||||
codecs: &mut [RTCRtpCodecParameters],
|
||||
kind: RTPCodecType,
|
||||
media_engine: &Arc<MediaEngine>,
|
||||
) -> Vec<RTCRtpCodecParameters> {
|
||||
let media_engine_codecs = media_engine.get_codecs_by_kind(kind);
|
||||
if codecs.is_empty() {
|
||||
return media_engine_codecs;
|
||||
}
|
||||
let mut filtered_codecs = vec![];
|
||||
for codec in codecs {
|
||||
let (c, match_type) = codec_parameters_fuzzy_search(codec, &media_engine_codecs);
|
||||
if match_type != CodecMatch::None {
|
||||
if codec.payload_type == 0 {
|
||||
codec.payload_type = c.payload_type;
|
||||
}
|
||||
filtered_codecs.push(codec.clone());
|
||||
}
|
||||
}
|
||||
|
||||
filtered_codecs
|
||||
}
|
||||
|
||||
// State
|
||||
|
||||
/// Get the current state and a receiver for the next state change.
|
||||
pub(crate) fn current_state(&self) -> State {
|
||||
*self.state_rx.borrow()
|
||||
}
|
||||
|
||||
pub(crate) fn start(&self) -> Result<()> {
|
||||
State::transition(State::Started, &self.state_tx)
|
||||
}
|
||||
|
||||
pub(crate) fn pause(&self) -> Result<()> {
|
||||
let current = self.current_state();
|
||||
|
||||
match current {
|
||||
State::Unstarted => State::transition(State::UnstartedPaused, &self.state_tx),
|
||||
State::Started => State::transition(State::Paused, &self.state_tx),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resume(&self) -> Result<()> {
|
||||
let current = self.current_state();
|
||||
|
||||
match current {
|
||||
State::UnstartedPaused => State::transition(State::Unstarted, &self.state_tx),
|
||||
State::Paused => State::transition(State::Started, &self.state_tx),
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn close(&self) -> Result<()> {
|
||||
State::transition(State::Stopped, &self.state_tx)
|
||||
}
|
||||
}
|
||||
|
||||
/// RTPReceiver allows an application to inspect the receipt of a TrackRemote
|
||||
pub struct RTCRtpReceiver {
|
||||
receive_mtu: usize,
|
||||
kind: RTPCodecType,
|
||||
transport: Arc<RTCDtlsTransport>,
|
||||
|
||||
pub internal: Arc<RTPReceiverInternal>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RTCRtpReceiver {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RTCRtpReceiver")
|
||||
.field("kind", &self.kind)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCRtpReceiver {
|
||||
pub fn new(
|
||||
receive_mtu: usize,
|
||||
kind: RTPCodecType,
|
||||
transport: Arc<RTCDtlsTransport>,
|
||||
media_engine: Arc<MediaEngine>,
|
||||
interceptor: Arc<dyn Interceptor + Send + Sync>,
|
||||
) -> Self {
|
||||
let (state_tx, state_rx) = watch::channel(State::Unstarted);
|
||||
|
||||
RTCRtpReceiver {
|
||||
receive_mtu,
|
||||
kind,
|
||||
transport: Arc::clone(&transport),
|
||||
|
||||
internal: Arc::new(RTPReceiverInternal {
|
||||
kind,
|
||||
|
||||
tracks: RwLock::new(vec![]),
|
||||
transport,
|
||||
media_engine,
|
||||
interceptor,
|
||||
|
||||
state_tx,
|
||||
state_rx,
|
||||
|
||||
transceiver_codecs: ArcSwapOption::new(None),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> RTPCodecType {
|
||||
self.kind
|
||||
}
|
||||
|
||||
pub(crate) fn set_transceiver_codecs(
|
||||
&self,
|
||||
codecs: Option<Arc<Mutex<Vec<RTCRtpCodecParameters>>>>,
|
||||
) {
|
||||
self.internal.transceiver_codecs.store(codecs);
|
||||
}
|
||||
|
||||
/// transport returns the currently-configured *DTLSTransport or nil
|
||||
/// if one has not yet been configured
|
||||
pub fn transport(&self) -> Arc<RTCDtlsTransport> {
|
||||
Arc::clone(&self.transport)
|
||||
}
|
||||
|
||||
/// get_parameters describes the current configuration for the encoding and
|
||||
/// transmission of media on the receiver's track.
|
||||
pub async fn get_parameters(&self) -> RTCRtpParameters {
|
||||
self.internal.get_parameters().await
|
||||
}
|
||||
|
||||
/// SetRTPParameters applies provided RTPParameters the RTPReceiver's tracks.
|
||||
/// This method is part of the ORTC API. It is not
|
||||
/// meant to be used together with the basic WebRTC API.
|
||||
/// The amount of provided codecs must match the number of tracks on the receiver.
|
||||
pub async fn set_rtp_parameters(&self, params: RTCRtpParameters) {
|
||||
let mut header_extensions = vec![];
|
||||
for h in ¶ms.header_extensions {
|
||||
header_extensions.push(RTPHeaderExtension {
|
||||
id: h.id,
|
||||
uri: h.uri.clone(),
|
||||
});
|
||||
}
|
||||
|
||||
let mut tracks = self.internal.tracks.write().await;
|
||||
for (idx, codec) in params.codecs.iter().enumerate() {
|
||||
let t = &mut tracks[idx];
|
||||
if let Some(stream_info) = &mut t.stream.stream_info {
|
||||
stream_info.rtp_header_extensions = header_extensions.clone();
|
||||
}
|
||||
|
||||
let current_track = &t.track;
|
||||
current_track.set_codec(codec.clone());
|
||||
current_track.set_params(params.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// track returns the RtpTransceiver TrackRemote
|
||||
pub async fn track(&self) -> Option<Arc<TrackRemote>> {
|
||||
let tracks = self.internal.tracks.read().await;
|
||||
if tracks.len() != 1 {
|
||||
None
|
||||
} else {
|
||||
tracks.first().map(|t| Arc::clone(&t.track))
|
||||
}
|
||||
}
|
||||
|
||||
/// tracks returns the RtpTransceiver traclockks
|
||||
/// A RTPReceiver to support Simulcast may now have multiple tracks
|
||||
pub async fn tracks(&self) -> Vec<Arc<TrackRemote>> {
|
||||
let tracks = self.internal.tracks.read().await;
|
||||
tracks.iter().map(|t| Arc::clone(&t.track)).collect()
|
||||
}
|
||||
|
||||
/// receive initialize the track and starts all the transports
|
||||
pub async fn receive(&self, parameters: &RTCRtpReceiveParameters) -> Result<()> {
|
||||
let receiver = Arc::downgrade(&self.internal);
|
||||
|
||||
let current_state = self.internal.current_state();
|
||||
if current_state.is_started() {
|
||||
return Err(Error::ErrRTPReceiverReceiveAlreadyCalled);
|
||||
}
|
||||
self.internal.start()?;
|
||||
|
||||
let (global_params, interceptor, media_engine) = {
|
||||
(
|
||||
self.internal.get_parameters().await,
|
||||
Arc::clone(&self.internal.interceptor),
|
||||
Arc::clone(&self.internal.media_engine),
|
||||
)
|
||||
};
|
||||
|
||||
let codec = if let Some(codec) = global_params.codecs.first() {
|
||||
codec.capability.clone()
|
||||
} else {
|
||||
RTCRtpCodecCapability::default()
|
||||
};
|
||||
|
||||
for encoding in ¶meters.encodings {
|
||||
let (stream_info, rtp_read_stream, rtp_interceptor, rtcp_read_stream, rtcp_interceptor) =
|
||||
if encoding.ssrc != 0 {
|
||||
let stream_info = create_stream_info(
|
||||
"".to_owned(),
|
||||
encoding.ssrc,
|
||||
0,
|
||||
codec.clone(),
|
||||
&global_params.header_extensions,
|
||||
);
|
||||
let (rtp_read_stream, rtp_interceptor, rtcp_read_stream, rtcp_interceptor) =
|
||||
self.transport
|
||||
.streams_for_ssrc(encoding.ssrc, &stream_info, &interceptor)
|
||||
.await?;
|
||||
|
||||
(
|
||||
Some(stream_info),
|
||||
Some(rtp_read_stream),
|
||||
Some(rtp_interceptor),
|
||||
Some(rtcp_read_stream),
|
||||
Some(rtcp_interceptor),
|
||||
)
|
||||
} else {
|
||||
(None, None, None, None, None)
|
||||
};
|
||||
|
||||
let t = TrackStreams {
|
||||
track: Arc::new(TrackRemote::new(
|
||||
self.receive_mtu,
|
||||
self.kind,
|
||||
encoding.ssrc,
|
||||
encoding.rid.clone(),
|
||||
receiver.clone(),
|
||||
Arc::clone(&media_engine),
|
||||
Arc::clone(&interceptor),
|
||||
)),
|
||||
stream: TrackStream {
|
||||
stream_info,
|
||||
rtp_read_stream,
|
||||
rtp_interceptor,
|
||||
rtcp_read_stream,
|
||||
rtcp_interceptor,
|
||||
},
|
||||
|
||||
repair_stream: TrackStream {
|
||||
stream_info: None,
|
||||
rtp_read_stream: None,
|
||||
rtp_interceptor: None,
|
||||
rtcp_read_stream: None,
|
||||
rtcp_interceptor: None,
|
||||
},
|
||||
};
|
||||
|
||||
{
|
||||
let mut tracks = self.internal.tracks.write().await;
|
||||
tracks.push(t);
|
||||
};
|
||||
|
||||
let rtx_ssrc = encoding.rtx.ssrc;
|
||||
if rtx_ssrc != 0 {
|
||||
let stream_info = create_stream_info(
|
||||
"".to_owned(),
|
||||
rtx_ssrc,
|
||||
0,
|
||||
codec.clone(),
|
||||
&global_params.header_extensions,
|
||||
);
|
||||
let (rtp_read_stream, rtp_interceptor, rtcp_read_stream, rtcp_interceptor) = self
|
||||
.transport
|
||||
.streams_for_ssrc(rtx_ssrc, &stream_info, &interceptor)
|
||||
.await?;
|
||||
|
||||
self.receive_for_rtx(
|
||||
rtx_ssrc,
|
||||
"".to_owned(),
|
||||
TrackStream {
|
||||
stream_info: Some(stream_info),
|
||||
rtp_read_stream: Some(rtp_read_stream),
|
||||
rtp_interceptor: Some(rtp_interceptor),
|
||||
rtcp_read_stream: Some(rtcp_read_stream),
|
||||
rtcp_interceptor: Some(rtcp_interceptor),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// read reads incoming RTCP for this RTPReceiver
|
||||
pub async fn read(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
self.internal.read(b).await
|
||||
}
|
||||
|
||||
/// read_simulcast reads incoming RTCP for this RTPReceiver for given rid
|
||||
pub async fn read_simulcast(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
rid: &str,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
self.internal.read_simulcast(b, rid).await
|
||||
}
|
||||
|
||||
/// read_rtcp is a convenience method that wraps Read and unmarshal for you.
|
||||
/// It also runs any configured interceptors.
|
||||
pub async fn read_rtcp(
|
||||
&self,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
self.internal.read_rtcp(self.receive_mtu).await
|
||||
}
|
||||
|
||||
/// read_simulcast_rtcp is a convenience method that wraps ReadSimulcast and unmarshal for you
|
||||
pub async fn read_simulcast_rtcp(
|
||||
&self,
|
||||
rid: &str,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
self.internal
|
||||
.read_simulcast_rtcp(rid, self.receive_mtu)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) async fn have_received(&self) -> bool {
|
||||
self.internal.current_state().is_started()
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self, incoming: &TrackDetails) {
|
||||
let mut encoding_size = incoming.ssrcs.len();
|
||||
if incoming.rids.len() >= encoding_size {
|
||||
encoding_size = incoming.rids.len();
|
||||
};
|
||||
|
||||
let mut encodings = vec![RTCRtpDecodingParameters::default(); encoding_size];
|
||||
for (i, encoding) in encodings.iter_mut().enumerate() {
|
||||
if incoming.rids.len() > i {
|
||||
encoding.rid = incoming.rids[i].clone();
|
||||
}
|
||||
if incoming.ssrcs.len() > i {
|
||||
encoding.ssrc = incoming.ssrcs[i];
|
||||
}
|
||||
|
||||
encoding.rtx.ssrc = incoming.repair_ssrc;
|
||||
}
|
||||
|
||||
if let Err(err) = self.receive(&RTCRtpReceiveParameters { encodings }).await {
|
||||
log::warn!("RTPReceiver Receive failed {}", err);
|
||||
return;
|
||||
}
|
||||
|
||||
// set track id and label early so they can be set as new track information
|
||||
// is received from the SDP.
|
||||
let is_unpaused = self.current_state() == State::Started;
|
||||
for track_remote in &self.tracks().await {
|
||||
track_remote.set_id(incoming.id.clone());
|
||||
track_remote.set_stream_id(incoming.stream_id.clone());
|
||||
|
||||
if is_unpaused {
|
||||
track_remote.fire_onunmute().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop irreversibly stops the RTPReceiver
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
let previous_state = self.internal.current_state();
|
||||
self.internal.close()?;
|
||||
|
||||
let mut errs = vec![];
|
||||
let was_ever_started = previous_state.is_started();
|
||||
if was_ever_started {
|
||||
let tracks = self.internal.tracks.write().await;
|
||||
for t in &*tracks {
|
||||
if let Some(rtcp_read_stream) = &t.stream.rtcp_read_stream {
|
||||
if let Err(err) = rtcp_read_stream.close().await {
|
||||
errs.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(rtp_read_stream) = &t.stream.rtp_read_stream {
|
||||
if let Err(err) = rtp_read_stream.close().await {
|
||||
errs.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(repair_rtcp_read_stream) = &t.repair_stream.rtcp_read_stream {
|
||||
if let Err(err) = repair_rtcp_read_stream.close().await {
|
||||
errs.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(repair_rtp_read_stream) = &t.repair_stream.rtp_read_stream {
|
||||
if let Err(err) = repair_rtp_read_stream.close().await {
|
||||
errs.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(stream_info) = &t.stream.stream_info {
|
||||
self.internal
|
||||
.interceptor
|
||||
.unbind_remote_stream(stream_info)
|
||||
.await;
|
||||
}
|
||||
|
||||
if let Some(repair_stream_info) = &t.repair_stream.stream_info {
|
||||
self.internal
|
||||
.interceptor
|
||||
.unbind_remote_stream(repair_stream_info)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
flatten_errs(errs)
|
||||
}
|
||||
|
||||
/// read_rtp should only be called by a track, this only exists so we can keep state in one place
|
||||
pub(crate) async fn read_rtp(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
tid: usize,
|
||||
) -> Result<(rtp::packet::Packet, Attributes)> {
|
||||
self.internal.read_rtp(b, tid).await
|
||||
}
|
||||
|
||||
/// receive_for_rid is the sibling of Receive expect for RIDs instead of SSRCs
|
||||
/// It populates all the internal state for the given RID
|
||||
pub(crate) async fn receive_for_rid(
|
||||
&self,
|
||||
rid: SmolStr,
|
||||
params: RTCRtpParameters,
|
||||
stream: TrackStream,
|
||||
) -> Result<Arc<TrackRemote>> {
|
||||
let mut tracks = self.internal.tracks.write().await;
|
||||
for t in &mut *tracks {
|
||||
if *t.track.rid() == rid {
|
||||
t.track.set_kind(self.kind);
|
||||
if let Some(codec) = params.codecs.first() {
|
||||
t.track.set_codec(codec.clone());
|
||||
}
|
||||
t.track.set_params(params.clone());
|
||||
t.track
|
||||
.set_ssrc(stream.stream_info.as_ref().map_or(0, |s| s.ssrc));
|
||||
t.stream = stream;
|
||||
return Ok(Arc::clone(&t.track));
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::ErrRTPReceiverForRIDTrackStreamNotFound)
|
||||
}
|
||||
|
||||
/// receiveForRtx starts a routine that processes the repair stream
|
||||
/// These packets aren't exposed to the user yet, but we need to process them for
|
||||
/// TWCC
|
||||
pub(crate) async fn receive_for_rtx(
|
||||
&self,
|
||||
ssrc: SSRC,
|
||||
rsid: String,
|
||||
repair_stream: TrackStream,
|
||||
) -> Result<()> {
|
||||
let mut tracks = self.internal.tracks.write().await;
|
||||
let l = tracks.len();
|
||||
for t in &mut *tracks {
|
||||
if (ssrc != 0 && l == 1) || t.track.rid() == rsid {
|
||||
t.repair_stream = repair_stream;
|
||||
|
||||
let receive_mtu = self.receive_mtu;
|
||||
let track = t.clone();
|
||||
tokio::spawn(async move {
|
||||
let a = Attributes::new();
|
||||
let mut b = vec![0u8; receive_mtu];
|
||||
while let Some(repair_rtp_interceptor) = &track.repair_stream.rtp_interceptor {
|
||||
//TODO: cancel repair_rtp_interceptor.read gracefully
|
||||
//println!("repair_rtp_interceptor read begin with ssrc={}", ssrc);
|
||||
if repair_rtp_interceptor.read(&mut b, &a).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::ErrRTPReceiverForRIDTrackStreamNotFound)
|
||||
}
|
||||
|
||||
// State
|
||||
|
||||
pub(crate) fn current_state(&self) -> State {
|
||||
self.internal.current_state()
|
||||
}
|
||||
|
||||
pub(crate) async fn pause(&self) -> Result<()> {
|
||||
self.internal.pause()?;
|
||||
|
||||
if !self.internal.current_state().is_started() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let streams = self.internal.tracks.read().await;
|
||||
|
||||
for stream in streams.iter() {
|
||||
// TODO: If we introduce futures as a direct dependency this and other futures could be
|
||||
// ran concurrently with [`join_all`](https://docs.rs/futures/0.3.21/futures/future/fn.join_all.html)
|
||||
stream.track.fire_onmute().await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn resume(&self) -> Result<()> {
|
||||
self.internal.resume()?;
|
||||
|
||||
if !self.internal.current_state().is_started() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let streams = self.internal.tracks.read().await;
|
||||
|
||||
for stream in streams.iter() {
|
||||
// TODO: If we introduce futures as a direct dependency this and other futures could be
|
||||
// ran concurrently with [`join_all`](https://docs.rs/futures/0.3.21/futures/future/fn.join_all.html)
|
||||
stream.track.fire_onunmute().await;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
use bytes::Bytes;
|
||||
use media::Sample;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time::Duration;
|
||||
use waitgroup::WaitGroup;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::{MIME_TYPE_OPUS, MIME_TYPE_VP8};
|
||||
use crate::error::Result;
|
||||
use crate::peer_connection::peer_connection_state::RTCPeerConnectionState;
|
||||
use crate::peer_connection::peer_connection_test::{
|
||||
close_pair_now, create_vnet_pair, signal_pair, until_connection_state,
|
||||
};
|
||||
use crate::rtp_transceiver::rtp_codec::RTCRtpHeaderExtensionParameters;
|
||||
use crate::rtp_transceiver::RTCPFeedback;
|
||||
use crate::track::track_local::track_local_static_sample::TrackLocalStaticSample;
|
||||
use crate::track::track_local::TrackLocal;
|
||||
|
||||
lazy_static! {
|
||||
static ref P: RTCRtpParameters = RTCRtpParameters {
|
||||
codecs: vec![RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_string(),
|
||||
clock_rate: 48000,
|
||||
channels: 2,
|
||||
sdp_fmtp_line: "minptime=10;useinbandfec=1".to_string(),
|
||||
rtcp_feedback: vec![RTCPFeedback {
|
||||
typ: "nack".to_owned(),
|
||||
parameter: "".to_owned(),
|
||||
}],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
}],
|
||||
header_extensions: vec![
|
||||
RTCRtpHeaderExtensionParameters {
|
||||
uri: "urn:ietf:params:rtp-hdrext:sdes:mid".to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpHeaderExtensionParameters {
|
||||
uri: "urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id".to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpHeaderExtensionParameters {
|
||||
uri: "urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id".to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
//use log::LevelFilter;
|
||||
//use std::io::Write;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_set_rtp_parameters() -> Result<()> {
|
||||
/*env_logger::Builder::new()
|
||||
.format(|buf, record| {
|
||||
writeln!(
|
||||
buf,
|
||||
"{}:{} [{}] {} - {}",
|
||||
record.file().unwrap_or("unknown"),
|
||||
record.line().unwrap_or(0),
|
||||
record.level(),
|
||||
chrono::Local::now().format("%H:%M:%S.%6f"),
|
||||
record.args()
|
||||
)
|
||||
})
|
||||
.filter(None, LevelFilter::Trace)
|
||||
.init();*/
|
||||
|
||||
let (mut sender, mut receiver, wan) = create_vnet_pair().await?;
|
||||
|
||||
let outgoing_track: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
sender.add_track(Arc::clone(&outgoing_track)).await?;
|
||||
|
||||
// Those parameters wouldn't make sense in a real application,
|
||||
// but for the sake of the test we just need different values.
|
||||
|
||||
let (seen_packet_tx, mut seen_packet_rx) = mpsc::channel::<()>(1);
|
||||
let seen_packet_tx = Arc::new(Mutex::new(Some(seen_packet_tx)));
|
||||
receiver.on_track(Box::new(move |_, receiver, _| {
|
||||
let seen_packet_tx2 = Arc::clone(&seen_packet_tx);
|
||||
Box::pin(async move {
|
||||
receiver.set_rtp_parameters(P.clone()).await;
|
||||
|
||||
if let Some(t) = receiver.track().await {
|
||||
let incoming_track_codecs = t.codec();
|
||||
|
||||
assert_eq!(P.header_extensions, t.params().header_extensions);
|
||||
assert_eq!(
|
||||
P.codecs[0].capability.mime_type,
|
||||
incoming_track_codecs.capability.mime_type
|
||||
);
|
||||
assert_eq!(
|
||||
P.codecs[0].capability.clock_rate,
|
||||
incoming_track_codecs.capability.clock_rate
|
||||
);
|
||||
assert_eq!(
|
||||
P.codecs[0].capability.channels,
|
||||
incoming_track_codecs.capability.channels
|
||||
);
|
||||
assert_eq!(
|
||||
P.codecs[0].capability.sdp_fmtp_line,
|
||||
incoming_track_codecs.capability.sdp_fmtp_line
|
||||
);
|
||||
assert_eq!(
|
||||
P.codecs[0].capability.rtcp_feedback,
|
||||
incoming_track_codecs.capability.rtcp_feedback
|
||||
);
|
||||
assert_eq!(P.codecs[0].payload_type, incoming_track_codecs.payload_type);
|
||||
|
||||
{
|
||||
let mut done = seen_packet_tx2.lock().await;
|
||||
done.take();
|
||||
}
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
let wg = WaitGroup::new();
|
||||
|
||||
until_connection_state(&mut sender, &wg, RTCPeerConnectionState::Connected).await;
|
||||
until_connection_state(&mut receiver, &wg, RTCPeerConnectionState::Connected).await;
|
||||
|
||||
signal_pair(&mut sender, &mut receiver).await?;
|
||||
|
||||
wg.wait().await;
|
||||
|
||||
if let Some(v) = outgoing_track
|
||||
.as_any()
|
||||
.downcast_ref::<TrackLocalStaticSample>()
|
||||
{
|
||||
v.write_sample(&Sample {
|
||||
data: Bytes::from_static(&[0xAA]),
|
||||
duration: Duration::from_secs(1),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
|
||||
let _ = seen_packet_rx.recv().await;
|
||||
{
|
||||
let mut w = wan.lock().await;
|
||||
w.stop().await?;
|
||||
}
|
||||
close_pair_now(&sender, &receiver).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Assert that SetReadDeadline works as expected
|
||||
// This test uses VNet since we must have zero loss
|
||||
#[tokio::test]
|
||||
async fn test_rtp_receiver_set_read_deadline() -> Result<()> {
|
||||
let (mut sender, mut receiver, wan) = create_vnet_pair().await?;
|
||||
|
||||
let track: Arc<dyn TrackLocal + Send + Sync> = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
sender.add_track(Arc::clone(&track)).await?;
|
||||
|
||||
let (seen_packet_tx, mut seen_packet_rx) = mpsc::channel::<()>(1);
|
||||
let seen_packet_tx = Arc::new(Mutex::new(Some(seen_packet_tx)));
|
||||
receiver.on_track(Box::new(move |track, receiver, _| {
|
||||
let seen_packet_tx2 = Arc::clone(&seen_packet_tx);
|
||||
Box::pin(async move {
|
||||
// First call will not error because we cache for probing
|
||||
let result = tokio::time::timeout(Duration::from_secs(1), track.read_rtp()).await;
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
" First call will not error because we cache for probing"
|
||||
);
|
||||
|
||||
let result = tokio::time::timeout(Duration::from_secs(1), track.read_rtp()).await;
|
||||
assert!(result.is_err());
|
||||
|
||||
let result = tokio::time::timeout(Duration::from_secs(1), receiver.read_rtcp()).await;
|
||||
assert!(result.is_err());
|
||||
|
||||
{
|
||||
let mut done = seen_packet_tx2.lock().await;
|
||||
done.take();
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
let wg = WaitGroup::new();
|
||||
until_connection_state(&mut sender, &wg, RTCPeerConnectionState::Connected).await;
|
||||
until_connection_state(&mut receiver, &wg, RTCPeerConnectionState::Connected).await;
|
||||
|
||||
signal_pair(&mut sender, &mut receiver).await?;
|
||||
|
||||
wg.wait().await;
|
||||
|
||||
if let Some(v) = track.as_any().downcast_ref::<TrackLocalStaticSample>() {
|
||||
v.write_sample(&Sample {
|
||||
data: Bytes::from_static(&[0xAA]),
|
||||
duration: Duration::from_secs(1),
|
||||
..Default::default()
|
||||
})
|
||||
.await?;
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
|
||||
let _ = seen_packet_rx.recv().await;
|
||||
{
|
||||
let mut w = wan.lock().await;
|
||||
w.stop().await?;
|
||||
}
|
||||
close_pair_now(&sender, &receiver).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
+544
@@ -0,0 +1,544 @@
|
||||
#[cfg(test)]
|
||||
mod rtp_sender_test;
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use ice::rand::generate_crypto_random_string;
|
||||
use interceptor::stream_info::StreamInfo;
|
||||
use interceptor::{Attributes, Interceptor, RTCPReader, RTPWriter};
|
||||
use tokio::sync::{mpsc, Mutex, Notify};
|
||||
use util::sync::Mutex as SyncMutex;
|
||||
|
||||
use super::srtp_writer_future::SequenceTransformer;
|
||||
use crate::api::media_engine::MediaEngine;
|
||||
use crate::dtls_transport::RTCDtlsTransport;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rtp_transceiver::rtp_codec::{RTCRtpCodecParameters, RTPCodecType};
|
||||
use crate::rtp_transceiver::rtp_transceiver_direction::RTCRtpTransceiverDirection;
|
||||
use crate::rtp_transceiver::srtp_writer_future::SrtpWriterFuture;
|
||||
use crate::rtp_transceiver::{
|
||||
create_stream_info, PayloadType, RTCRtpEncodingParameters, RTCRtpSendParameters,
|
||||
RTCRtpTransceiver, SSRC,
|
||||
};
|
||||
use crate::track::track_local::{
|
||||
InterceptorToTrackLocalWriter, TrackLocal, TrackLocalContext, TrackLocalWriter,
|
||||
};
|
||||
|
||||
pub(crate) struct RTPSenderInternal {
|
||||
pub(crate) send_called_rx: Mutex<mpsc::Receiver<()>>,
|
||||
pub(crate) stop_called_rx: Arc<Notify>,
|
||||
pub(crate) stop_called_signal: Arc<AtomicBool>,
|
||||
pub(crate) rtcp_interceptor: Mutex<Option<Arc<dyn RTCPReader + Send + Sync>>>,
|
||||
}
|
||||
|
||||
impl RTPSenderInternal {
|
||||
/// read reads incoming RTCP for this RTPReceiver
|
||||
async fn read(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let mut send_called_rx = self.send_called_rx.lock().await;
|
||||
|
||||
tokio::select! {
|
||||
_ = send_called_rx.recv() =>{
|
||||
let rtcp_interceptor = {
|
||||
let rtcp_interceptor = self.rtcp_interceptor.lock().await;
|
||||
rtcp_interceptor.clone()
|
||||
};
|
||||
if let Some(rtcp_interceptor) = rtcp_interceptor{
|
||||
let a = Attributes::new();
|
||||
tokio::select! {
|
||||
_ = self.stop_called_rx.notified() => {
|
||||
Err(Error::ErrClosedPipe)
|
||||
}
|
||||
result = rtcp_interceptor.read(b, &a) => {
|
||||
Ok(result?)
|
||||
}
|
||||
}
|
||||
}else{
|
||||
Err(Error::ErrInterceptorNotBind)
|
||||
}
|
||||
}
|
||||
_ = self.stop_called_rx.notified() =>{
|
||||
Err(Error::ErrClosedPipe)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// read_rtcp is a convenience method that wraps Read and unmarshals for you.
|
||||
async fn read_rtcp(
|
||||
&self,
|
||||
receive_mtu: usize,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let mut b = vec![0u8; receive_mtu];
|
||||
let (pkts, attributes) = self.read(&mut b).await?;
|
||||
|
||||
Ok((pkts, attributes))
|
||||
}
|
||||
}
|
||||
|
||||
/// RTPSender allows an application to control how a given Track is encoded and transmitted to a remote peer
|
||||
pub struct RTCRtpSender {
|
||||
pub(crate) track: Mutex<Option<Arc<dyn TrackLocal + Send + Sync>>>,
|
||||
|
||||
pub(crate) srtp_stream: Arc<SrtpWriterFuture>,
|
||||
pub(crate) stream_info: Mutex<StreamInfo>,
|
||||
seq_trans: Arc<SequenceTransformer>,
|
||||
|
||||
pub(crate) context: Mutex<TrackLocalContext>,
|
||||
|
||||
pub(crate) transport: Arc<RTCDtlsTransport>,
|
||||
|
||||
pub(crate) payload_type: PayloadType,
|
||||
pub(crate) ssrc: SSRC,
|
||||
receive_mtu: usize,
|
||||
|
||||
/// a transceiver sender since we can just check the
|
||||
/// transceiver negotiation status
|
||||
pub(crate) negotiated: AtomicBool,
|
||||
|
||||
pub(crate) media_engine: Arc<MediaEngine>,
|
||||
pub(crate) interceptor: Arc<dyn Interceptor + Send + Sync>,
|
||||
|
||||
pub(crate) id: String,
|
||||
|
||||
/// The id of the initial track, even if we later change to a different
|
||||
/// track id should be use when negotiating.
|
||||
pub(crate) initial_track_id: std::sync::Mutex<Option<String>>,
|
||||
/// AssociatedMediaStreamIds from the WebRTC specifications
|
||||
pub(crate) associated_media_stream_ids: std::sync::Mutex<Vec<String>>,
|
||||
|
||||
rtp_transceiver: SyncMutex<Option<Weak<RTCRtpTransceiver>>>,
|
||||
|
||||
send_called_tx: SyncMutex<Option<mpsc::Sender<()>>>,
|
||||
stop_called_tx: Arc<Notify>,
|
||||
stop_called_signal: Arc<AtomicBool>,
|
||||
|
||||
pub(crate) paused: Arc<AtomicBool>,
|
||||
|
||||
internal: Arc<RTPSenderInternal>,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for RTCRtpSender {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("RTCRtpSender")
|
||||
.field("id", &self.id)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCRtpSender {
|
||||
pub async fn new(
|
||||
receive_mtu: usize,
|
||||
track: Option<Arc<dyn TrackLocal + Send + Sync>>,
|
||||
transport: Arc<RTCDtlsTransport>,
|
||||
media_engine: Arc<MediaEngine>,
|
||||
interceptor: Arc<dyn Interceptor + Send + Sync>,
|
||||
start_paused: bool,
|
||||
) -> Self {
|
||||
let id = generate_crypto_random_string(
|
||||
32,
|
||||
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
||||
);
|
||||
let (send_called_tx, send_called_rx) = mpsc::channel(1);
|
||||
let stop_called_tx = Arc::new(Notify::new());
|
||||
let stop_called_rx = stop_called_tx.clone();
|
||||
let ssrc = rand::random::<u32>();
|
||||
let stop_called_signal = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let internal = Arc::new(RTPSenderInternal {
|
||||
send_called_rx: Mutex::new(send_called_rx),
|
||||
stop_called_rx,
|
||||
stop_called_signal: Arc::clone(&stop_called_signal),
|
||||
rtcp_interceptor: Mutex::new(None),
|
||||
});
|
||||
|
||||
let seq_trans = Arc::new(SequenceTransformer::new());
|
||||
let srtp_stream = Arc::new(SrtpWriterFuture {
|
||||
closed: AtomicBool::new(false),
|
||||
ssrc,
|
||||
rtp_sender: Arc::downgrade(&internal),
|
||||
rtp_transport: Arc::clone(&transport),
|
||||
rtcp_read_stream: Mutex::new(None),
|
||||
rtp_write_session: Mutex::new(None),
|
||||
seq_trans: Arc::clone(&seq_trans),
|
||||
});
|
||||
|
||||
let srtp_rtcp_reader = Arc::clone(&srtp_stream) as Arc<dyn RTCPReader + Send + Sync>;
|
||||
let rtcp_interceptor = interceptor.bind_rtcp_reader(srtp_rtcp_reader).await;
|
||||
{
|
||||
let mut internal_rtcp_interceptor = internal.rtcp_interceptor.lock().await;
|
||||
*internal_rtcp_interceptor = Some(rtcp_interceptor);
|
||||
}
|
||||
|
||||
let stream_ids = track
|
||||
.as_ref()
|
||||
.map(|track| vec![track.stream_id().to_string()])
|
||||
.unwrap_or_default();
|
||||
Self {
|
||||
track: Mutex::new(track),
|
||||
|
||||
srtp_stream,
|
||||
stream_info: Mutex::new(StreamInfo::default()),
|
||||
seq_trans,
|
||||
|
||||
context: Mutex::new(TrackLocalContext::default()),
|
||||
transport,
|
||||
|
||||
payload_type: 0,
|
||||
ssrc,
|
||||
receive_mtu,
|
||||
|
||||
negotiated: AtomicBool::new(false),
|
||||
|
||||
media_engine,
|
||||
interceptor,
|
||||
|
||||
id,
|
||||
initial_track_id: std::sync::Mutex::new(None),
|
||||
associated_media_stream_ids: std::sync::Mutex::new(stream_ids),
|
||||
|
||||
rtp_transceiver: SyncMutex::new(None),
|
||||
|
||||
send_called_tx: SyncMutex::new(Some(send_called_tx)),
|
||||
stop_called_tx,
|
||||
stop_called_signal,
|
||||
|
||||
paused: Arc::new(AtomicBool::new(start_paused)),
|
||||
|
||||
internal,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_negotiated(&self) -> bool {
|
||||
self.negotiated.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn set_negotiated(&self) {
|
||||
self.negotiated.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
pub(crate) fn set_rtp_transceiver(&self, rtp_transceiver: Option<Weak<RTCRtpTransceiver>>) {
|
||||
if let Some(t) = rtp_transceiver.as_ref().and_then(|t| t.upgrade()) {
|
||||
self.set_paused(!t.direction().has_send());
|
||||
}
|
||||
let mut tr = self.rtp_transceiver.lock();
|
||||
*tr = rtp_transceiver;
|
||||
}
|
||||
|
||||
pub(crate) fn set_paused(&self, paused: bool) {
|
||||
self.paused.store(paused, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
/// transport returns the currently-configured DTLSTransport
|
||||
/// if one has not yet been configured
|
||||
pub fn transport(&self) -> Arc<RTCDtlsTransport> {
|
||||
Arc::clone(&self.transport)
|
||||
}
|
||||
|
||||
/// get_parameters describes the current configuration for the encoding and
|
||||
/// transmission of media on the sender's track.
|
||||
pub async fn get_parameters(&self) -> RTCRtpSendParameters {
|
||||
let kind = {
|
||||
let track = self.track.lock().await;
|
||||
if let Some(t) = &*track {
|
||||
t.kind()
|
||||
} else {
|
||||
RTPCodecType::default()
|
||||
}
|
||||
};
|
||||
|
||||
let mut send_parameters = {
|
||||
RTCRtpSendParameters {
|
||||
rtp_parameters: self
|
||||
.media_engine
|
||||
.get_rtp_parameters_by_kind(kind, RTCRtpTransceiverDirection::Sendonly),
|
||||
encodings: vec![RTCRtpEncodingParameters {
|
||||
ssrc: self.ssrc,
|
||||
payload_type: self.payload_type,
|
||||
..Default::default()
|
||||
}],
|
||||
}
|
||||
};
|
||||
|
||||
let codecs = {
|
||||
let tr = self.rtp_transceiver.lock().clone();
|
||||
if let Some(t) = &tr {
|
||||
if let Some(t) = t.upgrade() {
|
||||
t.get_codecs().await
|
||||
} else {
|
||||
self.media_engine.get_codecs_by_kind(kind)
|
||||
}
|
||||
} else {
|
||||
self.media_engine.get_codecs_by_kind(kind)
|
||||
}
|
||||
};
|
||||
send_parameters.rtp_parameters.codecs = codecs;
|
||||
|
||||
send_parameters
|
||||
}
|
||||
|
||||
/// track returns the RTCRtpTransceiver track, or nil
|
||||
pub async fn track(&self) -> Option<Arc<dyn TrackLocal + Send + Sync>> {
|
||||
let track = self.track.lock().await;
|
||||
track.clone()
|
||||
}
|
||||
|
||||
/// replace_track replaces the track currently being used as the sender's source with a new TrackLocal.
|
||||
/// The new track must be of the same media kind (audio, video, etc) and switching the track should not
|
||||
/// require negotiation.
|
||||
pub async fn replace_track(
|
||||
&self,
|
||||
track: Option<Arc<dyn TrackLocal + Send + Sync>>,
|
||||
) -> Result<()> {
|
||||
if let Some(t) = &track {
|
||||
let tr = self.rtp_transceiver.lock();
|
||||
if let Some(r) = &*tr {
|
||||
if let Some(r) = r.upgrade() {
|
||||
if r.kind != t.kind() {
|
||||
return Err(Error::ErrRTPSenderNewTrackHasIncorrectKind);
|
||||
}
|
||||
} else {
|
||||
//TODO: what about None arc?
|
||||
}
|
||||
} else {
|
||||
//TODO: what about None tr?
|
||||
}
|
||||
}
|
||||
|
||||
if self.has_sent() {
|
||||
let t = {
|
||||
let t = self.track.lock().await;
|
||||
t.clone()
|
||||
};
|
||||
if let Some(t) = t {
|
||||
let context = self.context.lock().await;
|
||||
t.unbind(&context).await?;
|
||||
}
|
||||
}
|
||||
|
||||
if !self.has_sent() || track.is_none() {
|
||||
let mut t = self.track.lock().await;
|
||||
*t = track;
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let context = {
|
||||
let context = self.context.lock().await;
|
||||
context.clone()
|
||||
};
|
||||
|
||||
let result = if let Some(t) = &track {
|
||||
self.seq_trans.reset_offset();
|
||||
|
||||
let new_context = TrackLocalContext {
|
||||
id: context.id.clone(),
|
||||
params: self
|
||||
.media_engine
|
||||
.get_rtp_parameters_by_kind(t.kind(), RTCRtpTransceiverDirection::Sendonly),
|
||||
ssrc: context.ssrc,
|
||||
write_stream: context.write_stream.clone(),
|
||||
paused: self.paused.clone(),
|
||||
};
|
||||
|
||||
t.bind(&new_context).await
|
||||
} else {
|
||||
Err(Error::ErrRTPSenderTrackNil)
|
||||
};
|
||||
|
||||
match result {
|
||||
Err(err) => {
|
||||
// Re-bind the original track
|
||||
let track = self.track.lock().await;
|
||||
if let Some(t) = &*track {
|
||||
t.bind(&context).await?;
|
||||
}
|
||||
|
||||
Err(err)
|
||||
}
|
||||
Ok(codec) => {
|
||||
// Codec has changed
|
||||
if self.payload_type != codec.payload_type {
|
||||
let mut context = self.context.lock().await;
|
||||
context.params.codecs = vec![codec];
|
||||
}
|
||||
|
||||
{
|
||||
let mut t = self.track.lock().await;
|
||||
*t = track;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// send Attempts to set the parameters controlling the sending of media.
|
||||
pub async fn send(&self, parameters: &RTCRtpSendParameters) -> Result<()> {
|
||||
if self.has_sent() {
|
||||
return Err(Error::ErrRTPSenderSendAlreadyCalled);
|
||||
}
|
||||
|
||||
let write_stream = Arc::new(InterceptorToTrackLocalWriter::new(self.paused.clone()));
|
||||
let (context, stream_info) = {
|
||||
let track = self.track.lock().await;
|
||||
let mut context = TrackLocalContext {
|
||||
id: self.id.clone(),
|
||||
params: self.media_engine.get_rtp_parameters_by_kind(
|
||||
if let Some(t) = &*track {
|
||||
t.kind()
|
||||
} else {
|
||||
RTPCodecType::default()
|
||||
},
|
||||
RTCRtpTransceiverDirection::Sendonly,
|
||||
),
|
||||
ssrc: parameters.encodings[0].ssrc,
|
||||
write_stream: Some(
|
||||
Arc::clone(&write_stream) as Arc<dyn TrackLocalWriter + Send + Sync>
|
||||
),
|
||||
paused: self.paused.clone(),
|
||||
};
|
||||
|
||||
let codec = if let Some(t) = &*track {
|
||||
t.bind(&context).await?
|
||||
} else {
|
||||
RTCRtpCodecParameters::default()
|
||||
};
|
||||
let payload_type = codec.payload_type;
|
||||
let capability = codec.capability.clone();
|
||||
context.params.codecs = vec![codec];
|
||||
let stream_info = create_stream_info(
|
||||
self.id.clone(),
|
||||
parameters.encodings[0].ssrc,
|
||||
payload_type,
|
||||
capability,
|
||||
¶meters.rtp_parameters.header_extensions,
|
||||
);
|
||||
|
||||
(context, stream_info)
|
||||
};
|
||||
|
||||
let srtp_rtp_writer = Arc::clone(&self.srtp_stream) as Arc<dyn RTPWriter + Send + Sync>;
|
||||
let rtp_interceptor = self
|
||||
.interceptor
|
||||
.bind_local_stream(&stream_info, srtp_rtp_writer)
|
||||
.await;
|
||||
{
|
||||
let mut interceptor_rtp_writer = write_stream.interceptor_rtp_writer.lock().await;
|
||||
*interceptor_rtp_writer = Some(rtp_interceptor);
|
||||
}
|
||||
|
||||
{
|
||||
let mut ctx = self.context.lock().await;
|
||||
*ctx = context;
|
||||
}
|
||||
{
|
||||
let mut si = self.stream_info.lock().await;
|
||||
*si = stream_info;
|
||||
}
|
||||
|
||||
{
|
||||
let mut send_called_tx = self.send_called_tx.lock();
|
||||
send_called_tx.take();
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// stop irreversibly stops the RTPSender
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
if self.stop_called_signal.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
self.stop_called_signal.store(true, Ordering::SeqCst);
|
||||
self.stop_called_tx.notify_waiters();
|
||||
|
||||
if !self.has_sent() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.replace_track(None).await?;
|
||||
|
||||
{
|
||||
let stream_info = self.stream_info.lock().await;
|
||||
self.interceptor.unbind_local_stream(&stream_info).await;
|
||||
}
|
||||
|
||||
self.srtp_stream.close().await
|
||||
}
|
||||
|
||||
/// read reads incoming RTCP for this RTPReceiver
|
||||
pub async fn read(
|
||||
&self,
|
||||
b: &mut [u8],
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
self.internal.read(b).await
|
||||
}
|
||||
|
||||
/// read_rtcp is a convenience method that wraps Read and unmarshals for you.
|
||||
pub async fn read_rtcp(
|
||||
&self,
|
||||
) -> Result<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
self.internal.read_rtcp(self.receive_mtu).await
|
||||
}
|
||||
|
||||
/// Enables overriding outgoing `RTP` packets' `sequence number`s.
|
||||
///
|
||||
/// Must be called once before any data sent or never called at all.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Errors if this [`RTCRtpSender`] has started to send data or sequence
|
||||
/// transforming has been already enabled.
|
||||
pub fn enable_seq_transformer(&self) -> Result<()> {
|
||||
self.seq_trans.enable()
|
||||
}
|
||||
|
||||
/// has_sent tells if data has been ever sent for this instance
|
||||
pub(crate) fn has_sent(&self) -> bool {
|
||||
let send_called_tx = self.send_called_tx.lock();
|
||||
send_called_tx.is_none()
|
||||
}
|
||||
|
||||
/// has_stopped tells if stop has been called
|
||||
pub(crate) async fn has_stopped(&self) -> bool {
|
||||
self.stop_called_signal.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn initial_track_id(&self) -> Option<String> {
|
||||
let lock = self.initial_track_id.lock().unwrap();
|
||||
|
||||
lock.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn set_initial_track_id(&self, id: String) -> Result<()> {
|
||||
let mut lock = self.initial_track_id.lock().unwrap();
|
||||
|
||||
if lock.is_some() {
|
||||
return Err(Error::ErrSenderInitialTrackIdAlreadySet);
|
||||
}
|
||||
|
||||
*lock = Some(id);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn associate_media_stream_id(&self, id: String) -> bool {
|
||||
let mut lock = self.associated_media_stream_ids.lock().unwrap();
|
||||
|
||||
if lock.contains(&id) {
|
||||
return false;
|
||||
}
|
||||
|
||||
lock.push(id);
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn associated_media_stream_ids(&self) -> Vec<String> {
|
||||
let lock = self.associated_media_stream_ids.lock().unwrap();
|
||||
|
||||
lock.clone()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,336 @@
|
||||
use std::sync::atomic::AtomicU64;
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::time::Duration;
|
||||
use waitgroup::WaitGroup;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::{MIME_TYPE_H264, MIME_TYPE_OPUS, MIME_TYPE_VP8, MIME_TYPE_VP9};
|
||||
use crate::api::setting_engine::SettingEngine;
|
||||
use crate::api::APIBuilder;
|
||||
use crate::error::Result;
|
||||
use crate::peer_connection::peer_connection_state::RTCPeerConnectionState;
|
||||
use crate::peer_connection::peer_connection_test::{
|
||||
close_pair_now, create_vnet_pair, new_pair, send_video_until_done, signal_pair,
|
||||
until_connection_state,
|
||||
};
|
||||
use crate::rtp_transceiver::rtp_codec::RTCRtpCodecCapability;
|
||||
use crate::track::track_local::track_local_static_sample::TrackLocalStaticSample;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_sender_replace_track() -> Result<()> {
|
||||
let mut s = SettingEngine::default();
|
||||
s.disable_srtp_replay_protection(true);
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
|
||||
let api = APIBuilder::new()
|
||||
.with_setting_engine(s)
|
||||
.with_media_engine(m)
|
||||
.build();
|
||||
|
||||
let (mut sender, mut receiver) = new_pair(&api).await?;
|
||||
|
||||
let track_a = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let track_b = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_H264.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let rtp_sender = sender
|
||||
.add_track(Arc::clone(&track_a) as Arc<dyn TrackLocal + Send + Sync>)
|
||||
.await?;
|
||||
|
||||
let (seen_packet_a_tx, seen_packet_a_rx) = mpsc::channel::<()>(1);
|
||||
let (seen_packet_b_tx, seen_packet_b_rx) = mpsc::channel::<()>(1);
|
||||
|
||||
let seen_packet_a_tx = Arc::new(seen_packet_a_tx);
|
||||
let seen_packet_b_tx = Arc::new(seen_packet_b_tx);
|
||||
let on_track_count = Arc::new(AtomicU64::new(0));
|
||||
receiver.on_track(Box::new(move |track, _, _| {
|
||||
assert_eq!(on_track_count.fetch_add(1, Ordering::SeqCst), 0);
|
||||
let seen_packet_a_tx2 = Arc::clone(&seen_packet_a_tx);
|
||||
let seen_packet_b_tx2 = Arc::clone(&seen_packet_b_tx);
|
||||
Box::pin(async move {
|
||||
let pkt = match track.read_rtp().await {
|
||||
Ok((pkt, _)) => pkt,
|
||||
Err(err) => {
|
||||
//assert!(errors.Is(io.EOF, err))
|
||||
log::debug!("{}", err);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let last = pkt.payload[pkt.payload.len() - 1];
|
||||
if last == 0xAA {
|
||||
assert_eq!(track.codec().capability.mime_type, MIME_TYPE_VP8);
|
||||
let _ = seen_packet_a_tx2.send(()).await;
|
||||
} else if last == 0xBB {
|
||||
assert_eq!(track.codec().capability.mime_type, MIME_TYPE_H264);
|
||||
let _ = seen_packet_b_tx2.send(()).await;
|
||||
} else {
|
||||
panic!("Unexpected RTP Data {last:02x}");
|
||||
}
|
||||
})
|
||||
}));
|
||||
|
||||
signal_pair(&mut sender, &mut receiver).await?;
|
||||
|
||||
// Block Until packet with 0xAA has been seen
|
||||
tokio::spawn(async move {
|
||||
send_video_until_done(
|
||||
seen_packet_a_rx,
|
||||
vec![track_a],
|
||||
Bytes::from_static(&[0xAA]),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
rtp_sender
|
||||
.replace_track(Some(
|
||||
Arc::clone(&track_b) as Arc<dyn TrackLocal + Send + Sync>
|
||||
))
|
||||
.await?;
|
||||
|
||||
// Block Until packet with 0xBB has been seen
|
||||
tokio::spawn(async move {
|
||||
send_video_until_done(
|
||||
seen_packet_b_rx,
|
||||
vec![track_b],
|
||||
Bytes::from_static(&[0xBB]),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
close_pair_now(&sender, &receiver).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_sender_get_parameters() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut offerer, mut answerer) = new_pair(&api).await?;
|
||||
|
||||
let rtp_transceiver = offerer
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
signal_pair(&mut offerer, &mut answerer).await?;
|
||||
|
||||
let sender = rtp_transceiver.sender().await;
|
||||
let parameters = sender.get_parameters().await;
|
||||
assert_ne!(0, parameters.rtp_parameters.codecs.len());
|
||||
assert_eq!(1, parameters.encodings.len());
|
||||
assert_eq!(sender.ssrc, parameters.encodings[0].ssrc);
|
||||
|
||||
close_pair_now(&offerer, &answerer).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_sender_set_read_deadline() -> Result<()> {
|
||||
let (mut sender, mut receiver, wan) = create_vnet_pair().await?;
|
||||
|
||||
let track = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let rtp_sender = sender
|
||||
.add_track(Arc::clone(&track) as Arc<dyn TrackLocal + Send + Sync>)
|
||||
.await?;
|
||||
|
||||
let peer_connections_connected = WaitGroup::new();
|
||||
until_connection_state(
|
||||
&mut sender,
|
||||
&peer_connections_connected,
|
||||
RTCPeerConnectionState::Connected,
|
||||
)
|
||||
.await;
|
||||
until_connection_state(
|
||||
&mut receiver,
|
||||
&peer_connections_connected,
|
||||
RTCPeerConnectionState::Connected,
|
||||
)
|
||||
.await;
|
||||
|
||||
signal_pair(&mut sender, &mut receiver).await?;
|
||||
|
||||
peer_connections_connected.wait().await;
|
||||
|
||||
let result = tokio::time::timeout(Duration::from_secs(1), rtp_sender.read_rtcp()).await;
|
||||
assert!(result.is_err());
|
||||
|
||||
{
|
||||
let mut w = wan.lock().await;
|
||||
w.stop().await?;
|
||||
}
|
||||
close_pair_now(&sender, &receiver).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_sender_replace_track_invalid_track_kind_change() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut sender, mut receiver) = new_pair(&api).await?;
|
||||
|
||||
let track_a = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let track_b = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"audio".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let rtp_sender = sender
|
||||
.add_track(Arc::clone(&track_a) as Arc<dyn TrackLocal + Send + Sync>)
|
||||
.await?;
|
||||
|
||||
signal_pair(&mut sender, &mut receiver).await?;
|
||||
|
||||
let (seen_packet_tx, seen_packet_rx) = mpsc::channel::<()>(1);
|
||||
let seen_packet_tx = Arc::new(seen_packet_tx);
|
||||
receiver.on_track(Box::new(move |_, _, _| {
|
||||
let seen_packet_tx2 = Arc::clone(&seen_packet_tx);
|
||||
Box::pin(async move {
|
||||
let _ = seen_packet_tx2.send(()).await;
|
||||
})
|
||||
}));
|
||||
|
||||
tokio::spawn(async move {
|
||||
send_video_until_done(
|
||||
seen_packet_rx,
|
||||
vec![track_a],
|
||||
Bytes::from_static(&[0xAA]),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
if let Err(err) = rtp_sender.replace_track(Some(track_b)).await {
|
||||
assert_eq!(err, Error::ErrRTPSenderNewTrackHasIncorrectKind);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
|
||||
close_pair_now(&sender, &receiver).await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_sender_replace_track_invalid_codec_change() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
|
||||
let (mut sender, mut receiver) = new_pair(&api).await?;
|
||||
|
||||
let track_a = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let track_b = Arc::new(TrackLocalStaticSample::new(
|
||||
RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
"video".to_owned(),
|
||||
"webrtc-rs".to_owned(),
|
||||
));
|
||||
|
||||
let rtp_sender = sender
|
||||
.add_track(Arc::clone(&track_a) as Arc<dyn TrackLocal + Send + Sync>)
|
||||
.await?;
|
||||
|
||||
{
|
||||
let tr = rtp_sender.rtp_transceiver.lock();
|
||||
if let Some(t) = &*tr {
|
||||
if let Some(t) = t.upgrade() {
|
||||
t.set_codec_preferences(vec![RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
..Default::default()
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
}])
|
||||
.await?;
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
signal_pair(&mut sender, &mut receiver).await?;
|
||||
|
||||
let (seen_packet_tx, seen_packet_rx) = mpsc::channel::<()>(1);
|
||||
let seen_packet_tx = Arc::new(seen_packet_tx);
|
||||
receiver.on_track(Box::new(move |_, _, _| {
|
||||
let seen_packet_tx2 = Arc::clone(&seen_packet_tx);
|
||||
Box::pin(async move {
|
||||
let _ = seen_packet_tx2.send(()).await;
|
||||
})
|
||||
}));
|
||||
|
||||
tokio::spawn(async move {
|
||||
send_video_until_done(
|
||||
seen_packet_rx,
|
||||
vec![track_a],
|
||||
Bytes::from_static(&[0xAA]),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
});
|
||||
|
||||
if let Err(err) = rtp_sender.replace_track(Some(track_b)).await {
|
||||
assert_eq!(err, Error::ErrUnsupportedCodec);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
|
||||
close_pair_now(&sender, &receiver).await;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
use std::fmt;
|
||||
|
||||
/// RTPTransceiverDirection indicates the direction of the RTPTransceiver.
|
||||
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
|
||||
pub enum RTCRtpTransceiverDirection {
|
||||
Unspecified,
|
||||
|
||||
/// Sendrecv indicates the RTPSender will offer
|
||||
/// to send RTP and RTPReceiver the will offer to receive RTP.
|
||||
Sendrecv,
|
||||
|
||||
/// Sendonly indicates the RTPSender will offer to send RTP.
|
||||
Sendonly,
|
||||
|
||||
/// Recvonly indicates the RTPReceiver the will offer to receive RTP.
|
||||
Recvonly,
|
||||
|
||||
/// Inactive indicates the RTPSender won't offer
|
||||
/// to send RTP and RTPReceiver the won't offer to receive RTP.
|
||||
Inactive,
|
||||
}
|
||||
|
||||
const RTP_TRANSCEIVER_DIRECTION_SENDRECV_STR: &str = "sendrecv";
|
||||
const RTP_TRANSCEIVER_DIRECTION_SENDONLY_STR: &str = "sendonly";
|
||||
const RTP_TRANSCEIVER_DIRECTION_RECVONLY_STR: &str = "recvonly";
|
||||
const RTP_TRANSCEIVER_DIRECTION_INACTIVE_STR: &str = "inactive";
|
||||
|
||||
/// defines a procedure for creating a new
|
||||
/// RTPTransceiverDirection from a raw string naming the transceiver direction.
|
||||
impl From<&str> for RTCRtpTransceiverDirection {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
RTP_TRANSCEIVER_DIRECTION_SENDRECV_STR => RTCRtpTransceiverDirection::Sendrecv,
|
||||
RTP_TRANSCEIVER_DIRECTION_SENDONLY_STR => RTCRtpTransceiverDirection::Sendonly,
|
||||
RTP_TRANSCEIVER_DIRECTION_RECVONLY_STR => RTCRtpTransceiverDirection::Recvonly,
|
||||
RTP_TRANSCEIVER_DIRECTION_INACTIVE_STR => RTCRtpTransceiverDirection::Inactive,
|
||||
_ => RTCRtpTransceiverDirection::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCRtpTransceiverDirection {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCRtpTransceiverDirection::Sendrecv,
|
||||
2 => RTCRtpTransceiverDirection::Sendonly,
|
||||
3 => RTCRtpTransceiverDirection::Recvonly,
|
||||
4 => RTCRtpTransceiverDirection::Inactive,
|
||||
_ => RTCRtpTransceiverDirection::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCRtpTransceiverDirection {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match *self {
|
||||
RTCRtpTransceiverDirection::Sendrecv => {
|
||||
write!(f, "{RTP_TRANSCEIVER_DIRECTION_SENDRECV_STR}")
|
||||
}
|
||||
RTCRtpTransceiverDirection::Sendonly => {
|
||||
write!(f, "{RTP_TRANSCEIVER_DIRECTION_SENDONLY_STR}")
|
||||
}
|
||||
RTCRtpTransceiverDirection::Recvonly => {
|
||||
write!(f, "{RTP_TRANSCEIVER_DIRECTION_RECVONLY_STR}")
|
||||
}
|
||||
RTCRtpTransceiverDirection::Inactive => {
|
||||
write!(f, "{RTP_TRANSCEIVER_DIRECTION_INACTIVE_STR}")
|
||||
}
|
||||
_ => write!(f, "{}", crate::UNSPECIFIED_STR),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl RTCRtpTransceiverDirection {
|
||||
/// reverse indicate the opposite direction
|
||||
pub fn reverse(&self) -> RTCRtpTransceiverDirection {
|
||||
match *self {
|
||||
RTCRtpTransceiverDirection::Sendonly => RTCRtpTransceiverDirection::Recvonly,
|
||||
RTCRtpTransceiverDirection::Recvonly => RTCRtpTransceiverDirection::Sendonly,
|
||||
_ => *self,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn intersect(&self, other: RTCRtpTransceiverDirection) -> RTCRtpTransceiverDirection {
|
||||
Self::from_send_recv(
|
||||
self.has_send() && other.has_send(),
|
||||
self.has_recv() && other.has_recv(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn from_send_recv(send: bool, recv: bool) -> RTCRtpTransceiverDirection {
|
||||
match (send, recv) {
|
||||
(true, true) => Self::Sendrecv,
|
||||
(true, false) => Self::Sendonly,
|
||||
(false, true) => Self::Recvonly,
|
||||
(false, false) => Self::Inactive,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn has_send(&self) -> bool {
|
||||
matches!(self, Self::Sendrecv | Self::Sendonly)
|
||||
}
|
||||
|
||||
pub fn has_recv(&self) -> bool {
|
||||
matches!(self, Self::Sendrecv | Self::Recvonly)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_rtp_transceiver_direction() {
|
||||
let tests = vec![
|
||||
("Unspecified", RTCRtpTransceiverDirection::Unspecified),
|
||||
("sendrecv", RTCRtpTransceiverDirection::Sendrecv),
|
||||
("sendonly", RTCRtpTransceiverDirection::Sendonly),
|
||||
("recvonly", RTCRtpTransceiverDirection::Recvonly),
|
||||
("inactive", RTCRtpTransceiverDirection::Inactive),
|
||||
];
|
||||
|
||||
for (ct_str, expected_type) in tests {
|
||||
assert_eq!(RTCRtpTransceiverDirection::from(ct_str), expected_type);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtp_transceiver_direction_string() {
|
||||
let tests = vec![
|
||||
(RTCRtpTransceiverDirection::Unspecified, "Unspecified"),
|
||||
(RTCRtpTransceiverDirection::Sendrecv, "sendrecv"),
|
||||
(RTCRtpTransceiverDirection::Sendonly, "sendonly"),
|
||||
(RTCRtpTransceiverDirection::Recvonly, "recvonly"),
|
||||
(RTCRtpTransceiverDirection::Inactive, "inactive"),
|
||||
];
|
||||
|
||||
for (d, expected_string) in tests {
|
||||
assert_eq!(d.to_string(), expected_string);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtp_transceiver_has_send() {
|
||||
let tests = vec![
|
||||
(RTCRtpTransceiverDirection::Unspecified, false),
|
||||
(RTCRtpTransceiverDirection::Sendrecv, true),
|
||||
(RTCRtpTransceiverDirection::Sendonly, true),
|
||||
(RTCRtpTransceiverDirection::Recvonly, false),
|
||||
(RTCRtpTransceiverDirection::Inactive, false),
|
||||
];
|
||||
|
||||
for (d, expected_value) in tests {
|
||||
assert_eq!(d.has_send(), expected_value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtp_transceiver_has_recv() {
|
||||
let tests = vec![
|
||||
(RTCRtpTransceiverDirection::Unspecified, false),
|
||||
(RTCRtpTransceiverDirection::Sendrecv, true),
|
||||
(RTCRtpTransceiverDirection::Sendonly, false),
|
||||
(RTCRtpTransceiverDirection::Recvonly, true),
|
||||
(RTCRtpTransceiverDirection::Inactive, false),
|
||||
];
|
||||
|
||||
for (d, expected_value) in tests {
|
||||
assert_eq!(d.has_recv(), expected_value);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtp_transceiver_from_send_recv() {
|
||||
let tests = vec![
|
||||
(RTCRtpTransceiverDirection::Sendrecv, (true, true)),
|
||||
(RTCRtpTransceiverDirection::Sendonly, (true, false)),
|
||||
(RTCRtpTransceiverDirection::Recvonly, (false, true)),
|
||||
(RTCRtpTransceiverDirection::Inactive, (false, false)),
|
||||
];
|
||||
|
||||
for (expected_value, (send, recv)) in tests {
|
||||
assert_eq!(
|
||||
RTCRtpTransceiverDirection::from_send_recv(send, recv),
|
||||
expected_value
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_rtp_transceiver_intersect() {
|
||||
use RTCRtpTransceiverDirection::*;
|
||||
|
||||
let tests = vec![
|
||||
((Sendrecv, Recvonly), Recvonly),
|
||||
((Sendrecv, Sendonly), Sendonly),
|
||||
((Sendrecv, Inactive), Inactive),
|
||||
((Sendonly, Inactive), Inactive),
|
||||
((Recvonly, Inactive), Inactive),
|
||||
((Recvonly, Sendrecv), Recvonly),
|
||||
((Sendonly, Sendrecv), Sendonly),
|
||||
((Sendonly, Recvonly), Inactive),
|
||||
((Recvonly, Recvonly), Recvonly),
|
||||
];
|
||||
|
||||
for ((a, b), expected_direction) in tests {
|
||||
assert_eq!(a.intersect(b), expected_direction);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,356 @@
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
|
||||
use super::*;
|
||||
use crate::api::media_engine::{MIME_TYPE_OPUS, MIME_TYPE_VP8, MIME_TYPE_VP9};
|
||||
use crate::api::APIBuilder;
|
||||
use crate::dtls_transport::RTCDtlsTransport;
|
||||
use crate::peer_connection::configuration::RTCConfiguration;
|
||||
use crate::peer_connection::peer_connection_test::{close_pair_now, create_vnet_pair};
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_transceiver_set_codec_preferences() -> Result<()> {
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.push_codecs(m.video_codecs.clone(), RTPCodecType::Video)
|
||||
.await;
|
||||
m.push_codecs(m.audio_codecs.clone(), RTPCodecType::Audio)
|
||||
.await;
|
||||
|
||||
let media_video_codecs = m.video_codecs.clone();
|
||||
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
let interceptor = api.interceptor_registry.build("")?;
|
||||
let transport = Arc::new(RTCDtlsTransport::default());
|
||||
let receiver = Arc::new(api.new_rtp_receiver(
|
||||
RTPCodecType::Video,
|
||||
Arc::clone(&transport),
|
||||
Arc::clone(&interceptor),
|
||||
));
|
||||
|
||||
let sender = Arc::new(
|
||||
api.new_rtp_sender(None, Arc::clone(&transport), Arc::clone(&interceptor))
|
||||
.await,
|
||||
);
|
||||
|
||||
let tr = RTCRtpTransceiver::new(
|
||||
receiver,
|
||||
sender,
|
||||
RTCRtpTransceiverDirection::Unspecified,
|
||||
RTPCodecType::Video,
|
||||
media_video_codecs.clone(),
|
||||
Arc::clone(&api.media_engine),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(&tr.get_codecs().await, &media_video_codecs);
|
||||
|
||||
let fail_test_cases = vec![
|
||||
vec![RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_string(),
|
||||
clock_rate: 48000,
|
||||
channels: 2,
|
||||
sdp_fmtp_line: "minptime=10;useinbandfec=1".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
}],
|
||||
vec![
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_string(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_OPUS.to_string(),
|
||||
clock_rate: 48000,
|
||||
channels: 2,
|
||||
sdp_fmtp_line: "minptime=10;useinbandfec=1".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 111,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
for test_case in fail_test_cases {
|
||||
if let Err(err) = tr.set_codec_preferences(test_case).await {
|
||||
assert_eq!(err, Error::ErrRTPTransceiverCodecUnsupported);
|
||||
} else {
|
||||
panic!();
|
||||
}
|
||||
}
|
||||
|
||||
let success_test_cases = vec![
|
||||
vec![RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_string(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
}],
|
||||
vec![
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_string(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 96,
|
||||
..Default::default()
|
||||
},
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP9.to_string(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "profile-id=0".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 98,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
];
|
||||
|
||||
for test_case in success_test_cases {
|
||||
tr.set_codec_preferences(test_case).await?;
|
||||
}
|
||||
|
||||
tr.set_codec_preferences(vec![]).await?;
|
||||
assert_ne!(0, tr.get_codecs().await.len());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Assert that SetCodecPreferences properly filters codecs and PayloadTypes are respected
|
||||
#[tokio::test]
|
||||
async fn test_rtp_transceiver_set_codec_preferences_payload_type() -> Result<()> {
|
||||
let test_codec = RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: "video/test_codec".to_string(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 50,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
let offer_pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
|
||||
let mut m = MediaEngine::default();
|
||||
m.register_default_codecs()?;
|
||||
m.register_codec(test_codec.clone(), RTPCodecType::Video)?;
|
||||
let api = APIBuilder::new().with_media_engine(m).build();
|
||||
let answer_pc = api.new_peer_connection(RTCConfiguration::default()).await?;
|
||||
|
||||
let _ = offer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let answer_transceiver = answer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
answer_transceiver
|
||||
.set_codec_preferences(vec![
|
||||
test_codec,
|
||||
RTCRtpCodecParameters {
|
||||
capability: RTCRtpCodecCapability {
|
||||
mime_type: MIME_TYPE_VP8.to_string(),
|
||||
clock_rate: 90000,
|
||||
channels: 0,
|
||||
sdp_fmtp_line: "".to_string(),
|
||||
rtcp_feedback: vec![],
|
||||
},
|
||||
payload_type: 51,
|
||||
..Default::default()
|
||||
},
|
||||
])
|
||||
.await?;
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
|
||||
offer_pc.set_local_description(offer.clone()).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
|
||||
// VP8 with proper PayloadType
|
||||
assert!(
|
||||
answer.sdp.contains("a=rtpmap:51 VP8/90000"),
|
||||
"{}",
|
||||
answer.sdp
|
||||
);
|
||||
|
||||
// test_codec is ignored since offerer doesn't support
|
||||
assert!(!answer.sdp.contains("test_codec"));
|
||||
|
||||
close_pair_now(&offer_pc, &answer_pc).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_transceiver_direction_change() -> Result<()> {
|
||||
let (offer_pc, answer_pc, _) = create_vnet_pair().await?;
|
||||
|
||||
let offer_transceiver = offer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let _ = answer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
|
||||
offer_pc.set_local_description(offer.clone()).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
assert!(answer.sdp.contains("a=sendrecv"),);
|
||||
answer_pc.set_local_description(answer.clone()).await?;
|
||||
offer_pc.set_remote_description(answer).await?;
|
||||
|
||||
offer_transceiver
|
||||
.set_direction(RTCRtpTransceiverDirection::Inactive)
|
||||
.await;
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
assert!(offer.sdp.contains("a=inactive"),);
|
||||
|
||||
offer_pc.set_local_description(offer.clone()).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
assert!(answer.sdp.contains("a=inactive"),);
|
||||
offer_pc.set_remote_description(answer).await?;
|
||||
|
||||
close_pair_now(&offer_pc, &answer_pc).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_rtp_transceiver_set_direction_causing_negotiation() -> Result<()> {
|
||||
let (offer_pc, answer_pc, _) = create_vnet_pair().await?;
|
||||
|
||||
let count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
{
|
||||
let count = count.clone();
|
||||
offer_pc.on_negotiation_needed(Box::new(move || {
|
||||
let count = count.clone();
|
||||
Box::pin(async move {
|
||||
count.fetch_add(1, Ordering::SeqCst);
|
||||
})
|
||||
}));
|
||||
}
|
||||
|
||||
let offer_transceiver = offer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let _ = answer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
offer_pc.set_local_description(offer.clone()).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
answer_pc.set_local_description(answer.clone()).await?;
|
||||
offer_pc.set_remote_description(answer).await?;
|
||||
|
||||
assert_eq!(count.load(Ordering::SeqCst), 0);
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
offer_pc.set_local_description(offer.clone()).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
answer_pc.set_local_description(answer.clone()).await?;
|
||||
offer_pc.set_remote_description(answer).await?;
|
||||
|
||||
assert_eq!(count.load(Ordering::SeqCst), 0);
|
||||
|
||||
offer_transceiver
|
||||
.set_direction(RTCRtpTransceiverDirection::Inactive)
|
||||
.await;
|
||||
|
||||
// wait for negotiation ops queue to finish.
|
||||
offer_pc.internal.ops.done().await;
|
||||
|
||||
assert_eq!(count.load(Ordering::SeqCst), 1);
|
||||
|
||||
close_pair_now(&offer_pc, &answer_pc).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[ignore]
|
||||
#[tokio::test]
|
||||
async fn test_rtp_transceiver_stopping() -> Result<()> {
|
||||
let (offer_pc, answer_pc, _) = create_vnet_pair().await?;
|
||||
|
||||
let offer_transceiver = offer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let _ = answer_pc
|
||||
.add_transceiver_from_kind(RTPCodecType::Video, None)
|
||||
.await?;
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
|
||||
offer_pc.set_local_description(offer.clone()).await?;
|
||||
answer_pc.set_remote_description(offer).await?;
|
||||
|
||||
let answer = answer_pc.create_answer(None).await?;
|
||||
assert!(answer.sdp.contains("a=sendrecv"),);
|
||||
answer_pc.set_local_description(answer.clone()).await?;
|
||||
offer_pc.set_remote_description(answer).await?;
|
||||
|
||||
assert!(
|
||||
offer_transceiver.mid().is_some(),
|
||||
"A mid should have been associated with the transceiver when applying the answer"
|
||||
);
|
||||
// Stop the transceiver
|
||||
offer_transceiver.stop().await?;
|
||||
|
||||
let offer = offer_pc.create_offer(None).await?;
|
||||
assert!(offer.sdp.contains("a=inactive"),);
|
||||
let parsed = offer.parsed.unwrap();
|
||||
let m = &parsed.media_descriptions[0];
|
||||
assert_eq!(
|
||||
m.media_name.port.value, 0,
|
||||
"After stopping a transceiver it should be rejected in offers"
|
||||
);
|
||||
|
||||
close_pair_now(&offer_pc, &answer_pc).await;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,289 @@
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
use interceptor::{Attributes, RTCPReader, RTPWriter};
|
||||
use srtp::session::Session;
|
||||
use srtp::stream::Stream;
|
||||
use tokio::sync::Mutex;
|
||||
use util;
|
||||
|
||||
use crate::dtls_transport::RTCDtlsTransport;
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rtp_transceiver::rtp_sender::RTPSenderInternal;
|
||||
use crate::rtp_transceiver::SSRC;
|
||||
|
||||
/// `RTP` packet sequence number manager.
|
||||
///
|
||||
/// Used to override outgoing `RTP` packets' sequence numbers. On creating it is
|
||||
/// unabled and can be enabled before sending data beginning. Once data sending
|
||||
/// began it can not be enabled any more.
|
||||
pub(crate) struct SequenceTransformer(util::sync::Mutex<SequenceTransformerInner>);
|
||||
|
||||
/// [`SequenceTransformer`] inner.
|
||||
struct SequenceTransformerInner {
|
||||
offset: u16,
|
||||
last_sq: u16,
|
||||
reset_needed: bool,
|
||||
enabled: bool,
|
||||
data_sent: bool,
|
||||
}
|
||||
|
||||
impl SequenceTransformer {
|
||||
/// Creates a new [`SequenceTransformer`].
|
||||
pub(crate) fn new() -> Self {
|
||||
Self(util::sync::Mutex::new(SequenceTransformerInner {
|
||||
offset: 0,
|
||||
last_sq: rand::random(),
|
||||
reset_needed: false,
|
||||
enabled: false,
|
||||
data_sent: false,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Enables this [`SequenceTransformer`].
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// With [`Error::ErrRTPSenderSeqTransEnabled`] on trying to enable already
|
||||
/// enabled [`SequenceTransformer`].
|
||||
///
|
||||
/// With [`Error::ErrRTPSenderSeqTransEnabled`] on trying to enable
|
||||
/// [`SequenceTransformer`] after data sending began.
|
||||
pub(crate) fn enable(&self) -> Result<()> {
|
||||
let mut guard = self.0.lock();
|
||||
|
||||
if guard.enabled {
|
||||
return Err(Error::ErrRTPSenderSeqTransEnabled);
|
||||
}
|
||||
|
||||
(!guard.data_sent)
|
||||
.then(|| {
|
||||
guard.enabled = true;
|
||||
})
|
||||
.ok_or(Error::ErrRTPSenderDataSent)
|
||||
}
|
||||
|
||||
/// Indicates [`SequenceTransformer`] about necessity of recalculating
|
||||
/// `offset`.
|
||||
pub(crate) fn reset_offset(&self) {
|
||||
self.0.lock().reset_needed = true;
|
||||
}
|
||||
|
||||
/// Gets [`Some`] consistent `sequence number` if this [`SequenceTransformer`] is
|
||||
/// enabled or [`None`] if it is not.
|
||||
///
|
||||
/// Once this method is called, considers data sending began.
|
||||
fn seq_number(&self, raw_sn: u16) -> Option<u16> {
|
||||
let mut guard = self.0.lock();
|
||||
guard.data_sent = true;
|
||||
|
||||
if !guard.enabled {
|
||||
return None;
|
||||
}
|
||||
|
||||
let offset = guard
|
||||
.reset_needed
|
||||
.then(|| {
|
||||
guard.reset_needed = false;
|
||||
let offset = guard.last_sq.overflowing_sub(raw_sn.overflowing_sub(1).0).0;
|
||||
guard.offset = offset;
|
||||
offset
|
||||
})
|
||||
.unwrap_or(guard.offset);
|
||||
let next = raw_sn.overflowing_add(offset).0;
|
||||
guard.last_sq = next;
|
||||
|
||||
Some(next)
|
||||
}
|
||||
}
|
||||
|
||||
/// SrtpWriterFuture blocks Read/Write calls until
|
||||
/// the SRTP Session is available
|
||||
pub(crate) struct SrtpWriterFuture {
|
||||
pub(crate) closed: AtomicBool,
|
||||
pub(crate) ssrc: SSRC,
|
||||
pub(crate) rtp_sender: Weak<RTPSenderInternal>,
|
||||
pub(crate) rtp_transport: Arc<RTCDtlsTransport>,
|
||||
pub(crate) rtcp_read_stream: Mutex<Option<Arc<Stream>>>, // atomic.Value // *
|
||||
pub(crate) rtp_write_session: Mutex<Option<Arc<Session>>>, // atomic.Value // *
|
||||
pub(crate) seq_trans: Arc<SequenceTransformer>,
|
||||
}
|
||||
|
||||
impl SrtpWriterFuture {
|
||||
async fn init(&self, return_when_no_srtp: bool) -> Result<()> {
|
||||
if return_when_no_srtp {
|
||||
{
|
||||
if let Some(rtp_sender) = self.rtp_sender.upgrade() {
|
||||
if rtp_sender.stop_called_signal.load(Ordering::SeqCst) {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
} else {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
}
|
||||
|
||||
if !self.rtp_transport.srtp_ready_signal.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
} else {
|
||||
let mut rx = self.rtp_transport.srtp_ready_rx.lock().await;
|
||||
if let Some(srtp_ready_rx) = &mut *rx {
|
||||
if let Some(rtp_sender) = self.rtp_sender.upgrade() {
|
||||
tokio::select! {
|
||||
_ = rtp_sender.stop_called_rx.notified()=> return Err(Error::ErrClosedPipe),
|
||||
_ = srtp_ready_rx.recv() =>{}
|
||||
}
|
||||
} else {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if self.closed.load(Ordering::SeqCst) {
|
||||
return Err(Error::ErrClosedPipe);
|
||||
}
|
||||
|
||||
if let Some(srtcp_session) = self.rtp_transport.get_srtcp_session().await {
|
||||
let rtcp_read_stream = srtcp_session.open(self.ssrc).await;
|
||||
let mut stream = self.rtcp_read_stream.lock().await;
|
||||
*stream = Some(rtcp_read_stream);
|
||||
}
|
||||
|
||||
{
|
||||
let srtp_session = self.rtp_transport.get_srtp_session().await;
|
||||
let mut session = self.rtp_write_session.lock().await;
|
||||
*session = srtp_session;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn close(&self) -> Result<()> {
|
||||
if self.closed.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
self.closed.store(true, Ordering::SeqCst);
|
||||
|
||||
let stream = {
|
||||
let mut stream = self.rtcp_read_stream.lock().await;
|
||||
stream.take()
|
||||
};
|
||||
if let Some(rtcp_read_stream) = stream {
|
||||
Ok(rtcp_read_stream.close().await?)
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn read(&self, b: &mut [u8]) -> Result<usize> {
|
||||
{
|
||||
let stream = {
|
||||
let stream = self.rtcp_read_stream.lock().await;
|
||||
stream.clone()
|
||||
};
|
||||
if let Some(rtcp_read_stream) = stream {
|
||||
return Ok(rtcp_read_stream.read(b).await?);
|
||||
}
|
||||
}
|
||||
|
||||
self.init(false).await?;
|
||||
|
||||
{
|
||||
let stream = {
|
||||
let stream = self.rtcp_read_stream.lock().await;
|
||||
stream.clone()
|
||||
};
|
||||
if let Some(rtcp_read_stream) = stream {
|
||||
return Ok(rtcp_read_stream.read(b).await?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub async fn write_rtp(&self, pkt: &rtp::packet::Packet) -> Result<usize> {
|
||||
{
|
||||
let session = {
|
||||
let session = self.rtp_write_session.lock().await;
|
||||
session.clone()
|
||||
};
|
||||
if let Some(rtp_write_session) = session {
|
||||
return Ok(rtp_write_session.write_rtp(pkt).await?);
|
||||
}
|
||||
}
|
||||
|
||||
self.init(true).await?;
|
||||
|
||||
{
|
||||
let session = {
|
||||
let session = self.rtp_write_session.lock().await;
|
||||
session.clone()
|
||||
};
|
||||
if let Some(rtp_write_session) = session {
|
||||
return Ok(rtp_write_session.write_rtp(pkt).await?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
pub async fn write(&self, b: &Bytes) -> Result<usize> {
|
||||
{
|
||||
let session = {
|
||||
let session = self.rtp_write_session.lock().await;
|
||||
session.clone()
|
||||
};
|
||||
if let Some(rtp_write_session) = session {
|
||||
return Ok(rtp_write_session.write(b, true).await?);
|
||||
}
|
||||
}
|
||||
|
||||
self.init(true).await?;
|
||||
|
||||
{
|
||||
let session = {
|
||||
let session = self.rtp_write_session.lock().await;
|
||||
session.clone()
|
||||
};
|
||||
if let Some(rtp_write_session) = session {
|
||||
return Ok(rtp_write_session.write(b, true).await?);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
type IResult<T> = std::result::Result<T, interceptor::Error>;
|
||||
|
||||
#[async_trait]
|
||||
impl RTCPReader for SrtpWriterFuture {
|
||||
async fn read(
|
||||
&self,
|
||||
buf: &mut [u8],
|
||||
a: &Attributes,
|
||||
) -> IResult<(Vec<Box<dyn rtcp::packet::Packet + Send + Sync>>, Attributes)> {
|
||||
let read = self.read(buf).await?;
|
||||
let pkt = rtcp::packet::unmarshal(&mut &buf[..read])?;
|
||||
|
||||
Ok((pkt, a.clone()))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl RTPWriter for SrtpWriterFuture {
|
||||
async fn write(&self, pkt: &rtp::packet::Packet, _a: &Attributes) -> IResult<usize> {
|
||||
Ok(
|
||||
match self.seq_trans.seq_number(pkt.header.sequence_number) {
|
||||
Some(seq_num) => {
|
||||
let mut new_pkt = pkt.clone();
|
||||
new_pkt.header.sequence_number = seq_num;
|
||||
self.write_rtp(&new_pkt).await?
|
||||
}
|
||||
None => self.write_rtp(pkt).await?,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
#[cfg(test)]
|
||||
mod sctp_transport_test;
|
||||
|
||||
pub mod sctp_transport_capabilities;
|
||||
pub mod sctp_transport_state;
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::future::Future;
|
||||
use std::pin::Pin;
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU8, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use arc_swap::ArcSwapOption;
|
||||
use data::data_channel::DataChannel;
|
||||
use data::message::message_channel_open::ChannelType;
|
||||
use sctp::association::Association;
|
||||
use sctp_transport_state::RTCSctpTransportState;
|
||||
use tokio::sync::{Mutex, Notify};
|
||||
use util::Conn;
|
||||
|
||||
use crate::api::setting_engine::SettingEngine;
|
||||
use crate::data_channel::data_channel_parameters::DataChannelParameters;
|
||||
use crate::data_channel::data_channel_state::RTCDataChannelState;
|
||||
use crate::data_channel::RTCDataChannel;
|
||||
use crate::dtls_transport::dtls_role::DTLSRole;
|
||||
use crate::dtls_transport::*;
|
||||
use crate::error::*;
|
||||
use crate::sctp_transport::sctp_transport_capabilities::SCTPTransportCapabilities;
|
||||
use crate::stats::stats_collector::StatsCollector;
|
||||
use crate::stats::StatsReportType::{PeerConnection, SCTPTransport};
|
||||
use crate::stats::{ICETransportStats, PeerConnectionStats};
|
||||
|
||||
const SCTP_MAX_CHANNELS: u16 = u16::MAX;
|
||||
|
||||
pub type OnDataChannelHdlrFn = Box<
|
||||
dyn (FnMut(Arc<RTCDataChannel>) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
pub type OnDataChannelOpenedHdlrFn = Box<
|
||||
dyn (FnMut(Arc<RTCDataChannel>) -> Pin<Box<dyn Future<Output = ()> + Send + 'static>>)
|
||||
+ Send
|
||||
+ Sync,
|
||||
>;
|
||||
|
||||
struct AcceptDataChannelParams {
|
||||
notify_rx: Arc<Notify>,
|
||||
sctp_association: Arc<Association>,
|
||||
data_channels: Arc<Mutex<Vec<Arc<RTCDataChannel>>>>,
|
||||
on_error_handler: Arc<ArcSwapOption<Mutex<OnErrorHdlrFn>>>,
|
||||
on_data_channel_handler: Arc<ArcSwapOption<Mutex<OnDataChannelHdlrFn>>>,
|
||||
on_data_channel_opened_handler: Arc<ArcSwapOption<Mutex<OnDataChannelOpenedHdlrFn>>>,
|
||||
data_channels_opened: Arc<AtomicU32>,
|
||||
data_channels_accepted: Arc<AtomicU32>,
|
||||
setting_engine: Arc<SettingEngine>,
|
||||
}
|
||||
|
||||
/// SCTPTransport provides details about the SCTP transport.
|
||||
#[derive(Default)]
|
||||
pub struct RTCSctpTransport {
|
||||
pub(crate) dtls_transport: Arc<RTCDtlsTransport>,
|
||||
|
||||
// State represents the current state of the SCTP transport.
|
||||
state: AtomicU8, // RTCSctpTransportState
|
||||
|
||||
// SCTPTransportState doesn't have an enum to distinguish between New/Connecting
|
||||
// so we need a dedicated field
|
||||
is_started: AtomicBool,
|
||||
|
||||
// max_message_size represents the maximum size of data that can be passed to
|
||||
// DataChannel's send() method.
|
||||
max_message_size: usize,
|
||||
|
||||
// max_channels represents the maximum amount of DataChannel's that can
|
||||
// be used simultaneously.
|
||||
max_channels: u16,
|
||||
|
||||
sctp_association: Mutex<Option<Arc<Association>>>,
|
||||
|
||||
on_error_handler: Arc<ArcSwapOption<Mutex<OnErrorHdlrFn>>>,
|
||||
on_data_channel_handler: Arc<ArcSwapOption<Mutex<OnDataChannelHdlrFn>>>,
|
||||
on_data_channel_opened_handler: Arc<ArcSwapOption<Mutex<OnDataChannelOpenedHdlrFn>>>,
|
||||
|
||||
// DataChannels
|
||||
pub(crate) data_channels: Arc<Mutex<Vec<Arc<RTCDataChannel>>>>,
|
||||
pub(crate) data_channels_opened: Arc<AtomicU32>,
|
||||
pub(crate) data_channels_requested: Arc<AtomicU32>,
|
||||
data_channels_accepted: Arc<AtomicU32>,
|
||||
|
||||
notify_tx: Arc<Notify>,
|
||||
|
||||
setting_engine: Arc<SettingEngine>,
|
||||
}
|
||||
|
||||
impl RTCSctpTransport {
|
||||
pub(crate) fn new(
|
||||
dtls_transport: Arc<RTCDtlsTransport>,
|
||||
setting_engine: Arc<SettingEngine>,
|
||||
) -> Self {
|
||||
RTCSctpTransport {
|
||||
dtls_transport,
|
||||
state: AtomicU8::new(RTCSctpTransportState::Connecting as u8),
|
||||
is_started: AtomicBool::new(false),
|
||||
max_message_size: RTCSctpTransport::calc_message_size(65536, 65536),
|
||||
max_channels: SCTP_MAX_CHANNELS,
|
||||
sctp_association: Mutex::new(None),
|
||||
on_error_handler: Arc::new(ArcSwapOption::empty()),
|
||||
on_data_channel_handler: Arc::new(ArcSwapOption::empty()),
|
||||
on_data_channel_opened_handler: Arc::new(ArcSwapOption::empty()),
|
||||
|
||||
data_channels: Arc::new(Mutex::new(vec![])),
|
||||
data_channels_opened: Arc::new(AtomicU32::new(0)),
|
||||
data_channels_requested: Arc::new(AtomicU32::new(0)),
|
||||
data_channels_accepted: Arc::new(AtomicU32::new(0)),
|
||||
|
||||
notify_tx: Arc::new(Notify::new()),
|
||||
|
||||
setting_engine,
|
||||
}
|
||||
}
|
||||
|
||||
/// transport returns the DTLSTransport instance the SCTPTransport is sending over.
|
||||
pub fn transport(&self) -> Arc<RTCDtlsTransport> {
|
||||
Arc::clone(&self.dtls_transport)
|
||||
}
|
||||
|
||||
/// get_capabilities returns the SCTPCapabilities of the SCTPTransport.
|
||||
pub fn get_capabilities(&self) -> SCTPTransportCapabilities {
|
||||
SCTPTransportCapabilities {
|
||||
max_message_size: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the SCTPTransport. Since both local and remote parties must mutually
|
||||
/// create an SCTPTransport, SCTP SO (Simultaneous Open) is used to establish
|
||||
/// a connection over SCTP.
|
||||
pub async fn start(&self, _remote_caps: SCTPTransportCapabilities) -> Result<()> {
|
||||
if self.is_started.load(Ordering::SeqCst) {
|
||||
return Ok(());
|
||||
}
|
||||
self.is_started.store(true, Ordering::SeqCst);
|
||||
|
||||
let dtls_transport = self.transport();
|
||||
if let Some(net_conn) = &dtls_transport.conn().await {
|
||||
let sctp_association = loop {
|
||||
tokio::select! {
|
||||
_ = self.notify_tx.notified() => {
|
||||
// It seems like notify_tx is only notified on Stop so perhaps this check
|
||||
// is redundant.
|
||||
// TODO: Consider renaming notify_tx to shutdown_tx.
|
||||
if self.state.load(Ordering::SeqCst) == RTCSctpTransportState::Closed as u8 {
|
||||
return Err(Error::ErrSCTPTransportDTLS);
|
||||
}
|
||||
},
|
||||
association = sctp::association::Association::client(sctp::association::Config {
|
||||
net_conn: Arc::clone(net_conn) as Arc<dyn Conn + Send + Sync>,
|
||||
max_receive_buffer_size: 0,
|
||||
max_message_size: 0,
|
||||
name: String::new(),
|
||||
}) => {
|
||||
break Arc::new(association?);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
{
|
||||
let mut sa = self.sctp_association.lock().await;
|
||||
*sa = Some(Arc::clone(&sctp_association));
|
||||
}
|
||||
self.state
|
||||
.store(RTCSctpTransportState::Connected as u8, Ordering::SeqCst);
|
||||
|
||||
let param = AcceptDataChannelParams {
|
||||
notify_rx: self.notify_tx.clone(),
|
||||
sctp_association,
|
||||
data_channels: Arc::clone(&self.data_channels),
|
||||
on_error_handler: Arc::clone(&self.on_error_handler),
|
||||
on_data_channel_handler: Arc::clone(&self.on_data_channel_handler),
|
||||
on_data_channel_opened_handler: Arc::clone(&self.on_data_channel_opened_handler),
|
||||
data_channels_opened: Arc::clone(&self.data_channels_opened),
|
||||
data_channels_accepted: Arc::clone(&self.data_channels_accepted),
|
||||
setting_engine: Arc::clone(&self.setting_engine),
|
||||
};
|
||||
tokio::spawn(async move {
|
||||
RTCSctpTransport::accept_data_channels(param).await;
|
||||
});
|
||||
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ErrSCTPTransportDTLS)
|
||||
}
|
||||
}
|
||||
|
||||
/// Stop stops the SCTPTransport
|
||||
pub async fn stop(&self) -> Result<()> {
|
||||
{
|
||||
let mut sctp_association = self.sctp_association.lock().await;
|
||||
if let Some(sa) = sctp_association.take() {
|
||||
sa.close().await?;
|
||||
}
|
||||
}
|
||||
|
||||
self.state
|
||||
.store(RTCSctpTransportState::Closed as u8, Ordering::SeqCst);
|
||||
|
||||
self.notify_tx.notify_waiters();
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn accept_data_channels(param: AcceptDataChannelParams) {
|
||||
let dcs = param.data_channels.lock().await;
|
||||
let mut existing_data_channels = Vec::new();
|
||||
for dc in dcs.iter() {
|
||||
if let Some(dc) = dc.data_channel.lock().await.clone() {
|
||||
existing_data_channels.push(dc);
|
||||
}
|
||||
}
|
||||
drop(dcs);
|
||||
|
||||
loop {
|
||||
let dc = tokio::select! {
|
||||
_ = param.notify_rx.notified() => break,
|
||||
result = DataChannel::accept(
|
||||
¶m.sctp_association,
|
||||
data::data_channel::Config::default(),
|
||||
&existing_data_channels,
|
||||
) => {
|
||||
match result {
|
||||
Ok(dc) => dc,
|
||||
Err(err) => {
|
||||
if data::Error::ErrStreamClosed == err {
|
||||
log::error!("Failed to accept data channel: {}", err);
|
||||
if let Some(handler) = &*param.on_error_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(err.into()).await;
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let mut max_retransmits = 0;
|
||||
let mut max_packet_lifetime = 0;
|
||||
let val = dc.config.reliability_parameter as u16;
|
||||
let ordered;
|
||||
|
||||
match dc.config.channel_type {
|
||||
ChannelType::Reliable => {
|
||||
ordered = true;
|
||||
}
|
||||
ChannelType::ReliableUnordered => {
|
||||
ordered = false;
|
||||
}
|
||||
ChannelType::PartialReliableRexmit => {
|
||||
ordered = true;
|
||||
max_retransmits = val;
|
||||
}
|
||||
ChannelType::PartialReliableRexmitUnordered => {
|
||||
ordered = false;
|
||||
max_retransmits = val;
|
||||
}
|
||||
ChannelType::PartialReliableTimed => {
|
||||
ordered = true;
|
||||
max_packet_lifetime = val;
|
||||
}
|
||||
ChannelType::PartialReliableTimedUnordered => {
|
||||
ordered = false;
|
||||
max_packet_lifetime = val;
|
||||
}
|
||||
};
|
||||
|
||||
let negotiated = if dc.config.negotiated {
|
||||
Some(dc.stream_identifier())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let rtc_dc = Arc::new(RTCDataChannel::new(
|
||||
DataChannelParameters {
|
||||
label: dc.config.label.clone(),
|
||||
protocol: dc.config.protocol.clone(),
|
||||
negotiated,
|
||||
ordered,
|
||||
max_packet_life_time: max_packet_lifetime,
|
||||
max_retransmits,
|
||||
},
|
||||
Arc::clone(¶m.setting_engine),
|
||||
));
|
||||
|
||||
if let Some(handler) = &*param.on_data_channel_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(Arc::clone(&rtc_dc)).await;
|
||||
|
||||
param.data_channels_accepted.fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
let mut dcs = param.data_channels.lock().await;
|
||||
dcs.push(Arc::clone(&rtc_dc));
|
||||
}
|
||||
|
||||
rtc_dc.handle_open(Arc::new(dc)).await;
|
||||
|
||||
if let Some(handler) = &*param.on_data_channel_opened_handler.load() {
|
||||
let mut f = handler.lock().await;
|
||||
f(rtc_dc).await;
|
||||
param.data_channels_opened.fetch_add(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// on_error sets an event handler which is invoked when
|
||||
/// the SCTP connection error occurs.
|
||||
pub fn on_error(&self, f: OnErrorHdlrFn) {
|
||||
self.on_error_handler.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// on_data_channel sets an event handler which is invoked when a data
|
||||
/// channel message arrives from a remote peer.
|
||||
pub fn on_data_channel(&self, f: OnDataChannelHdlrFn) {
|
||||
self.on_data_channel_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
/// on_data_channel_opened sets an event handler which is invoked when a data
|
||||
/// channel is opened
|
||||
pub fn on_data_channel_opened(&self, f: OnDataChannelOpenedHdlrFn) {
|
||||
self.on_data_channel_opened_handler
|
||||
.store(Some(Arc::new(Mutex::new(f))));
|
||||
}
|
||||
|
||||
fn calc_message_size(remote_max_message_size: usize, can_send_size: usize) -> usize {
|
||||
if remote_max_message_size == 0 && can_send_size == 0 {
|
||||
usize::MAX
|
||||
} else if remote_max_message_size == 0 {
|
||||
can_send_size
|
||||
} else if can_send_size == 0 || can_send_size > remote_max_message_size {
|
||||
remote_max_message_size
|
||||
} else {
|
||||
can_send_size
|
||||
}
|
||||
}
|
||||
|
||||
/// max_channels is the maximum number of RTCDataChannels that can be open simultaneously.
|
||||
pub fn max_channels(&self) -> u16 {
|
||||
if self.max_channels == 0 {
|
||||
SCTP_MAX_CHANNELS
|
||||
} else {
|
||||
self.max_channels
|
||||
}
|
||||
}
|
||||
|
||||
/// state returns the current state of the SCTPTransport
|
||||
pub fn state(&self) -> RTCSctpTransportState {
|
||||
self.state.load(Ordering::SeqCst).into()
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_stats(
|
||||
&self,
|
||||
collector: &StatsCollector,
|
||||
peer_connection_id: String,
|
||||
) {
|
||||
let dtls_transport = self.transport();
|
||||
|
||||
// TODO: should this be collected?
|
||||
dtls_transport.collect_stats(collector).await;
|
||||
|
||||
// data channels
|
||||
let mut data_channels_closed = 0;
|
||||
let data_channels = self.data_channels.lock().await;
|
||||
for data_channel in &*data_channels {
|
||||
match data_channel.ready_state() {
|
||||
RTCDataChannelState::Connecting => (),
|
||||
RTCDataChannelState::Open => (),
|
||||
_ => data_channels_closed += 1,
|
||||
}
|
||||
data_channel.collect_stats(collector).await;
|
||||
}
|
||||
|
||||
let mut reports = HashMap::new();
|
||||
let peer_connection_stats =
|
||||
PeerConnectionStats::new(self, peer_connection_id.clone(), data_channels_closed);
|
||||
reports.insert(peer_connection_id, PeerConnection(peer_connection_stats));
|
||||
|
||||
// conn
|
||||
if let Some(agent) = dtls_transport.ice_transport.gatherer.get_agent().await {
|
||||
let stats = ICETransportStats::new("sctp_transport".to_owned(), agent);
|
||||
reports.insert(stats.id.clone(), SCTPTransport(stats));
|
||||
}
|
||||
|
||||
collector.merge(reports);
|
||||
}
|
||||
|
||||
pub(crate) async fn generate_and_set_data_channel_id(
|
||||
&self,
|
||||
dtls_role: DTLSRole,
|
||||
) -> Result<u16> {
|
||||
let mut id = 0u16;
|
||||
if dtls_role != DTLSRole::Client {
|
||||
id += 1;
|
||||
}
|
||||
|
||||
// Create map of ids so we can compare without double-looping each time.
|
||||
let mut ids_map = HashSet::new();
|
||||
{
|
||||
let data_channels = self.data_channels.lock().await;
|
||||
for dc in &*data_channels {
|
||||
ids_map.insert(dc.id());
|
||||
}
|
||||
}
|
||||
|
||||
let max = self.max_channels();
|
||||
while id < max - 1 {
|
||||
if ids_map.contains(&id) {
|
||||
id += 2;
|
||||
} else {
|
||||
return Ok(id);
|
||||
}
|
||||
}
|
||||
|
||||
Err(Error::ErrMaxDataChannelID)
|
||||
}
|
||||
|
||||
pub(crate) async fn association(&self) -> Option<Arc<Association>> {
|
||||
let sctp_association = self.sctp_association.lock().await;
|
||||
sctp_association.clone()
|
||||
}
|
||||
|
||||
pub(crate) fn data_channels_accepted(&self) -> u32 {
|
||||
self.data_channels_accepted.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn data_channels_opened(&self) -> u32 {
|
||||
self.data_channels_opened.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn data_channels_requested(&self) -> u32 {
|
||||
self.data_channels_requested.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// SCTPTransportCapabilities indicates the capabilities of the SCTPTransport.
|
||||
#[derive(Debug, PartialEq, Eq, Copy, Clone, Serialize, Deserialize)]
|
||||
pub struct SCTPTransportCapabilities {
|
||||
pub max_message_size: u32,
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
use std::fmt;
|
||||
|
||||
/// SCTPTransportState indicates the state of the SCTP transport.
|
||||
#[derive(Default, Debug, Copy, Clone, PartialEq, Eq)]
|
||||
#[repr(u8)]
|
||||
pub enum RTCSctpTransportState {
|
||||
#[default]
|
||||
Unspecified,
|
||||
|
||||
/// SCTPTransportStateConnecting indicates the SCTPTransport is in the
|
||||
/// process of negotiating an association. This is the initial state of the
|
||||
/// SCTPTransportState when an SCTPTransport is created.
|
||||
Connecting,
|
||||
|
||||
/// SCTPTransportStateConnected indicates the negotiation of an
|
||||
/// association is completed.
|
||||
Connected,
|
||||
|
||||
/// SCTPTransportStateClosed indicates a SHUTDOWN or ABORT chunk is
|
||||
/// received or when the SCTP association has been closed intentionally,
|
||||
/// such as by closing the peer connection or applying a remote description
|
||||
/// that rejects data or changes the SCTP port.
|
||||
Closed,
|
||||
}
|
||||
|
||||
const SCTP_TRANSPORT_STATE_CONNECTING_STR: &str = "connecting";
|
||||
const SCTP_TRANSPORT_STATE_CONNECTED_STR: &str = "connected";
|
||||
const SCTP_TRANSPORT_STATE_CLOSED_STR: &str = "closed";
|
||||
|
||||
impl From<&str> for RTCSctpTransportState {
|
||||
fn from(raw: &str) -> Self {
|
||||
match raw {
|
||||
SCTP_TRANSPORT_STATE_CONNECTING_STR => RTCSctpTransportState::Connecting,
|
||||
SCTP_TRANSPORT_STATE_CONNECTED_STR => RTCSctpTransportState::Connected,
|
||||
SCTP_TRANSPORT_STATE_CLOSED_STR => RTCSctpTransportState::Closed,
|
||||
_ => RTCSctpTransportState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<u8> for RTCSctpTransportState {
|
||||
fn from(v: u8) -> Self {
|
||||
match v {
|
||||
1 => RTCSctpTransportState::Connecting,
|
||||
2 => RTCSctpTransportState::Connected,
|
||||
3 => RTCSctpTransportState::Closed,
|
||||
_ => RTCSctpTransportState::Unspecified,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for RTCSctpTransportState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
let s = match *self {
|
||||
RTCSctpTransportState::Connecting => SCTP_TRANSPORT_STATE_CONNECTING_STR,
|
||||
RTCSctpTransportState::Connected => SCTP_TRANSPORT_STATE_CONNECTED_STR,
|
||||
RTCSctpTransportState::Closed => SCTP_TRANSPORT_STATE_CLOSED_STR,
|
||||
RTCSctpTransportState::Unspecified => crate::UNSPECIFIED_STR,
|
||||
};
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod test {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_new_sctp_transport_state() {
|
||||
let tests = vec![
|
||||
(crate::UNSPECIFIED_STR, RTCSctpTransportState::Unspecified),
|
||||
("connecting", RTCSctpTransportState::Connecting),
|
||||
("connected", RTCSctpTransportState::Connected),
|
||||
("closed", RTCSctpTransportState::Closed),
|
||||
];
|
||||
|
||||
for (state_string, expected_state) in tests {
|
||||
assert_eq!(
|
||||
RTCSctpTransportState::from(state_string),
|
||||
expected_state,
|
||||
"testCase: {expected_state}",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sctp_transport_state_string() {
|
||||
let tests = vec![
|
||||
(RTCSctpTransportState::Unspecified, crate::UNSPECIFIED_STR),
|
||||
(RTCSctpTransportState::Connecting, "connecting"),
|
||||
(RTCSctpTransportState::Connected, "connected"),
|
||||
(RTCSctpTransportState::Closed, "closed"),
|
||||
];
|
||||
|
||||
for (state, expected_string) in tests {
|
||||
assert_eq!(state.to_string(), expected_string)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
use std::sync::atomic::AtomicU16;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_generate_data_channel_id() -> Result<()> {
|
||||
let sctp_transport_with_channels = |ids: &[u16]| -> RTCSctpTransport {
|
||||
let mut data_channels = vec![];
|
||||
for id in ids {
|
||||
data_channels.push(Arc::new(RTCDataChannel {
|
||||
id: AtomicU16::new(*id),
|
||||
..Default::default()
|
||||
}));
|
||||
}
|
||||
|
||||
RTCSctpTransport {
|
||||
data_channels: Arc::new(Mutex::new(data_channels)),
|
||||
..Default::default()
|
||||
}
|
||||
};
|
||||
|
||||
let tests = vec![
|
||||
(DTLSRole::Client, sctp_transport_with_channels(&[]), 0),
|
||||
(DTLSRole::Client, sctp_transport_with_channels(&[1]), 0),
|
||||
(DTLSRole::Client, sctp_transport_with_channels(&[0]), 2),
|
||||
(DTLSRole::Client, sctp_transport_with_channels(&[0, 2]), 4),
|
||||
(DTLSRole::Client, sctp_transport_with_channels(&[0, 4]), 2),
|
||||
(DTLSRole::Server, sctp_transport_with_channels(&[]), 1),
|
||||
(DTLSRole::Server, sctp_transport_with_channels(&[0]), 1),
|
||||
(DTLSRole::Server, sctp_transport_with_channels(&[1]), 3),
|
||||
(DTLSRole::Server, sctp_transport_with_channels(&[1, 3]), 5),
|
||||
(DTLSRole::Server, sctp_transport_with_channels(&[1, 5]), 3),
|
||||
];
|
||||
|
||||
for (role, s, expected) in tests {
|
||||
match s.generate_and_set_data_channel_id(role).await {
|
||||
Ok(actual) => assert_eq!(actual, expected),
|
||||
Err(err) => panic!("failed to generate id: {err}"),
|
||||
};
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
Vendored
+586
@@ -0,0 +1,586 @@
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::time::SystemTime;
|
||||
|
||||
use ice::agent::agent_stats::{CandidatePairStats, CandidateStats};
|
||||
use ice::agent::Agent;
|
||||
use ice::candidate::{CandidatePairState, CandidateType};
|
||||
use ice::network_type::NetworkType;
|
||||
use serde::{Serialize, Serializer};
|
||||
use smol_str::SmolStr;
|
||||
use stats_collector::StatsCollector;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::data_channel::data_channel_state::RTCDataChannelState;
|
||||
use crate::data_channel::RTCDataChannel;
|
||||
use crate::dtls_transport::dtls_fingerprint::RTCDtlsFingerprint;
|
||||
use crate::peer_connection::certificate::RTCCertificate;
|
||||
use crate::rtp_transceiver::rtp_codec::RTCRtpCodecParameters;
|
||||
use crate::rtp_transceiver::{PayloadType, SSRC};
|
||||
use crate::sctp_transport::RTCSctpTransport;
|
||||
|
||||
mod serialize;
|
||||
pub mod stats_collector;
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub enum RTCStatsType {
|
||||
#[serde(rename = "candidate-pair")]
|
||||
CandidatePair,
|
||||
#[serde(rename = "certificate")]
|
||||
Certificate,
|
||||
#[serde(rename = "codec")]
|
||||
Codec,
|
||||
#[serde(rename = "csrc")]
|
||||
CSRC,
|
||||
#[serde(rename = "data-channel")]
|
||||
DataChannel,
|
||||
#[serde(rename = "inbound-rtp")]
|
||||
InboundRTP,
|
||||
#[serde(rename = "local-candidate")]
|
||||
LocalCandidate,
|
||||
#[serde(rename = "outbound-rtp")]
|
||||
OutboundRTP,
|
||||
#[serde(rename = "peer-connection")]
|
||||
PeerConnection,
|
||||
#[serde(rename = "receiver")]
|
||||
Receiver,
|
||||
#[serde(rename = "remote-candidate")]
|
||||
RemoteCandidate,
|
||||
#[serde(rename = "remote-inbound-rtp")]
|
||||
RemoteInboundRTP,
|
||||
#[serde(rename = "remote-outbound-rtp")]
|
||||
RemoteOutboundRTP,
|
||||
#[serde(rename = "sender")]
|
||||
Sender,
|
||||
#[serde(rename = "transport")]
|
||||
Transport,
|
||||
}
|
||||
|
||||
pub enum SourceStatsType {
|
||||
LocalCandidate(CandidateStats),
|
||||
RemoteCandidate(CandidateStats),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum StatsReportType {
|
||||
CandidatePair(ICECandidatePairStats),
|
||||
CertificateStats(CertificateStats),
|
||||
Codec(CodecStats),
|
||||
DataChannel(DataChannelStats),
|
||||
LocalCandidate(ICECandidateStats),
|
||||
PeerConnection(PeerConnectionStats),
|
||||
RemoteCandidate(ICECandidateStats),
|
||||
SCTPTransport(ICETransportStats),
|
||||
Transport(ICETransportStats),
|
||||
InboundRTP(InboundRTPStats),
|
||||
OutboundRTP(OutboundRTPStats),
|
||||
RemoteInboundRTP(RemoteInboundRTPStats),
|
||||
RemoteOutboundRTP(RemoteOutboundRTPStats),
|
||||
}
|
||||
|
||||
impl From<SourceStatsType> for StatsReportType {
|
||||
fn from(stats: SourceStatsType) -> Self {
|
||||
match stats {
|
||||
SourceStatsType::LocalCandidate(stats) => StatsReportType::LocalCandidate(
|
||||
ICECandidateStats::new(stats, RTCStatsType::LocalCandidate),
|
||||
),
|
||||
SourceStatsType::RemoteCandidate(stats) => StatsReportType::RemoteCandidate(
|
||||
ICECandidateStats::new(stats, RTCStatsType::RemoteCandidate),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for StatsReportType {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
match self {
|
||||
StatsReportType::CandidatePair(stats) => stats.serialize(serializer),
|
||||
StatsReportType::CertificateStats(stats) => stats.serialize(serializer),
|
||||
StatsReportType::Codec(stats) => stats.serialize(serializer),
|
||||
StatsReportType::DataChannel(stats) => stats.serialize(serializer),
|
||||
StatsReportType::LocalCandidate(stats) => stats.serialize(serializer),
|
||||
StatsReportType::PeerConnection(stats) => stats.serialize(serializer),
|
||||
StatsReportType::RemoteCandidate(stats) => stats.serialize(serializer),
|
||||
StatsReportType::SCTPTransport(stats) => stats.serialize(serializer),
|
||||
StatsReportType::Transport(stats) => stats.serialize(serializer),
|
||||
StatsReportType::InboundRTP(stats) => stats.serialize(serializer),
|
||||
StatsReportType::OutboundRTP(stats) => stats.serialize(serializer),
|
||||
StatsReportType::RemoteInboundRTP(stats) => stats.serialize(serializer),
|
||||
StatsReportType::RemoteOutboundRTP(stats) => stats.serialize(serializer),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct StatsReport {
|
||||
pub reports: HashMap<String, StatsReportType>,
|
||||
}
|
||||
|
||||
impl From<StatsCollector> for StatsReport {
|
||||
fn from(collector: StatsCollector) -> Self {
|
||||
StatsReport {
|
||||
reports: collector.into_reports(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for StatsReport {
|
||||
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
self.reports.serialize(serializer)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ICECandidatePairStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCIceCandidatePairStats
|
||||
// TODO: Add `transportId`
|
||||
pub local_candidate_id: String,
|
||||
pub remote_candidate_id: String,
|
||||
pub state: CandidatePairState,
|
||||
pub nominated: bool,
|
||||
pub packets_sent: u32,
|
||||
pub packets_received: u32,
|
||||
pub bytes_sent: u64,
|
||||
pub bytes_received: u64,
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub last_packet_sent_timestamp: Instant,
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub last_packet_received_timestamp: Instant,
|
||||
pub total_round_trip_time: f64,
|
||||
pub current_round_trip_time: f64,
|
||||
pub available_outgoing_bitrate: f64,
|
||||
pub available_incoming_bitrate: f64,
|
||||
pub requests_received: u64,
|
||||
pub requests_sent: u64,
|
||||
pub responses_received: u64,
|
||||
pub responses_sent: u64,
|
||||
pub consent_requests_sent: u64,
|
||||
// TODO: Add `packetsDiscardedOnSend`
|
||||
// TODO: Add `bytesDiscardedOnSend`
|
||||
|
||||
// Non-canon
|
||||
pub circuit_breaker_trigger_count: u32,
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub consent_expired_timestamp: Instant,
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub first_request_timestamp: Instant,
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub last_request_timestamp: Instant,
|
||||
pub retransmissions_sent: u64,
|
||||
}
|
||||
|
||||
impl From<CandidatePairStats> for ICECandidatePairStats {
|
||||
fn from(stats: CandidatePairStats) -> Self {
|
||||
ICECandidatePairStats {
|
||||
available_incoming_bitrate: stats.available_incoming_bitrate,
|
||||
available_outgoing_bitrate: stats.available_outgoing_bitrate,
|
||||
bytes_received: stats.bytes_received,
|
||||
bytes_sent: stats.bytes_sent,
|
||||
circuit_breaker_trigger_count: stats.circuit_breaker_trigger_count,
|
||||
consent_expired_timestamp: stats.consent_expired_timestamp,
|
||||
consent_requests_sent: stats.consent_requests_sent,
|
||||
current_round_trip_time: stats.current_round_trip_time,
|
||||
first_request_timestamp: stats.first_request_timestamp,
|
||||
id: format!("{}-{}", stats.local_candidate_id, stats.remote_candidate_id),
|
||||
last_packet_received_timestamp: stats.last_packet_received_timestamp,
|
||||
last_packet_sent_timestamp: stats.last_packet_sent_timestamp,
|
||||
last_request_timestamp: stats.last_request_timestamp,
|
||||
local_candidate_id: stats.local_candidate_id,
|
||||
nominated: stats.nominated,
|
||||
packets_received: stats.packets_received,
|
||||
packets_sent: stats.packets_sent,
|
||||
remote_candidate_id: stats.remote_candidate_id,
|
||||
requests_received: stats.requests_received,
|
||||
requests_sent: stats.requests_sent,
|
||||
responses_received: stats.responses_received,
|
||||
responses_sent: stats.responses_sent,
|
||||
retransmissions_sent: stats.retransmissions_sent,
|
||||
state: stats.state,
|
||||
stats_type: RTCStatsType::CandidatePair,
|
||||
timestamp: stats.timestamp,
|
||||
total_round_trip_time: stats.total_round_trip_time,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ICECandidateStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCIceCandidateStats
|
||||
pub candidate_type: CandidateType,
|
||||
pub deleted: bool,
|
||||
pub ip: String,
|
||||
pub network_type: NetworkType,
|
||||
pub port: u16,
|
||||
pub priority: u32,
|
||||
pub relay_protocol: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
impl ICECandidateStats {
|
||||
fn new(stats: CandidateStats, stats_type: RTCStatsType) -> Self {
|
||||
ICECandidateStats {
|
||||
candidate_type: stats.candidate_type,
|
||||
deleted: stats.deleted,
|
||||
id: stats.id,
|
||||
ip: stats.ip,
|
||||
network_type: stats.network_type,
|
||||
port: stats.port,
|
||||
priority: stats.priority,
|
||||
relay_protocol: stats.relay_protocol,
|
||||
stats_type,
|
||||
timestamp: stats.timestamp,
|
||||
url: stats.url,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ICETransportStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// Non-canon
|
||||
pub bytes_received: usize,
|
||||
pub bytes_sent: usize,
|
||||
}
|
||||
|
||||
impl ICETransportStats {
|
||||
pub(crate) fn new(id: String, agent: Arc<Agent>) -> Self {
|
||||
ICETransportStats {
|
||||
id,
|
||||
bytes_received: agent.get_bytes_received(),
|
||||
bytes_sent: agent.get_bytes_sent(),
|
||||
stats_type: RTCStatsType::Transport,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CertificateStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCCertificateStats
|
||||
pub fingerprint: String,
|
||||
pub fingerprint_algorithm: String,
|
||||
// TODO: Add `base64Certificate` and `issuerCertificateId`.
|
||||
}
|
||||
|
||||
impl CertificateStats {
|
||||
pub(crate) fn new(cert: &RTCCertificate, fingerprint: RTCDtlsFingerprint) -> Self {
|
||||
CertificateStats {
|
||||
// TODO: base64_certificate
|
||||
fingerprint: fingerprint.value,
|
||||
fingerprint_algorithm: fingerprint.algorithm,
|
||||
id: cert.stats_id.clone(),
|
||||
// TODO: issuer_certificate_id
|
||||
stats_type: RTCStatsType::Certificate,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct CodecStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCCodecStats
|
||||
pub payload_type: PayloadType,
|
||||
pub mime_type: String,
|
||||
pub channels: u16,
|
||||
pub clock_rate: u32,
|
||||
pub sdp_fmtp_line: String,
|
||||
// TODO: Add `transportId`
|
||||
}
|
||||
|
||||
impl From<&RTCRtpCodecParameters> for CodecStats {
|
||||
fn from(codec: &RTCRtpCodecParameters) -> Self {
|
||||
CodecStats {
|
||||
channels: codec.capability.channels,
|
||||
clock_rate: codec.capability.clock_rate,
|
||||
id: codec.stats_id.clone(),
|
||||
mime_type: codec.capability.mime_type.clone(),
|
||||
payload_type: codec.payload_type,
|
||||
sdp_fmtp_line: codec.capability.sdp_fmtp_line.clone(),
|
||||
stats_type: RTCStatsType::Codec,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DataChannelStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCDataChannelStats
|
||||
pub bytes_received: usize,
|
||||
pub bytes_sent: usize,
|
||||
pub data_channel_identifier: u16,
|
||||
pub label: String,
|
||||
pub messages_received: usize,
|
||||
pub messages_sent: usize,
|
||||
pub protocol: String,
|
||||
pub state: RTCDataChannelState,
|
||||
}
|
||||
|
||||
impl DataChannelStats {
|
||||
pub(crate) async fn from(data_channel: &RTCDataChannel) -> Self {
|
||||
let state = data_channel.ready_state();
|
||||
|
||||
let mut bytes_received = 0;
|
||||
let mut bytes_sent = 0;
|
||||
let mut messages_received = 0;
|
||||
let mut messages_sent = 0;
|
||||
|
||||
let lock = data_channel.data_channel.lock().await;
|
||||
|
||||
if let Some(internal) = &*lock {
|
||||
bytes_received = internal.bytes_received();
|
||||
bytes_sent = internal.bytes_sent();
|
||||
messages_received = internal.messages_received();
|
||||
messages_sent = internal.messages_sent();
|
||||
}
|
||||
|
||||
Self {
|
||||
bytes_received,
|
||||
bytes_sent,
|
||||
data_channel_identifier: data_channel.id(), // TODO: "The value is initially null"
|
||||
id: data_channel.stats_id.clone(),
|
||||
label: data_channel.label.clone(),
|
||||
messages_received,
|
||||
messages_sent,
|
||||
protocol: data_channel.protocol.clone(),
|
||||
state,
|
||||
stats_type: RTCStatsType::DataChannel,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct PeerConnectionStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCPeerConnectionStats
|
||||
pub data_channels_closed: u32,
|
||||
pub data_channels_opened: u32,
|
||||
|
||||
// Non-canon
|
||||
pub data_channels_accepted: u32,
|
||||
pub data_channels_requested: u32,
|
||||
}
|
||||
|
||||
impl PeerConnectionStats {
|
||||
pub fn new(transport: &RTCSctpTransport, stats_id: String, data_channels_closed: u32) -> Self {
|
||||
PeerConnectionStats {
|
||||
data_channels_accepted: transport.data_channels_accepted(),
|
||||
data_channels_closed,
|
||||
data_channels_opened: transport.data_channels_opened(),
|
||||
data_channels_requested: transport.data_channels_requested(),
|
||||
id: stats_id,
|
||||
stats_type: RTCStatsType::PeerConnection,
|
||||
timestamp: Instant::now(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct InboundRTPStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCRtpStreamStats
|
||||
pub ssrc: SSRC,
|
||||
pub kind: &'static str, // Either "video" or "audio"
|
||||
// TODO: Add transportId
|
||||
// TODO: Add codecId
|
||||
|
||||
// RTCReceivedRtpStreamStats
|
||||
pub packets_received: u64,
|
||||
// TODO: packetsLost
|
||||
// TODO: jitter(maybe, might be uattainable for the same reason as `framesDropped`)
|
||||
// NB: `framesDropped` can't be produced since we aren't decoding, might be worth introducing a
|
||||
// way for consumers to control this in the future.
|
||||
|
||||
// RTCInboundRtpStreamStats
|
||||
pub track_identifier: String,
|
||||
pub mid: SmolStr,
|
||||
// TODO: `remoteId`
|
||||
// NB: `framesDecoded`, `frameWidth`, frameHeight`, `framesPerSecond`, `qpSum`,
|
||||
// `totalDecodeTime`, `totalInterFrameDelay`, and `totalSquaredInterFrameDelay` are all decoder
|
||||
// specific values and can't be produced since we aren't decoding.
|
||||
pub last_packet_received_timestamp: Option<SystemTime>,
|
||||
pub header_bytes_received: u64,
|
||||
// TODO: `packetsDiscarded`. This value only makes sense if we have jitter buffer, which we
|
||||
// cannot assume.
|
||||
// TODO: `fecPacketsReceived`, `fecPacketsDiscarded`
|
||||
pub bytes_received: u64,
|
||||
pub nack_count: u64,
|
||||
pub fir_count: Option<u64>,
|
||||
pub pli_count: Option<u64>,
|
||||
// NB: `totalProcessingDelay`, `estimatedPlayoutTimestamp`, `jitterBufferDelay`,
|
||||
// `jitterBufferTargetDelay`, `jitterBufferEmittedCount`, `jitterBufferMinimumDelay`,
|
||||
// `totalSamplesReceived`, `concealedSamples`, `silentConcealedSamples`, `concealmentEvents`,
|
||||
// `insertedSamplesForDeceleration`, `removedSamplesForAcceleration`, `audioLevel`,
|
||||
// `totalAudioEneregy`, `totalSampleDuration`, `framesReceived, and `decoderImplementation` are
|
||||
// all decoder specific and can't be produced since we aren't decoding.
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct OutboundRTPStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCRtpStreamStats
|
||||
pub ssrc: SSRC,
|
||||
pub kind: &'static str, // Either "video" or "audio"
|
||||
// TODO: Add transportId
|
||||
// TODO: Add codecId
|
||||
|
||||
// RTCSentRtpStreamStats
|
||||
pub packets_sent: u64,
|
||||
pub bytes_sent: u64,
|
||||
|
||||
// RTCOutboundRtpStreamStats
|
||||
// NB: non-canon in browsers this is available via `RTCMediaSourceStats` which we are unlikely to implement
|
||||
pub track_identifier: String,
|
||||
pub mid: SmolStr,
|
||||
// TODO: `mediaSourceId` and `remoteId`
|
||||
pub rid: Option<SmolStr>,
|
||||
pub header_bytes_sent: u64,
|
||||
// TODO: `retransmittedPacketsSent` and `retransmittedPacketsSent`
|
||||
// NB: `targetBitrate`, `totalEncodedBytesTarget`, `frameWidth` `frameHeight`, `framesPerSecond`, `framesSent`,
|
||||
// `hugeFramesSent`, `framesEncoded`, `keyFramesEncoded`, `qpSum`, and `totalEncodeTime` are
|
||||
// all encoder specific and can't be produced snce we aren't encoding.
|
||||
// TODO: `totalPacketSendDelay` time from `TrackLocalWriter::write_rtp` to being written to
|
||||
// socket.
|
||||
|
||||
// NB: `qualityLimitationReason`, `qualityLimitationDurations`, and `qualityLimitationResolutionChanges` are all
|
||||
// encoder specific and can't be produced since we aren't encoding.
|
||||
pub nack_count: u64,
|
||||
pub fir_count: Option<u64>,
|
||||
pub pli_count: Option<u64>,
|
||||
// NB: `encoderImplementation` is encoder specific and can't be produced since we aren't
|
||||
// encoding.
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteInboundRTPStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCRtpStreamStats
|
||||
pub ssrc: SSRC,
|
||||
pub kind: &'static str, // Either "video" or "audio"
|
||||
// TODO: Add transportId
|
||||
// TODO: Add codecId
|
||||
|
||||
// RTCReceivedRtpStreamStats
|
||||
pub packets_received: u64,
|
||||
pub packets_lost: i64,
|
||||
// TODO: jitter(maybe, might be uattainable for the same reason as `framesDropped`)
|
||||
// NB: `framesDropped` can't be produced since we aren't decoding, might be worth introducing a
|
||||
// way for consumers to control this in the future.
|
||||
|
||||
// RTCRemoteInboundRtpStreamStats
|
||||
pub local_id: String,
|
||||
pub round_trip_time: Option<f64>,
|
||||
pub total_round_trip_time: f64,
|
||||
pub fraction_lost: f64,
|
||||
pub round_trip_time_measurements: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RemoteOutboundRTPStats {
|
||||
// RTCStats
|
||||
#[serde(with = "serialize::instant_to_epoch_seconds")]
|
||||
pub timestamp: Instant,
|
||||
#[serde(rename = "type")]
|
||||
pub stats_type: RTCStatsType,
|
||||
pub id: String,
|
||||
|
||||
// RTCRtpStreamStats
|
||||
pub ssrc: SSRC,
|
||||
pub kind: &'static str, // Either "video" or "audio"
|
||||
// TODO: Add transportId
|
||||
// TODO: Add codecId
|
||||
|
||||
// RTCSentRtpStreamStats
|
||||
pub packets_sent: u64,
|
||||
pub bytes_sent: u64,
|
||||
|
||||
// RTCRemoteOutboundRtpStreamStats
|
||||
pub local_id: String,
|
||||
// TODO: `remote_timestamp`
|
||||
pub round_trip_time: Option<f64>,
|
||||
pub reports_sent: u64,
|
||||
pub total_round_trip_time: f64,
|
||||
pub round_trip_time_measurements: u64,
|
||||
}
|
||||
Vendored
+28
@@ -0,0 +1,28 @@
|
||||
pub mod instant_to_epoch_seconds {
|
||||
// Serializes a `tokio::time::Instant` to an approximation of epoch time in the form
|
||||
// of an `f64` where the integer portion is seconds and the decimal portion is milliseconds.
|
||||
// For instance, `Monday, May 30, 2022 10:45:26.456 PM UTC` converts to `1653950726.456`.
|
||||
//
|
||||
// Note that an `Instant` is not connected to real world time, so this conversion is
|
||||
// approximate.
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use serde::{Serialize, Serializer};
|
||||
use tokio::time::Instant;
|
||||
|
||||
pub fn serialize<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
S: Serializer,
|
||||
{
|
||||
let system_now = SystemTime::now();
|
||||
let instant_now = Instant::now();
|
||||
let approx = system_now - (instant_now - *instant);
|
||||
let epoch = approx
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.expect("Time went backwards");
|
||||
|
||||
let epoch_ms = epoch.as_millis() as f64 / 1000.0;
|
||||
|
||||
epoch_ms.serialize(serializer)
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use util::sync::Mutex;
|
||||
|
||||
use super::StatsReportType;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct StatsCollector {
|
||||
pub(crate) reports: Mutex<HashMap<String, StatsReportType>>,
|
||||
}
|
||||
|
||||
impl StatsCollector {
|
||||
pub(crate) fn new() -> Self {
|
||||
StatsCollector {
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn insert(&self, id: String, stats: StatsReportType) {
|
||||
let mut reports = self.reports.lock();
|
||||
reports.insert(id, stats);
|
||||
}
|
||||
|
||||
pub(crate) fn merge(&self, stats: HashMap<String, StatsReportType>) {
|
||||
let mut reports = self.reports.lock();
|
||||
reports.extend(stats)
|
||||
}
|
||||
|
||||
pub(crate) fn into_reports(self) -> HashMap<String, StatsReportType> {
|
||||
self.reports.into_inner()
|
||||
}
|
||||
}
|
||||
Vendored
+29
@@ -0,0 +1,29 @@
|
||||
pub mod track_local;
|
||||
pub mod track_remote;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use interceptor::stream_info::StreamInfo;
|
||||
use interceptor::{RTCPReader, RTPReader};
|
||||
use track_remote::*;
|
||||
|
||||
pub(crate) const RTP_OUTBOUND_MTU: usize = 1200;
|
||||
pub(crate) const RTP_PAYLOAD_TYPE_BITMASK: u8 = 0x7F;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TrackStream {
|
||||
pub(crate) stream_info: Option<StreamInfo>,
|
||||
pub(crate) rtp_read_stream: Option<Arc<srtp::stream::Stream>>,
|
||||
pub(crate) rtp_interceptor: Option<Arc<dyn RTPReader + Send + Sync>>,
|
||||
pub(crate) rtcp_read_stream: Option<Arc<srtp::stream::Stream>>,
|
||||
pub(crate) rtcp_interceptor: Option<Arc<dyn RTCPReader + Send + Sync>>,
|
||||
}
|
||||
|
||||
/// TrackStreams maintains a mapping of RTP/RTCP streams to a specific track
|
||||
/// a RTPReceiver may contain multiple streams if we are dealing with Simulcast
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct TrackStreams {
|
||||
pub(crate) track: Arc<TrackRemote>,
|
||||
pub(crate) stream: TrackStream,
|
||||
pub(crate) repair_stream: TrackStream,
|
||||
}
|
||||
+163
@@ -0,0 +1,163 @@
|
||||
#[cfg(test)]
|
||||
mod track_local_static_test;
|
||||
|
||||
pub mod track_local_static_rtp;
|
||||
pub mod track_local_static_sample;
|
||||
|
||||
use std::any::Any;
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::Arc;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use interceptor::{Attributes, RTPWriter};
|
||||
use tokio::sync::Mutex;
|
||||
use util::Unmarshal;
|
||||
|
||||
use crate::error::{Error, Result};
|
||||
use crate::rtp_transceiver::rtp_codec::*;
|
||||
use crate::rtp_transceiver::*;
|
||||
|
||||
/// TrackLocalWriter is the Writer for outbound RTP Packets
|
||||
#[async_trait]
|
||||
pub trait TrackLocalWriter: fmt::Debug {
|
||||
/// write_rtp encrypts a RTP packet and writes to the connection
|
||||
async fn write_rtp(&self, p: &rtp::packet::Packet) -> Result<usize>;
|
||||
|
||||
/// write encrypts and writes a full RTP packet
|
||||
async fn write(&self, b: &[u8]) -> Result<usize>;
|
||||
}
|
||||
|
||||
/// TrackLocalContext is the Context passed when a TrackLocal has been Binded/Unbinded from a PeerConnection, and used
|
||||
/// in Interceptors.
|
||||
#[derive(Default, Debug, Clone)]
|
||||
pub struct TrackLocalContext {
|
||||
pub(crate) id: String,
|
||||
pub(crate) params: RTCRtpParameters,
|
||||
pub(crate) ssrc: SSRC,
|
||||
pub(crate) write_stream: Option<Arc<dyn TrackLocalWriter + Send + Sync>>,
|
||||
pub(crate) paused: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl TrackLocalContext {
|
||||
/// codec_parameters returns the negotiated RTPCodecParameters. These are the codecs supported by both
|
||||
/// PeerConnections and the SSRC/PayloadTypes
|
||||
pub fn codec_parameters(&self) -> &[RTCRtpCodecParameters] {
|
||||
&self.params.codecs
|
||||
}
|
||||
|
||||
/// header_extensions returns the negotiated RTPHeaderExtensionParameters. These are the header extensions supported by
|
||||
/// both PeerConnections and the SSRC/PayloadTypes
|
||||
pub fn header_extensions(&self) -> &[RTCRtpHeaderExtensionParameters] {
|
||||
&self.params.header_extensions
|
||||
}
|
||||
|
||||
/// ssrc requires the negotiated SSRC of this track
|
||||
/// This track may have multiple if RTX is enabled
|
||||
pub fn ssrc(&self) -> SSRC {
|
||||
self.ssrc
|
||||
}
|
||||
|
||||
/// write_stream returns the write_stream for this TrackLocal. The implementer writes the outbound
|
||||
/// media packets to it
|
||||
pub fn write_stream(&self) -> Option<Arc<dyn TrackLocalWriter + Send + Sync>> {
|
||||
self.write_stream.clone()
|
||||
}
|
||||
|
||||
/// id is a unique identifier that is used for both bind/unbind
|
||||
pub fn id(&self) -> String {
|
||||
self.id.clone()
|
||||
}
|
||||
}
|
||||
/// TrackLocal is an interface that controls how the user can send media
|
||||
/// The user can provide their own TrackLocal implementations, or use
|
||||
/// the implementations in pkg/media
|
||||
#[async_trait]
|
||||
pub trait TrackLocal {
|
||||
/// bind should implement the way how the media data flows from the Track to the PeerConnection
|
||||
/// This will be called internally after signaling is complete and the list of available
|
||||
/// codecs has been determined
|
||||
async fn bind(&self, t: &TrackLocalContext) -> Result<RTCRtpCodecParameters>;
|
||||
|
||||
/// unbind should implement the teardown logic when the track is no longer needed. This happens
|
||||
/// because a track has been stopped.
|
||||
async fn unbind(&self, t: &TrackLocalContext) -> Result<()>;
|
||||
|
||||
/// id is the unique identifier for this Track. This should be unique for the
|
||||
/// stream, but doesn't have to globally unique. A common example would be 'audio' or 'video'
|
||||
/// and stream_id would be 'desktop' or 'webcam'
|
||||
fn id(&self) -> &str;
|
||||
|
||||
/// stream_id is the group this track belongs too. This must be unique
|
||||
fn stream_id(&self) -> &str;
|
||||
|
||||
/// kind controls if this TrackLocal is audio or video
|
||||
fn kind(&self) -> RTPCodecType;
|
||||
|
||||
fn as_any(&self) -> &dyn Any;
|
||||
}
|
||||
|
||||
/// TrackBinding is a single bind for a Track
|
||||
/// Bind can be called multiple times, this stores the
|
||||
/// result for a single bind call so that it can be used when writing
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct TrackBinding {
|
||||
id: String,
|
||||
ssrc: SSRC,
|
||||
payload_type: PayloadType,
|
||||
params: RTCRtpParameters,
|
||||
write_stream: Option<Arc<dyn TrackLocalWriter + Send + Sync>>,
|
||||
sender_paused: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl TrackBinding {
|
||||
pub fn is_sender_paused(&self) -> bool {
|
||||
self.sender_paused.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct InterceptorToTrackLocalWriter {
|
||||
pub(crate) interceptor_rtp_writer: Mutex<Option<Arc<dyn RTPWriter + Send + Sync>>>,
|
||||
sender_paused: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
impl InterceptorToTrackLocalWriter {
|
||||
pub(crate) fn new(paused: Arc<AtomicBool>) -> Self {
|
||||
InterceptorToTrackLocalWriter {
|
||||
interceptor_rtp_writer: Mutex::new(None),
|
||||
sender_paused: paused,
|
||||
}
|
||||
}
|
||||
|
||||
fn is_sender_paused(&self) -> bool {
|
||||
self.sender_paused.load(Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for InterceptorToTrackLocalWriter {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("InterceptorToTrackLocalWriter").finish()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TrackLocalWriter for InterceptorToTrackLocalWriter {
|
||||
async fn write_rtp(&self, pkt: &rtp::packet::Packet) -> Result<usize> {
|
||||
if self.is_sender_paused() {
|
||||
return Ok(0);
|
||||
}
|
||||
|
||||
let interceptor_rtp_writer = self.interceptor_rtp_writer.lock().await;
|
||||
if let Some(writer) = &*interceptor_rtp_writer {
|
||||
let a = Attributes::new();
|
||||
Ok(writer.write(pkt, &a).await?)
|
||||
} else {
|
||||
Ok(0)
|
||||
}
|
||||
}
|
||||
|
||||
async fn write(&self, mut b: &[u8]) -> Result<usize> {
|
||||
let pkt = rtp::packet::Packet::unmarshal(&mut b)?;
|
||||
self.write_rtp(&pkt).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,238 @@
|
||||
use std::collections::HashMap;
|
||||
|
||||
use bytes::BytesMut;
|
||||
use tokio::sync::Mutex;
|
||||
use util::{Marshal, MarshalSize};
|
||||
|
||||
use super::*;
|
||||
use crate::error::flatten_errs;
|
||||
|
||||
/// TrackLocalStaticRTP is a TrackLocal that has a pre-set codec and accepts RTP Packets.
|
||||
/// If you wish to send a media.Sample use TrackLocalStaticSample
|
||||
#[derive(Debug)]
|
||||
pub struct TrackLocalStaticRTP {
|
||||
pub(crate) bindings: Mutex<Vec<Arc<TrackBinding>>>,
|
||||
codec: RTCRtpCodecCapability,
|
||||
id: String,
|
||||
stream_id: String,
|
||||
}
|
||||
|
||||
impl TrackLocalStaticRTP {
|
||||
/// returns a TrackLocalStaticRTP.
|
||||
pub fn new(codec: RTCRtpCodecCapability, id: String, stream_id: String) -> Self {
|
||||
TrackLocalStaticRTP {
|
||||
codec,
|
||||
bindings: Mutex::new(vec![]),
|
||||
id,
|
||||
stream_id,
|
||||
}
|
||||
}
|
||||
|
||||
/// codec gets the Codec of the track
|
||||
pub fn codec(&self) -> RTCRtpCodecCapability {
|
||||
self.codec.clone()
|
||||
}
|
||||
|
||||
pub async fn any_binding_paused(&self) -> bool {
|
||||
let bindings = self.bindings.lock().await;
|
||||
bindings
|
||||
.iter()
|
||||
.any(|b| b.sender_paused.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
pub async fn all_binding_paused(&self) -> bool {
|
||||
let bindings = self.bindings.lock().await;
|
||||
bindings
|
||||
.iter()
|
||||
.all(|b| b.sender_paused.load(Ordering::SeqCst))
|
||||
}
|
||||
|
||||
/// write_rtp_with_extensions writes a RTP Packet to the TrackLocalStaticRTP
|
||||
/// If one PeerConnection fails the packets will still be sent to
|
||||
/// all PeerConnections. The error message will contain the ID of the failed
|
||||
/// PeerConnections so you can remove them
|
||||
///
|
||||
/// If the RTCRtpSender direction is such that no packets should be sent, any call to this
|
||||
/// function are blocked internally. Care must be taken to not increase the sequence number
|
||||
/// while the sender is paused. While the actual _sending_ is blocked, the receiver will
|
||||
/// miss out when the sequence number "rolls over", which in turn will break SRTP.
|
||||
///
|
||||
/// Extensions that are already configured on the packet are overwritten by extensions in
|
||||
/// `extensions`.
|
||||
pub async fn write_rtp_with_extensions(
|
||||
&self,
|
||||
p: &rtp::packet::Packet,
|
||||
extensions: &[rtp::extension::HeaderExtension],
|
||||
) -> Result<usize> {
|
||||
let mut n = 0;
|
||||
let mut write_errs = vec![];
|
||||
let mut pkt = p.clone();
|
||||
|
||||
let bindings = {
|
||||
let bindings = self.bindings.lock().await;
|
||||
bindings.clone()
|
||||
};
|
||||
// Prepare the extensions data
|
||||
let extension_data: HashMap<_, _> = extensions
|
||||
.iter()
|
||||
.flat_map(|extension| {
|
||||
let buf = {
|
||||
let mut buf = BytesMut::with_capacity(extension.marshal_size());
|
||||
buf.resize(extension.marshal_size(), 0);
|
||||
if let Err(err) = extension.marshal_to(&mut buf) {
|
||||
write_errs.push(Error::Util(err));
|
||||
return None;
|
||||
}
|
||||
|
||||
buf.freeze()
|
||||
};
|
||||
|
||||
Some((extension.uri(), buf))
|
||||
})
|
||||
.collect();
|
||||
|
||||
for b in bindings.into_iter() {
|
||||
if b.is_sender_paused() {
|
||||
// See caveat in function doc.
|
||||
continue;
|
||||
}
|
||||
pkt.header.ssrc = b.ssrc;
|
||||
pkt.header.payload_type = b.payload_type;
|
||||
|
||||
for (uri, data) in extension_data.iter() {
|
||||
if let Some(id) = b
|
||||
.params
|
||||
.header_extensions
|
||||
.iter()
|
||||
.find(|ext| &ext.uri == uri)
|
||||
.map(|ext| ext.id)
|
||||
{
|
||||
if let Err(err) = pkt.header.set_extension(id as u8, data.clone()) {
|
||||
write_errs.push(Error::Rtp(err));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(write_stream) = &b.write_stream {
|
||||
match write_stream.write_rtp(&pkt).await {
|
||||
Ok(m) => {
|
||||
n += m;
|
||||
}
|
||||
Err(err) => {
|
||||
write_errs.push(err);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
write_errs.push(Error::new("track binding has none write_stream".to_owned()));
|
||||
}
|
||||
}
|
||||
|
||||
flatten_errs(write_errs)?;
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TrackLocal for TrackLocalStaticRTP {
|
||||
/// bind is called by the PeerConnection after negotiation is complete
|
||||
/// This asserts that the code requested is supported by the remote peer.
|
||||
/// If so it setups all the state (SSRC and PayloadType) to have a call
|
||||
async fn bind(&self, t: &TrackLocalContext) -> Result<RTCRtpCodecParameters> {
|
||||
let parameters = RTCRtpCodecParameters {
|
||||
capability: self.codec.clone(),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let (codec, match_type) = codec_parameters_fuzzy_search(¶meters, t.codec_parameters());
|
||||
if match_type != CodecMatch::None {
|
||||
{
|
||||
let mut bindings = self.bindings.lock().await;
|
||||
bindings.push(Arc::new(TrackBinding {
|
||||
ssrc: t.ssrc(),
|
||||
payload_type: codec.payload_type,
|
||||
write_stream: t.write_stream(),
|
||||
params: t.params.clone(),
|
||||
id: t.id(),
|
||||
sender_paused: t.paused.clone(),
|
||||
}));
|
||||
}
|
||||
|
||||
Ok(codec)
|
||||
} else {
|
||||
Err(Error::ErrUnsupportedCodec)
|
||||
}
|
||||
}
|
||||
|
||||
/// unbind implements the teardown logic when the track is no longer needed. This happens
|
||||
/// because a track has been stopped.
|
||||
async fn unbind(&self, t: &TrackLocalContext) -> Result<()> {
|
||||
let mut bindings = self.bindings.lock().await;
|
||||
let mut idx = None;
|
||||
for (index, binding) in bindings.iter().enumerate() {
|
||||
if binding.id == t.id() {
|
||||
idx = Some(index);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(index) = idx {
|
||||
bindings.remove(index);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(Error::ErrUnbindFailed)
|
||||
}
|
||||
}
|
||||
|
||||
/// id is the unique identifier for this Track. This should be unique for the
|
||||
/// stream, but doesn't have to globally unique. A common example would be 'audio' or 'video'
|
||||
/// and StreamID would be 'desktop' or 'webcam'
|
||||
fn id(&self) -> &str {
|
||||
self.id.as_str()
|
||||
}
|
||||
|
||||
/// stream_id is the group this track belongs too. This must be unique
|
||||
fn stream_id(&self) -> &str {
|
||||
self.stream_id.as_str()
|
||||
}
|
||||
|
||||
/// kind controls if this TrackLocal is audio or video
|
||||
fn kind(&self) -> RTPCodecType {
|
||||
if self.codec.mime_type.starts_with("audio/") {
|
||||
RTPCodecType::Audio
|
||||
} else if self.codec.mime_type.starts_with("video/") {
|
||||
RTPCodecType::Video
|
||||
} else {
|
||||
RTPCodecType::Unspecified
|
||||
}
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TrackLocalWriter for TrackLocalStaticRTP {
|
||||
/// write_rtp writes a RTP Packet to the TrackLocalStaticRTP
|
||||
/// If one PeerConnection fails the packets will still be sent to
|
||||
/// all PeerConnections. The error message will contain the ID of the failed
|
||||
/// PeerConnections so you can remove them
|
||||
///
|
||||
/// If the RTCRtpSender direction is such that no packets should be sent, any call to this
|
||||
/// function are blocked internally. Care must be taken to not increase the sequence number
|
||||
/// while the sender is paused. While the actual _sending_ is blocked, the receiver will
|
||||
/// miss out when the sequence number "rolls over", which in turn will break SRTP.
|
||||
async fn write_rtp(&self, p: &rtp::packet::Packet) -> Result<usize> {
|
||||
self.write_rtp_with_extensions(p, &[]).await
|
||||
}
|
||||
|
||||
/// write writes a RTP Packet as a buffer to the TrackLocalStaticRTP
|
||||
/// If one PeerConnection fails the packets will still be sent to
|
||||
/// all PeerConnections. The error message will contain the ID of the failed
|
||||
/// PeerConnections so you can remove them
|
||||
async fn write(&self, mut b: &[u8]) -> Result<usize> {
|
||||
let pkt = rtp::packet::Packet::unmarshal(&mut b)?;
|
||||
self.write_rtp(&pkt).await?;
|
||||
Ok(b.len())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
use log::warn;
|
||||
use media::Sample;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use super::track_local_static_rtp::TrackLocalStaticRTP;
|
||||
use super::*;
|
||||
use crate::error::flatten_errs;
|
||||
use crate::track::RTP_OUTBOUND_MTU;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct TrackLocalStaticSampleInternal {
|
||||
packetizer: Option<Box<dyn rtp::packetizer::Packetizer + Send + Sync>>,
|
||||
sequencer: Option<Box<dyn rtp::sequence::Sequencer + Send + Sync>>,
|
||||
clock_rate: f64,
|
||||
did_warn_about_wonky_pause: bool,
|
||||
}
|
||||
|
||||
/// TrackLocalStaticSample is a TrackLocal that has a pre-set codec and accepts Samples.
|
||||
/// If you wish to send a RTP Packet use TrackLocalStaticRTP
|
||||
#[derive(Debug)]
|
||||
pub struct TrackLocalStaticSample {
|
||||
rtp_track: TrackLocalStaticRTP,
|
||||
internal: Mutex<TrackLocalStaticSampleInternal>,
|
||||
}
|
||||
|
||||
impl TrackLocalStaticSample {
|
||||
/// returns a TrackLocalStaticSample
|
||||
pub fn new(codec: RTCRtpCodecCapability, id: String, stream_id: String) -> Self {
|
||||
let rtp_track = TrackLocalStaticRTP::new(codec, id, stream_id);
|
||||
|
||||
TrackLocalStaticSample {
|
||||
rtp_track,
|
||||
internal: Mutex::new(TrackLocalStaticSampleInternal {
|
||||
packetizer: None,
|
||||
sequencer: None,
|
||||
clock_rate: 0.0f64,
|
||||
did_warn_about_wonky_pause: false,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// codec gets the Codec of the track
|
||||
pub fn codec(&self) -> RTCRtpCodecCapability {
|
||||
self.rtp_track.codec()
|
||||
}
|
||||
|
||||
/// write_sample writes a Sample to the TrackLocalStaticSample
|
||||
/// If one PeerConnection fails the packets will still be sent to
|
||||
/// all PeerConnections. The error message will contain the ID of the failed
|
||||
/// PeerConnections so you can remove them
|
||||
pub async fn write_sample(&self, sample: &Sample) -> Result<()> {
|
||||
self.write_sample_with_extensions(sample, &[]).await
|
||||
}
|
||||
|
||||
/// Write a sample with provided RTP extensions.
|
||||
///
|
||||
/// Alternatively to this method [`TrackLocalStaticSample::sample_writer`] can be used instead.
|
||||
///
|
||||
/// See [`TrackLocalStaticSample::write_sample`] for further details.
|
||||
pub async fn write_sample_with_extensions(
|
||||
&self,
|
||||
sample: &Sample,
|
||||
extensions: &[rtp::extension::HeaderExtension],
|
||||
) -> Result<()> {
|
||||
let mut internal = self.internal.lock().await;
|
||||
|
||||
if internal.packetizer.is_none() || internal.sequencer.is_none() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let (any_paused, all_paused) = (
|
||||
self.rtp_track.any_binding_paused().await,
|
||||
self.rtp_track.all_binding_paused().await,
|
||||
);
|
||||
|
||||
if all_paused {
|
||||
// Abort already here to not increment sequence numbers.
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
if any_paused {
|
||||
// This is a problem state due to how this impl is structured. The sequencer will allocate
|
||||
// one sequence number per RTP packet regardless of how many TrackBinding that will send
|
||||
// the packet. I.e. we get the same sequence number per multiple SSRC, which is not good
|
||||
// for SRTP, but that's how it works.
|
||||
//
|
||||
// SRTP has a further problem with regards to jumps in sequence number. Consider this:
|
||||
//
|
||||
// 1. Create track local
|
||||
// 2. Bind track local to track 1.
|
||||
// 3. Bind track local to track 2.
|
||||
// 4. Pause track 1.
|
||||
// 5. Keep sending...
|
||||
//
|
||||
// At this point, the track local will keep incrementing the sequence number, because we have
|
||||
// one binding that is still active. However SRTP hmac verifying (tag), can only accept a
|
||||
// relatively small jump in sequence numbers since it uses the ROC (i.e. how many times the
|
||||
// sequence number has rolled over), which means if this pause state of one binding persists
|
||||
// for a longer time, the track can never be resumed since the receiver would have missed
|
||||
// the rollovers.
|
||||
if !internal.did_warn_about_wonky_pause {
|
||||
internal.did_warn_about_wonky_pause = true;
|
||||
warn!("Detected multiple track bindings where only one was paused");
|
||||
}
|
||||
}
|
||||
|
||||
// skip packets by the number of previously dropped packets
|
||||
if let Some(sequencer) = &internal.sequencer {
|
||||
for _ in 0..sample.prev_dropped_packets {
|
||||
sequencer.next_sequence_number();
|
||||
}
|
||||
}
|
||||
|
||||
let clock_rate = internal.clock_rate;
|
||||
|
||||
let packets = if let Some(packetizer) = &mut internal.packetizer {
|
||||
let samples = (sample.duration.as_secs_f64() * clock_rate) as u32;
|
||||
if sample.prev_dropped_packets > 0 {
|
||||
packetizer.skip_samples(samples * sample.prev_dropped_packets as u32);
|
||||
}
|
||||
packetizer.packetize(&sample.data, samples)?
|
||||
} else {
|
||||
vec![]
|
||||
};
|
||||
|
||||
let mut write_errs = vec![];
|
||||
for p in packets {
|
||||
if let Err(err) = self
|
||||
.rtp_track
|
||||
.write_rtp_with_extensions(&p, extensions)
|
||||
.await
|
||||
{
|
||||
write_errs.push(err);
|
||||
}
|
||||
}
|
||||
|
||||
flatten_errs(write_errs)
|
||||
}
|
||||
|
||||
/// Create a builder for writing samples with additional data.
|
||||
///
|
||||
/// # Example
|
||||
/// ```no_run
|
||||
/// use rtp::extension::audio_level_extension::AudioLevelExtension;
|
||||
/// use std::time::Duration;
|
||||
/// use webrtc::api::media_engine::MIME_TYPE_VP8;
|
||||
/// use webrtc::rtp_transceiver::rtp_codec::RTCRtpCodecCapability;
|
||||
/// use webrtc::track::track_local::track_local_static_sample::TrackLocalStaticSample;
|
||||
///
|
||||
/// #[tokio::main]
|
||||
/// async fn main() {
|
||||
/// let track = TrackLocalStaticSample::new(
|
||||
/// RTCRtpCodecCapability {
|
||||
/// mime_type: MIME_TYPE_VP8.to_owned(),
|
||||
/// ..Default::default()
|
||||
/// },
|
||||
/// "video".to_owned(),
|
||||
/// "webrtc-rs".to_owned(),
|
||||
/// );
|
||||
/// let result = track
|
||||
/// .sample_writer()
|
||||
/// .with_audio_level(AudioLevelExtension {
|
||||
/// level: 10,
|
||||
/// voice: true,
|
||||
/// })
|
||||
/// .write_sample(&media::Sample{
|
||||
/// data: bytes::Bytes::new(),
|
||||
/// duration: Duration::from_secs(1),
|
||||
/// ..Default::default()
|
||||
/// })
|
||||
/// .await;
|
||||
/// }
|
||||
/// ```
|
||||
pub fn sample_writer(&self) -> SampleWriter<'_> {
|
||||
SampleWriter::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TrackLocal for TrackLocalStaticSample {
|
||||
/// Bind is called by the PeerConnection after negotiation is complete
|
||||
/// This asserts that the code requested is supported by the remote peer.
|
||||
/// If so it setups all the state (SSRC and PayloadType) to have a call
|
||||
async fn bind(&self, t: &TrackLocalContext) -> Result<RTCRtpCodecParameters> {
|
||||
let codec = self.rtp_track.bind(t).await?;
|
||||
|
||||
let mut internal = self.internal.lock().await;
|
||||
|
||||
// We only need one packetizer
|
||||
if internal.packetizer.is_some() {
|
||||
return Ok(codec);
|
||||
}
|
||||
|
||||
let payloader = codec.capability.payloader_for_codec()?;
|
||||
let sequencer: Box<dyn rtp::sequence::Sequencer + Send + Sync> =
|
||||
Box::new(rtp::sequence::new_random_sequencer());
|
||||
internal.packetizer = Some(Box::new(rtp::packetizer::new_packetizer(
|
||||
RTP_OUTBOUND_MTU,
|
||||
0, // Value is handled when writing
|
||||
0, // Value is handled when writing
|
||||
payloader,
|
||||
sequencer.clone(),
|
||||
codec.capability.clock_rate,
|
||||
)));
|
||||
internal.sequencer = Some(sequencer);
|
||||
internal.clock_rate = codec.capability.clock_rate as f64;
|
||||
|
||||
Ok(codec)
|
||||
}
|
||||
|
||||
/// unbind implements the teardown logic when the track is no longer needed. This happens
|
||||
/// because a track has been stopped.
|
||||
async fn unbind(&self, t: &TrackLocalContext) -> Result<()> {
|
||||
self.rtp_track.unbind(t).await
|
||||
}
|
||||
|
||||
/// id is the unique identifier for this Track. This should be unique for the
|
||||
/// stream, but doesn't have to globally unique. A common example would be 'audio' or 'video'
|
||||
/// and StreamID would be 'desktop' or 'webcam'
|
||||
fn id(&self) -> &str {
|
||||
self.rtp_track.id()
|
||||
}
|
||||
|
||||
/// stream_id is the group this track belongs too. This must be unique
|
||||
fn stream_id(&self) -> &str {
|
||||
self.rtp_track.stream_id()
|
||||
}
|
||||
|
||||
/// kind controls if this TrackLocal is audio or video
|
||||
fn kind(&self) -> RTPCodecType {
|
||||
self.rtp_track.kind()
|
||||
}
|
||||
|
||||
fn as_any(&self) -> &dyn Any {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
mod sample_writer {
|
||||
use media::Sample;
|
||||
use rtp::extension::audio_level_extension::AudioLevelExtension;
|
||||
use rtp::extension::video_orientation_extension::VideoOrientationExtension;
|
||||
use rtp::extension::HeaderExtension;
|
||||
|
||||
use super::TrackLocalStaticSample;
|
||||
use crate::error::Result;
|
||||
|
||||
/// Helper for writing Samples via [`TrackLocalStaticSample`] that carry extra RTP data.
|
||||
///
|
||||
/// Created via [`TrackLocalStaticSample::sample_writer`].
|
||||
pub struct SampleWriter<'track> {
|
||||
track: &'track TrackLocalStaticSample,
|
||||
extensions: Vec<HeaderExtension>,
|
||||
}
|
||||
|
||||
impl<'track> SampleWriter<'track> {
|
||||
pub(super) fn new(track: &'track TrackLocalStaticSample) -> Self {
|
||||
Self {
|
||||
track,
|
||||
extensions: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
/// Add a RTP audio level extension to all packets written for the sample.
|
||||
///
|
||||
/// This overwrites any previously configured audio level extension.
|
||||
pub fn with_audio_level(self, ext: AudioLevelExtension) -> Self {
|
||||
self.with_extension(HeaderExtension::AudioLevel(ext))
|
||||
}
|
||||
|
||||
/// Add a RTP video orientation extension to all packets written for the sample.
|
||||
///
|
||||
/// This overwrites any previously configured video orientation extension.
|
||||
pub fn with_video_orientation(self, ext: VideoOrientationExtension) -> Self {
|
||||
self.with_extension(HeaderExtension::VideoOrientation(ext))
|
||||
}
|
||||
|
||||
/// Add any RTP extension to all packets written for the sample.
|
||||
pub fn with_extension(mut self, ext: HeaderExtension) -> Self {
|
||||
self.extensions.retain(|e| !e.is_same(&ext));
|
||||
|
||||
self.extensions.push(ext);
|
||||
|
||||
self
|
||||
}
|
||||
|
||||
/// Write the sample to the track.
|
||||
///
|
||||
/// Creates one or more RTP packets with any extensions specified for each packet and sends
|
||||
/// them.
|
||||
pub async fn write_sample(self, sample: &Sample) -> Result<()> {
|
||||
self.track
|
||||
.write_sample_with_extensions(sample, &self.extensions)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub use sample_writer::SampleWriter;
|
||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user